text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
This action might not be possible to undo. Are you sure you want to continue? John B. Peatman Professor of Electrical and Computer Engineering Georgia Institute of Technology Qwik&Low Books 1418 Iroquois Path, NE Atlanta, GA 30319 (770) 457-6133 jpeatman@comcast.net Trademark Information: PIC, PICmicro, nanoWatt Technology, PICkit 2, MPLAB, C18, MPASM, MPLINK are trademarks of Microchip Technology Incorporated in the United States and other countries. All other trademarks mentioned in this book are property of their respective companies. The author makes no warranty of any kind, expressed or implied, with regard to the program code contained in this book. The author shall not be liable in any event arising out of the use of this program code. ISBN 978-0-9799770-0-8 987654321 This book is available as a $15.50 print-on-demand paperback book from or as a free download along with supporting material from To six former students who changed the direction of my professional life: Jim Carreker and Neal Williams 1968–1969 Joe Bazzell and Larry Madar 1989–1990 Rawin Rojvanit and Chris Twigg 2001–2002 CONTENTS Preface 7 Chapter 1 1.1 1.2 1.3 1.4 1.5 1.6 Chapter 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 Chapter 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 Chapter 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 Introduction 13 Low-Power Designs 13 The Learning Curve 14 The PIC18LF4321 Microcontroller 15 The PIC18LF6390 LCD Controller 15 QwikBug Development Environment 17 Programming with the PICkit 2 Programmer 17 Low-Power Operation 18 Overview 18 CR2032 Coin Cell 18 A PIC18LFXXXX Family of Microcontrollers 19 INTOSC and INTRC, the Internal Oscillators 21 Intermittent Sleep Mode Operation 21 Effect of Clock Frequency 25 User Program Steps to Reduce Current Draw 26 The Qwik&Low Board 27 Coding in C 28 Qwik&Low Board 31 Overview 31 Equipment Setup 31 Input/Output Peripheral Power 33 Power Switching and Current Monitoring PICkit 2 Programmer Connection 35 Effect of Coin Cell Aging 37 Watch Crystal Circuitry 38 Qwik&Low LCD 38 Expansion Header 40 Summary of MCU Pin Use 40 A First Template Program (T1.c) 43 Overview 43 A T1.c Template Program 43 Configuration Selections 47 Global Variables 50 Bit Manipulations 50 Function Prototypes 51 A Calibrated Delay Macro 51 Main Function 52 8-bit and 16-bit Registers 53 Clock Rate Choice 53 Analog Pins Versus Digital I/O Pins 54 Digital Inputs Versus Outputs 54 Brownout Module Disabling 54 Main Loop 55 Compilation 56 Problems 57 SPI Bus and the LCD (T2.c) 58 Overview 58 Serial Peripheral Interface 58 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 Display Strings 61 Displayable Characters 62 Decimal Point 62 T2.c, A Display Template 63 Initialization of Two Microcontrollers 68 SPI Initialization 68 The Display Function and LCDSTRING 68 The Time Function 69 The Pushbutton Function 69 Problems 70 PC Monitor Use (Measure.c) 71 Overview 71 Waveforms and Baud-rate Accuracy 72 UART’s TX Circuitry and Use 76 UART Initialization 76 TXascii Macro 78 Number-to-ASCII Conversion 78 Measure.c, a Cycle Counting Program 80 Problems 88 Reorganization of Timing Via Interrupts (T3.c) 89 Overview 89 Low- and High-Priority Interrupts 89 Interrupts and the C18 Compiler 91 Timer1 Oscillator 91 Timer1 Counter 94 Timer3 Counter 96 The T3.c Template Program 96 Problems 96 Stepper Motor Control 107 Overview 107 Stepper-Motor Operation 107 Bipolar Versus Unipolar Stepper Motors 111 Stepper-Motor Driver 112 Stepping 115 Problems 116 Analog-To-Digital Converter 119 Overview 119 Qwik&Low Analog Versus Digital Pins 119 ADC Result Alternatives 122 Reference Voltage Choice 123 ADC Timing 123 ADC Input Selection and Conversion 125 ADC Conversion During Sleep 126 AD22103 Temperature Sensor 127 Problems 132 Rotary Pulse Generator (RPG.c) Overview 133 RPG Resolution 133 RPG Functionality 134 133 Chapter 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 35 Chapter 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 Chapter 8 8.1 8.2 8.3 8.4 8.5 Chapter 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 Chapter 5 5.1 5.2 Chapter 10 10.1 10.2 10.3 4 Contents 5 10.4 10.5 The RPG Function 136 The Detented RPG 138 Problems 149 Measurements 150 Overview 150 Code Size 150 Code Execution 153 Variable Code Execution 153 Interrupt Timing Measurement 155 Time Spent Doing Useful Work in Main Loop Cleaning Up Surprises 156 Problems 157 Interrupts 159 Overview 159 MCU Interrupt Response 159 Compiler Handling of Interrupts 160 Using One Priority Level Only 163 PIC18LF4321 Interrupt Sources 165 Use of the Interrupt Mechanism + Idle Mode External Interrupts 165 PORTB-Change Interrupts 167 Problems 168 Timing Measurements Revisited (Calibrate.c) Overview 169 Timer0 Operation 170 Internal Oscillator Calibration 173 External Time Measurement 181 Start, Stop, and Send Functions 183 Problems 183 EEPROM (EEtest.c) 187 Overview 187 EEPROM Use 187 EEPROM Registers and Functions 188 Multiple Write Sequences 191 Protecting the Write Sequence 191 EEPROM Life 198 Problems 199 1-Wire Interface (SSN.c) 201 Overview 201 Interface Circuitry 201 Writing Ones and Zeros 203 Message Protocol 204 Reading Ones and Zeros 211 Generalizing from the SSN.c Template 211 Multiple 1-Wire Devices on a Single Bus 213 DS2415 1-Wire Time Chip 215 Problems 217 Starburst Display (LCD.c) 219 Overview 219 Starburst Display Configuration 219 Chapter 11 11.1 11.2 11.3 11.4 11.5 11.6 11.7 16.3 16.4 16.5 16.6 16.7 16.8 16.9 16.10 LCD Controller Circuit 221 Multiplexed LCD Voltage Waveforms 223 LCDDATAi Register Use 224 ASCII Code to LCDDATAi Representation 225 Awakening vs. Interrupt Vectoring 229 Reception of SPI Bytes into VSTRING 229 Decimal Point 230 Data Structures 230 Problems 239 SPI for Feature Enhancement 241 Overview 241 SPI Output Functionality 242 SPI Input Functionality 245 AD5601 DAC Output 246 MOSI/MISO Terminology 249 ADT7301 SPI Temperature Sensor 251 Problems 255 156 Chapter 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 Chapter 17 17.1 17.2 17.3 17.4 17.5 17.6 165 APPENDICES 169 Appendix A1 A1.1 A1.2 A1.3 A1.4 A1.5 A1.6 A1.7 A1.8 A1.9 Appendix A2 A2.1 A2.2 A2.3 A2.4 A2.5 A2.6 A2.7 A2.8 A2.9 A2.10 A2.11 Appendix A3 Appendix A4 Index 306 QwikBug Program Debugger 256 Introduction 256 Installation 258 Graphical User Interface 262 Loading a Program 262 Program Control 264 Breakpoints 266 Watch Variables 267 Additional Features 273 Keyboard Shortcuts 276 Interpreting .Lst Files 277 Overview 277 Harvard Architecture 277 Instruction Set and Direct Addressing 279 F/W Distinction 279 Name Replacements for Operand Addresses 283 Counting Cycles 283 Flag Bits 285 Indirect Addressing of RAM Variables 286 CPU Registers 287 Indirect Addressing of Program Memory 289 Special Function Registers 289 Qwik&Low Board in Detail 293 300 Chapter 13 13.1 13.2 13.3 13.4 13.5 Chapter 14 14.1 14.2 14.3 14.4 14.5 14.6 Chapter 15 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 Chapter 16 16.1 16.2 Stepper-Motor Board In Detail For helpful purchase information. and used. electrical isolation. the student version of the compiler produces machine code that is virtually identical to that produced by the commercial version.com/purchase/. In addition.qwikandlow. For example. This book employs the Qwik&Low board. The board was designed by the author and is available as Microchip Technology's Part No. as the vehicle for the reader to carry out these explorations. is using what they call nanoWatt Technology™ features to upgrade their entire microcontroller product line by: • enhancing the feature set of an older part with new power-controlling modules and new power-sensitive operating modes. throughout the book to minimize the execution time of algorithms. see. Another goal of this book has been to provide readers with a low-cost tool for their learning. shown on the cover of this book. many of these applications can take advantage of the benefits accruing when powered from a coin cell battery. while. portability. The intent of this book is to explore how these features impact the design process and the new opportunities these features make possible. In fact. at the same time. reducing chip cost. the number one supplier of 8-bit microcontrollers in the world. • extending the supply voltage range from 5. DM183034.PREFACE The premise of this book rests on the reality that as embedded microcontrollers reach into virtually all corners of modern life. Some of these are: • • • • • small product size. 7 . enhanced design simplicity. It introduces the reader to code writing for a microcontroller using the C programming language. Microchip’s C18 compiler. is used throughout.5 V down to 2.0 V. The new parts will handle the old applications. one as a general purpose microcontroller (PIC18LF4321) and one as the controller (PIC18LF6390) for the board’s liquid crystal display. Microchip Technology. • reducing leakage current. they open the door to a wide range of new applications. Manufacturers have met this reality with low-power. reduced product cost. The board uses two Microchip PIC™ microcontrollers mounted on the under side of the board. available to anyone in the form of a free student version. extended-supply-voltage versions of their microcontroller chips. with just the few constraints introduced. QwikBug employs the same Background Debug Mode used by Microchip’s debugging tools but does so using nothing more than a serial connection (via either a serial cable or a USB-toserial adapter) to a PC.com. This is the author’s seventh textbook.lulu. More experienced C code writers find plenty to hold their interest as they explore how alternative codings of an algorithm impact the execution time of the algorithm. the same price as the author’s first textbook. the book is being made available at no cost. stopping at a breakpoint. While the reader awaits the one. the code writing is introduced via a series of template programs. the author will miss their astute help in having it reach its intended audience of professors. It is the author’s experience that this approach brings everyone along. by searching their website for Peatman. running the program. The centerpiece of this support is QwikBug. The site also lists a printed version of the book carrying the intended first printing price of $15. The book takes the route of writing application code from the outset in C. with four earlier books published by McGraw-Hill and two by Prentice Hall. stepping from one line to the next of the C source file. However. To support readers having no experience with C as well as those having extensive experience. By foregoing the fine and generous support of a commercial publisher. That is. QwikBug supports: • • • • • downloading of an application program to the Qwik&Low board. shortening the C code to implement an algorithm does not necessarily translate into faster execution of the algorithm. monitoring or changing the content of selected variables and registers. with those new to C able to “do more of the same” as they modify template programs to develop code for new lab projects. www. Preface Free supporting tools are available at the author’s website. In gratitude to the many students who have supported the author’s activities over many years.to two-week delivery of the printed edition. published by McGraw-Hill thirty-five years ago. a debugging user interface. The free download of the book is available from the print-ondemand book printer.50. a shortened execution time of an algorithm leads directly to a lowering of the average coin cell current. ABOUT THE BOOK This book will typically be used in a one-semester course at the senior level. . The issues that arise in this translation are discussed throughout the book. Code written in C does not translate in an obvious manner into the machine code executed by the microcontroller. Alternatively.qwikandlow.com. this decision has its downside. the free downloaded version can be used. With an environment in which the microcontroller sleeps (and draws only a few microamperes of current from a coin cell when it is not otherwise doing useful work). students. and professionals. it might be used at the junior level if it is deemed worthwhile to trade the increased engineering sophistication of seniors for the opportunity to follow this course with other design-oriented courses and individual project activities. Tools are included for monitoring code size and code execution time. In this chapter a stepper motor and its controller circuit draw power from their own power supply and take control inputs from the Qwik&Low board. It then goes on to convert accurate cycle count measurements into accurate microsecond measurements. a rotary encoder) to vary an input parameter to an application.k. might well be introduced before its sequential order in the book. These parts include the silicon serial number chip that gives each Qwik&Low board a unique serial number. Interrupt timing measurements are also studied. Chapters 11 and 13 provide two takes on timing measurements. It carries out the task while drawing an average current of only 6 µA. Chapter 5 extends the first template to the use of the Qwik&Low board’s liquid-crystal display. on low-power designs. with measurement results displayed on the PC monitor. Chapter 11 deals with the monitoring of the execution time of an algorithm. The Microchip compiler is “wrapped” in a c18.a. at least in rudimentary form. Chapter 7 introduces the use of interrupts to control the timing of events with counters controlled by a crystal oscillator. Chapter 8 presents an interesting digression. multiple-character. The book begins with the perspective of Steve Sanghi. 5 V displays. CEO and President of Microchip Technology. Early in the course. Chapter 6 opens the door for an application program to be tested. limited task. The appendix explains how this file can be used to understand program code execution. Chapter 15 explains the 1-wire interface protocol used by Dallas/Maxim for a family of parts. It describes how the nonvolatile EEPROM in the chip can be used to save and restore data through power disruptions. It discusses the drastic effect that alternative ways of expressing interrupt service routines in C can have on execution time. This is especially useful when code is being debugged that does not seem to do what it is intended to do. The first three chapters present an overview of the environment of the book..lst file. Chapter 13 looks at how the microcontroller’s ±2% accurate internal oscillator can be calibrated against the 32768 Hz. This illustrates the operation of a low-power chip dedicated to a specific. Chapter 12 explores in depth the chip’s full interrupt capabilities that were first introduced in Chapter 7. Chapter 16 describes the operation of the PIC18LF6390 LCD controller chip and its firmware. and the Qwik&Low board used as a vehicle for all that follows. For a course that is driven by a sequence of lab projects. The chapter also deals with the scaling and display of a ratiometric temperature sensor’s output. low-power operation. Chapter 14. a project might use it to introduce a variable into an algorithm with the ADC output from a one-turn potentiometer input. earlier than the consecutive sequence of chapters would dictate. orders of magnitude less than the current drawn by popular dot-matrix. Chapters 9 and 10 are likely to be studied and used. Chapter 10 discusses the use of a rotary pulse generator (a. . ±50-ppm (parts per million) watch crystal oscillator used by two of the microcontroller’s timers. like Chapters 9 and 10 before it. serving as a model for more general expansion. Chapter 9 explains the use of the microcontroller’s analog-to-digital converter. a critical issue for average current draw and an elusive issue when coding is done in C. Chapter 4 introduces the first template program and lays the groundwork for understanding and using it.Preface 9 An appendix is included for those who are interested in studying how a C algorithm is implemented in the assembly language of the PIC18LF4321 microcontroller.exe utility that not only compiles the C code into machine code but also generates a qwik. QwikBug requires a programmed “Background Debug Mode” vector because Microchip’s utilities reserve the BDM vector use for their own debugger. He suggested numerous alternatives for expressing a given algorithm in C. Every line of C code in the book was either written by Alex Singh or written by the author and vetted by Alex.exe compiler wrapper that invokes the Microchip C18 compiler with carefully selected parameters chosen to optimize code efficiency and execution time and to produce the same resulting machine code for both the commercial version of the compiler and the student version. Louis Howe developed QwikProgram 2. The result is a rock-solid tool validated by a semester of student use and fully described by Ryan in Appendix A1. ACKNOWLEDGMENTS It has been my good fortune over the last several years to be guided in my academic endeavors by Gary May. a utility to update the “Program Hierarchy” table showing the relationships between all the functions in an application program. all in the interest of examining alternatives produced by the C compiler. The intent is to gain an understanding of the assembly code produced by the compiler of an application program written in C. Alex’s wrapper displays the number of bytes of machine code produced by the application program as well as the percentage of available program memory used by the program. Alex also developed the first pass of the Preface Chapter 17 considers another role for the serial peripheral interface used by the microcontroller to send data to the LCD controller. posting everything needed by the author’s students as they used the book in manuscript form during the 2007 fall semester. The last two appendices describe the circuitry of the Qwik&Low board and of the stepper motor control board. He wrote the code for the EEPROM of Chapter 14. Gary’s predecessor. and by Roger Webb. instruction set. a utility that reformats the indenting of a source file and aligns the comments appended to the lines of C code. Two chips are considered: a digital-to-analog converter. and a temperature sensor with a high-resolution digital output. This is a task that is thwarted by Microchip’s programming utilities.qwikandlow. and addressing modes of the PIC18 microcontroller family. a utility needed to program Kenneth Kinion’s QwikBug executive into the PIC18LF4321 chip. This book would not have been written but for the assistance of some able students.com website. This interface can be used for attaching chips with additional I/O features to the microcontroller. for the silicon serial number chip of Chapter 15 and the elegant display controller code of Chapter 16. Chair of the School of Electrical and Computer Engineering at the Georgia Institute of Technology. The first describes the installation and use of the QwikBug debugger. He also developed QwikPH. A purchased Qwik&Low board includes this QwikBug executive programmed into its PIC18LF4321 chip. Alex developed the c18. The book concludes with four appendices. Ryan graduated from Georgia Tech in May 2007 and generously agreed to spend nights and weekends during the summer reworking the user interface for source files written in C. Both of these utilities employ the comforting feature of . Ryan Hutchinson developed the QwikBug user interface and Kenneth Kinion the QwikBug executive for use with assembly language source files during the 2007 spring semester. The second describes the CPU structure. David Bauer developed QwikIndent. John B. As described in Appendix A2. Peatman Georgia Institute of Technology jpeatman@comcast. my son-in-law and master photographer. Cody Planteen developed the QwikLst utility. if desired.Preface 11 renaming the source file before producing a new modified source file and thus providing the ability to revert to the original source file. has produced all of the photographs in this book. application engineers (and former students) Rawin Rojvanit and David Flowers have been quick with answers to elusive questions or guides to their appropriate colleagues.net . Bill Kaduck and Dave Cornish of MICRODESIGNS. She brightens the days of my life.exe utility to enhance the resulting assembly language list file into a more readable qwik. I am once again indebted to my wife. Marilyn has translated my handwritten words into readable. and Erin Connaughton. Full Service Manager. They have managed the rendering of my penciled line drawings into finished artwork and have produced the finished book pages. Mark Schutte. with the publication of my seventh textbook. have shared design ideas that have enhanced the design of the Qwik&Low board. it is included in the invocation of the c18. President and CEO of Intelligent Systems Corporation. understandable text and has been involved with every decision in the production of the book. Naga Maddipati helped to track down and fix an elusive leakage current problem in the PIC18LF6390 LCD controller. Thus Brett Duane brought clarity to a start-up problem with the Timer1 oscillator. Steve Sanghi and Eric Sells provided valuable material and insights for Chapter 1. Project Manager. Inc. Rick’s extensive design experience once again has proven crucial to the development of the Qwik&Low board and also of the stepper motor controller board. At Microchip Technology. Leland Strange. It thereby helps to clarify the C compiler’s implementation of an application program. Marilyn. Finally. with Laserwords of Chennai. This low cost but quality book would not have happened without the gracious and accommodating help of Saradha. From the outset she has supported the development of a text that could serve the reader with the gift of a free downloadable text. has long provided professional insights as well as fostering my continually evolving class and laboratory activities at Georgia Tech.lst file. He also designed the book’s cover. I have long been indebted to Rick Farmer for his help with the physical design and PC board implementation of assorted projects over the years. India. . Chandler. mobile phones. CEO and President. Low power and dependable operation are important in embedded applications..1 LOW-POWER DESIGNS: THE WAY FORWARD IN EMBEDDED APPLICATIONS1 The need to reduce overall power consumption plays a crucial role in many embedded applications. 13 . As microcontroller designs continue to move into smaller applications with limited power resources. Arizona. Batteries are the power source in low-power designs. Microchip Technology Inc. System designers face many challenges posed by compact and portable device electronics. it is left to the ingenuity of the embedded designer to get the most out of the power source using suitable microcontrollers and related devices. Since the advances in battery technology are incremental in nature. The main focus of a successful 1 This section was written by Steve Sanghi. the availability of economical small-pin-count devices with complex peripherals and power-saving features has become increasingly desirable. laptops and other devices.Chapter 1 INTRODUCTION 1. This can be seen in examples such as PDAs. media players. This intention could be twofold—to extend battery life or meet regulations like Energy Star. Chip designers have incorporated several power-saving features into their devices that give designers control over power consumption. the Brown-out Reset (BOR) feature is not necessary in battery-powered applications. waking up periodically under a timer’s interrupt to run program code. The combination of lower-power peripherals and microcontroller sleep modes improves the design of a low-power solution. Safety is a high priority in some applications such as medical and mission-critical applications. designers can take advantage of a fail-safe clock monitor feature to detect the loss of a clock source—thus helping the system toward either a gentle shutdown or a “stay-alive” mode. The competition is especially fierce among manufacturers of 8-bit microcontrollers. This opens up new product design opportunities in space-constrained applications that could not afford the cost of a microcontroller. For example. By using the latest microcontrollers. Power saving can be optimally achieved in low-power designs by having the microcontroller control power used by both internal and external peripherals. This requires the partitioning of the design based on power consumption during its operation. if a single peripheral in the device consumes most of the power. in most applications. In these applications. the power consumption can be reduced by as much as 96%. system designers need to provide for emergency situations where an appliance can suffer from loss of power or program control. As a rule of thumb. Minimizing power consumption in embedded systems enables the use of smaller batteries in portable systems.14 Chapter 1 Introduction low-power design is a microcontroller that features a variety of sleep modes and clock modes. designers can implement power-management techniques and build cost-effective low-power devices. In certain microcontrollers. determine the required operation states and plan to shutdown unwanted circuitry. worrying about reducing the microcontroller’s power will have no impact on the overall system power consumption. 1. . When designing a low-power product. By invoking the sleep state. which pervade low-cost high-volume applications. To conserve power. if shutdown is not desired. There could be instances where the loss of a clock source can trigger an erroneous execution of a product’s control program.2 THE LEARNING CURVE Microcontroller manufacturers develop their products for a highly fractionated market. The impact of low-power designs can have significant implications from disposable medical devices to consumer electronics and beyond. The idle modes of the microcontroller power down the CPU while allowing peripherals such as an ADC to continue to operate. One is a general-featured. with instructions that operate on 8 bits at a time. afford a manufacturer the best tradeoff for developing families of parts having a rich assortment of features reaching across the family. With approximately two dozen manufacturers of microcontrollers worldwide. designers can turn off the CPU using an idle instruction and keep the peripherals running. The most obvious one is being able to turn off the peripherals when they are not needed. no one company dominates the marketplace. system controllers need to remain in a low-power state most of the time. For example. the Qwik&Low board used in conjunction with this book employs two Microchip Technology microcontrollers. On the other hand. They share the same CPU architecture and instruction set. These microcontrollers. Several techniques exist that allow designers to save power. 4 THE PIC18LF6390 LCD CONTROLLER The Qwik&Low board includes a second microcontroller with internal resources dedicated to the ongoing task of updating and refreshing a liquid-crystal display (LCD). Microchip’s 8-bit microcontrollers span from 6-pin to 100-pin parts. Only . As a consequence.. 1. an analog-to-digital converter). It has the diversity of resources that make it a good match for a wealth of applications. Given this fractionated market and given the benefits that follow market share. Microchip has pursued a careful learning curve strategy. readers will learn techniques for using a microcontroller in an energy-efficient manner that will translate to another manufacturer’s microcontroller.4 The PIC18LF6390 LCD Controller 15 multipurpose microcontroller. The other concentrates its feature set around the ability to serve as a versatile LCD controller that supports a variety of LCD multiplexing modes and a variety of serial and parallel data input formats. also gained the number one spot in 8-bit microcontroller revenue.3 THE PIC18LF4321 MICROCONTROLLER The general-purpose microcontroller employed in this book is shown in block diagram form in Figure 1-1. This microcontroller includes an LCD module that autonomously refreshes the LCD while the rest of the chip sleeps and draws virtually no power.Section 1. each with its own set of on-chip peripheral modules (e. even sophisticated parts such as those used on the Qwik&Low board have a unit price of about $3. The principle of the learning curve states that each doubling of the quantity of parts produced results in a fixed percentage decrease in the unit cost of a part.g. accounting for over 2 billion of the 5 billion microcontrollers it has sold to date. Even as students graduate and find themselves immersed in a company environment with tools and facilities organized to use another manufacturer’s microcontroller. this year. Microchip has continued to hold this number one spot since then and has. the skills and perspectives gained here will reap dividends there. Alternative approaches to hardware and program code organization will be compared for their resulting average current draw from the coin cell. Its features also make it a fine vehicle for exploring applications where power is supplied by a wafer-thin coin cell. This second microcontroller illustrates one of the trends in the world of low-power applications. For years Motorola dominated the 8-bit microcontroller market with one out of every three microcontrollers sold being a Motorola product. 1. Just as important. Microchip has gained market share. The payoff for users of this book is that their learning is directed toward a family of parts that finds wide use and is competitively priced. Microchip has pioneered the use of low-cost reprogrammable flash memory. a marketplace increasingly supplied by many competitors had reduced Motorola’s market share and led to Microchip gaining the number one spot in the number of 8-bit microcontrollers shipped. In 2002. By passing these reduced costs along to customers in the form of reduced prices. load the registers used autonomously by the LCD module. and then return to sleep. low power Interrupt logic Timers Timer1 Timer3 Timer0 CPU clock CPU Run-idle-sleep modes 2.0 V to 5.16 Chapter 1 Introduction PIC18LF4321 CPU clock INTOSC INTRC 8 kHz to 2 MHz 8 kHz.5 V operating range High priority Interrupts Low priority Data RAM Data EEPROM 512 bytes CCP2 256 bytes Capture/Compare/PWM modules Flash program memory 8192 bytes (4096 16-bit instructions) Configuration bytes to enable/disable features Power-on reset & start-up timers Enable/disable Enable/disable & threshold Enable/disable & timeout period Serial Peripheral Interface SCK SDO SDI TX RX Timer2 (configure with timers) CCP1 CCP1 Timer1 oscillator 32768 Hz crystal Other options CCP2 UART Edge-select interrupt circuitry (up to 3 inputs) Brown-out reset Watchdog timer wakeup or reset 4 ms to 131 sec Program code protect Ten-bit analog-to-digital converter (up to 13 channels) Two voltage comparators High-low supply voltage detect (16 levels) Enable/disable Otherwise unemployed I/O pins (up to 36 pins) Background Debug Enable/disable Mode (used by QwikBug) FIGURE 1-1 Block diagram of PIC18LF4321 microcontroller when a string of characters making up a new message is received by the chip does the CPU awaken and process the characters. . . QwikProgram 2. Otherwise. For programming the LCD controller.com website for anyone interested in making modifications to it (e. The source code for QwikBug is freely available from the www. after which some of its code optimization is withdrawn. QwikBug can be used to download a program. without QwikBug). 1. running on a PC. the header pattern labeled “LCD PICkit 2” is used. Figure 2-11 in the next chapter illustrates the programming connection. stop at a breakpoint. complete with the user program’s “configuration byte” choices (which are normally ignored. The author has found that the relatively small program code examples used in this book compiled to virtually identical “hex” files whether using the “expired” student version of the compiler or the “site license” commercial version..qwikandlow. If application code is programmed into the MCU directly (i. QwikBug. QwikBug supports application programs written in C and compiled using Microchip’s C18 compiler. The need for a special utility arises because of QwikBug’s use of the chip’s Background Debug Mode vector. This vector is located within the PIC18LF4321 chip at an address that Microchip’s PICkit 2 programming utility prohibits accessing. examine and modify registers and RAM variables. uncluttered user interface described in Appendix A1. “single step” successive lines of C source code. The resulting male probe of the PICkit 2 is inserted (but not soldered) into the 6-pin unpopulated header pattern labeled “MCU PICkit 2” on the Qwik&Low board. All of these tools are free. to modify its choice of configuration options.. reserving its use for their in-circuit debugging tool. a USB-to-serial adapter cable is used.qwikandlow. and serve as a display of character strings for an application program (in addition to the Qwik&Low board’s LCD). run it. While “Student Edition” may sound worrisome. Once installed.g.6 PROGRAMMING WITH THE PICKIT 2 PROGRAMMER Microchip’s low-cost ($35) PICkit 2 programmer can be used to program either the PIC18LF4321 MCU or the PIC18LF6390 LCD controller. the program can be run directly from reset.5 QWIKBUG DEVELOPMENT ENVIRONMENT The PIC18LF4321 microcontroller on the Qwik&Low board has been programmed with an executive kernel that works with its counterpart. deferring to QwikBug’s choices).Section 1. If the PC has a serial port. as described in Appendix A1.e.com website to a PC. to change the watchdog timer timeout period from 16 ms to 8 ms). It requires the addition of a 6-pin male-to-male header inserted into the 6-pin female socket of the PICkit 2. Reprogramming the modified QwikBug into the chip requires a PICkit™2 programmer and a special programming utility. The LCD controller code can be modified to enhance its user interface. QwikBug presents the easy-to-use.6 Programming With The PICkit 2 Programmer 17 1. a standard “straight-through” serial cable is used for the connection to the Qwik&Low board. The QwikBug “install” program can be downloaded and installed from the author’s www. it is available to anyone and is identical to the commercial version for 60 days. beginning with the Student Edition of Microchip’s C18 compiler. 2 CR2032 COIN CELL The low-cost ($0. 2. the average current can be minimized. a larger current can be drawn from it subject to degradation from its specified life of 220 mAh.4 mA. The specifications of the coin cell will lead to a consideration of the microcontroller and its power-saving operating modes. 18 . A vehicle for testing operating alternatives will take the form of a manufactured Qwik&Low board. perhaps with brief excursions to currents in the milliampere range. Note that while this coin cell is specified for a standard discharge current of 0.1 OVERVIEW This chapter considers the opportunities and challenges of using a popular MCU (microcontroller unit) under the constrained design goal of powering it with a lowcost 3-V coin cell. popular CR2032 coin cell is shown in Figure 2-1. The challenge will be to explore ways to organize an application so as to draw only a few tens of microamperes from the coin cell. A case will be presented for writing code in C rather than in assembly language. By keeping such excursions short.Chapter 2 LOW-POWER OPERATION 2.25). 3 A PIC18LFXXXX FAMILY OF MICROCONTROLLERS Microchip Technology’s microcontrollers employing nanoWatt Technology offer a user a variety of ways to operate the chip to minimize the current draw on the coin cell. each chip listed in Figure 2-2a includes essentially the same feature set.3 A PIC18LFXXXX Family Of Microcontrollers 19 (a) Coin cell and a dime Nominal voltage = 3 V Rated capacity = 220 mAh (milliampere-hours) Standard discharge current = 0.0 1 Current (mA) (c) Voltage vs. listed in Figures 2-2b and c. This book will focus on the low-power features of Figure 2-2b while using the I/O features of Figure 2-2c. Current 2 FIGURE 2-1 CR2032 lithium coin cell 2. Other than the amount of program memory and RAM.0 Voltage (V) 2.Section 2. .0 1.4 mA (b) Specifications 3. Up to 32/25 I/O pins on 44-pin/28-pin parts. up to over 2 minutes. (b) Low-power-achieving features. . 32 ms. peripherals on Idle mode: CPU off. Separate very low power but 10% accurate internal 8 kHz CPU clock.38/$5. (c) Input/output functions FIGURE 2-2 Family features of four PIC nanoWatt Technology™ microcontrollers The table of Figure 2-2a lists the distinguishing amounts of program memory and RAM data memory plus the 2007 price for four otherwise virtually identical pairs of chips. Another very low power oscillator using external 32768 Hz watch crystal for 50 ppm accuracy.41/$3. 16 ms. SPI and I2C serial peripheral expansion support. Each pair includes a 44-pin surface-mount part and the same microcontroller in . peripherals off Operation down to 2. . . 2% accurate CPU clock frequencies (2 MHz down to 8 kHz). . Watchdog timer for periodic wakeup from lowest-power sleep mode. Four sixteen-bit timers plus associated circuitry for versatile timing measurement and control. Eight internally generated.com).71/$5.11 $6.20 Chapter 2 Low-Power Operation 44-pin TQFP package PIC18LF4221-I/PT PIC18LF4321-I/PT PIC18LF4420-I/PT PIC18LF4520-I/PT 28-pin DIP package PIC18LF2221-I/SP PIC18LF2321-I/SP PIC18LF2420-I/SP PIC18LF2520-I/SP Flash program memory (kilobytes) 4 8 16 32 RAM (bytes) 512 512 768 1536 44/28-pin price (1-25) $3.microchipdirect.4V for CPU clock of 2 MHz or less.96 $3.83 (a) Price versus program memory and RAM size (prices from www. peripherals on Sleep mode: CPU off. Twenty interrupt sources. Timeout period of 4 ms.24/$2. 13/10 analog-to-ten-bit-digital converter inputs (44-pin/28-pin parts). 8 ms.25 $7. Two voltage comparators. USART asynchronous and synchronous serial communication support. Power-managed modes of operation: Run mode: CPU on. These bytes select features of the chip that cannot be altered during the execution of a user program. both in the microcontroller and external to it. from 2 MHz down to 7. If the binary value 00000010 is written to OSCCON. the microcontroller needs a mechanism that can awaken it periodically.5 INTERMITTENT SLEEP MODE OPERATION The PIC18LFxxxx microcontrollers include a “sleep” instruction that. . 2. causes the CPU clock to stop. The internal oscillator frequency choice is under the control of a user program. up to something over 2 min. . but draws roughly an extra 150 µA of current from the 3-V coin cell as will be seen in Figure 2-4. the most-significant bit of the chip’s OSCTUNE register can be set to select the higher-power. 32 ms. Its programmable scaler can be used to create watchdog timeout periods of 4 ms. A built-in mechanism that is satisfactory for many applications is the PIC18LFxxxx watchdog timer.4 INTOSC AND INTRC.8 kHz. This is illustrated in Figure 2-5. The choice of divider is selected when the chip is programmed with what are called its configuration bytes. less accurate INTRC source.1 µA.8 kHz can be derived in either of two ways.Section 2. and a final divide-by-four circuit.8 kHz. any of the upper seven frequencies can be selected. when executed. the table values provide design guidance by way of their comparative values. then the lowest frequency. The lowest frequency of about 7. the data of Figure 2-4 would tell the whole story of the CPU’s relatively high current versus clock rate.. The highest seven of these frequencies are derived from a relatively accurate (±2%) 8-MHz oscillator. 8 ms. To execute instructions in periodic bursts in this way. 16 ms. will be used throughout. Clearing this bit will select the low-power. will be selected. The effect of the choice of CPU clock upon the current drawn from a 3-V coin cell powering the chip is illustrated in Figure 2-4. more accurate INTOSC source. it can respond to inputs and control outputs and then go back to sleep. By awakening the chip from its sleep mode periodically. Added to this current would be the current drawn by peripheral functions. the chip exhibits a measured value of leakage current of 0.096 bytes of program memory should suffice for the tasks of this text. Given that Microchip’s data sheet does not address all the variations of interest here. THE INTERNAL OSCILLATORS Figure 2-3a illustrates the circuitry that selects one of the eight internally generated CPU (central processing unit) clock frequencies. With nothing being clocked. These are typical values taken from actual measurements. illustrated in Figure 2-6. The divided-down INTOSC oscillator provides a more accurate clock frequency. 2. . The lowest-power choice uses the relatively inaccurate INTRC oscillator. 7. the “sweet spot” 4321/2321 pair.5 Intermittent Sleep Mode Operation 21 a 28-pin DIP package (with 11 of its I/O pads not brought out to DIP pins). with double the program memory for essentially the same price. If the CPU were continuously clocked. Although even the 4221/2221 pair with 4. By writing any of seven choices to the chip’s OSCCON register. a programmable divider. In this case. . 256 0 1 FOSC ÷4 FCPU OSCCON = x 0 0 0 x x x x AND OSCTUNE = 0 x x x x x x x (a) CPU clock derivation from INTOSC or INTRC oscillators. Whenever the watchdog timer is .8 kHz source OSCTUNE 1 0 use INTOSC. FCPU = 8000/1024 = 7.25 KHz ±10% OSCCON divider ÷ 1. once and for all.8 kHz ± 10% (low-power alternative) (b) Clock selection registers FIGURE 2-3 INTOSC and INTRC clock sources The watchdog timer can be enabled with a bit of a configuration byte.5 31. as shown in Figure 2-6. Alternatively. use OSCTUNE to select 7. 64. independent of what a user program might choose to do. setting or clearing the SWDTEN bit of the WDTCON register can leave the enabling/disabling under program control.25 125 For this choice. 0 OSCCON 0 0 1 0 System clock select bits 0 0 0 1 1 0 Use primary oscillator selected by configuration choice (Figure 4-2) Use Timer1 (32768 Hz crystal oscillator) Use internal oscillator block (INTOSC or INTRC) FCPU (kHz) (FOSC/4) FOSC (kHz) 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 0 1 0 8000 2000 4000 1000 2000 500 1000 250 500 125 250 62. 2. 8. 16.8 kHz ± 2% use INTRC.22 Chapter 2 Low-Power Operation INTOSC 8 MHz ± 2% Low-power INTRC 31. FCPU = 31.25/4 = 7. 4. 32. 5 µs 130 µs 122 µs Current draw 1.Section 2.06 µs 8. independent of whether the INTRC oscillator is also selected as the CPU clock. During successive awakenings of the chip.25 kHz Actual Fcpu (Fosc/4) 1. it can be used to reduce average current by lengthening the “Tperiod” interval of Figure 2-5.508 µs 1. The choice of the watchdog timer’s divider can be used to shorten response time to input/output demands.02 µs 2. the low-power INTRC oscillator is enabled for use with the watchdog timer. FCPU = 2 MHz) . (shown for FOSC = 8 MHz.966 MHz 983 kHz 492 kHz 246 kHz 123.2 µs 32. the input is 1750 µA ≈0 µA Tactive Tperiod Iavg = 1750 × Tactive Tperiod time FIGURE 2-5 Effect of intermittent sleep mode upon average current.2 µA.69 kHz 8.03 µs 4. Alternatively. then sensing the state of a switch during successive intervals effectively debounces the switch.7 kHz 30.036 mA 674 µA 486 µA 390 µA 343 µA 207 µA 206 µA 64 µA FIGURE 2-4 Current draw of PIC18LF4321 when operating continuously from a 3V coin cell versus CPU clock source and frequency.5 kHz 61. Another issue bearing on this choice is the effect of the contact bounce exhibited by pushbutton switches and keypad switches employed in a user interface. (All internal and external functions other than CPU instruction execution are inactive.19 kHz CPU clock period 0.750 mA 1.) enabled. as shown in Figure 2-7.8 kHz 7.10 µs 16. The running of INTRC plus the watchdog timer together draw a measured current of 2.5 Intermittent Sleep Mode Operation 23 Clock source INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTRC Nominal Fosc 8 MHz 4 MHz 2 MHz 1 MHz 500 kHz 250 kHz 125 kHz 31.25 kHz 31. If Tperiod is selected to be larger than the maximum contact bounce time of any switches in an application. a miniscule current for implementing this intermittent sleep mode of operation. Figure 2-7a illustrates a circuit for sensing the press of a pushbutton. a succession of 1s was read.24 Chapter 2 Low-Power Operation WDTCON SWDTEN = 0: Disable watchdog timer 1: Enable both INTRC oscillator and watchdog timer Enable INTRC for use by watchdog timer Enable watchdog timer itself Low-power INTRC 31. a succession of 0s is read. Action is taken when the pin is read as a 0 and the previous reading was a 1. While the key is held down. Before the keypress.2 µA (c) Measured value of current FIGURE 2-6 Watchdog Timer read. control is passed to the SWDTEN bit of the WDTCON register Watchdog timer is enabled. then a single change from 1 to 0 will be detected at the time of the following .25 kHz ±10% N is set by the WDTPS configuration value ÷128 Period = 4 ms (a) Circuit WDT OFF : ON : ÷N scaler Tperiod Wake up sleeping CPU Watchdog timer disabled. regardless of the state of the SWDTEN bit Tperiod 4 ms 8 ms 16 ms 32 ms 64 ms WDTPS 1 2 4 8 16 • • • 32768 ≈2 minutes (b) Configuration options programmed into the chip (unavailable for change by the user program) I(INTRC+WDT) = 2. If the key is bouncing at the moment the key state is read and if it is read as a 1. a timer or a serial data transfer module). The average current is calculated as Texec Iavg = 〈______〉 × Iawake 16 ms where Texec is the time to execute code for 100 CPU clock cycles.g. For Tperiod = 16 ms. In this case. Figure 2-8 illustrates the average current draw if a user program takes 100 CPU clock cycles to execute every 16 ms. . a single change from 1 to 0 will be noted at the time of this sample. 2. the user program just needs to check the state of a switch every third awake time to debounce it. The data for this table are drawn from Figure 2-4. In neither case does the …1→1→1→0→1→0→1→0→0→0… sequence register as anything other than a single 1 → 0 transition. If the bouncing key is read as a 0. The maximum contact bounce time of small electromechanical switches is commonly specified as less than 10 ms. with no keybounce ever seen.Section 2. If Tperiod = 4 ms..6 EFFECT OF CLOCK FREQUENCY A final consideration when operating the MCU in this intermittent sleep mode is the effect of the choice of FOSC. For Tperiod = 8 ms. the frequency of the clock source. the awake time (and hence the average current draw on the 3-V coin cell) is proportional to the CPU clock period times the instantaneous current draw.6 Effect Of Clock Frequency 25 +3 V MCU R Digital input pin (a) Circuit Maximum contact bounce time 3V 0V Tperiod Tperiod Tperiod Tperiod Tperiod Tperiod 1 1 1 0 or 1 0 0 0 (b) Value read by digital input pin FIGURE 2-7 Debouncing an electromechanical switch sample. the switch can be checked every other awake time. First consider the commonly occurring case where the awake time is determined solely by the time it takes to execute a user program that is not delayed by pauses while waiting for a peripheral function (e. the switch is checked every awake time. Rather than repeatedly polling the state of an input pin and waiting for it to indicate that an external event has been completed.g..7 USER PROGRAM STEPS TO REDUCE CURRENT DRAW The microcontroller used with this text has two ways to reduce the average current draw when user code includes externally produced delays. the chip can first be put to sleep.2 µs 32. and repeatedly polling the state of an input pin.26 Chapter 2 Low-Power Operation The conclusion to be drawn from Figure 2-8 is dramatic. the choice of the lowcurrent INTRC oscillator produces a higher average current draw than all but the lowest FOSC derived from the INTOSC oscillator. a variation of the interrupt approach just Clock source INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTRC Nominal Fosc 8 MHz 4 MHz 2 MHz 1 MHz 500 kHz 250 kHz 125 kHz 31. It is important to remember that these conclusions rest on having an application that is not delayed by waiting for the completion of a task by a peripheral module.0 ms 12.6 µA 6. indicating the completion of the external event. 2. perhaps by switching to the INTRC oscillator.508 µs 1.6 µA 12 µA 20 µA 35 µA 42 µA 167 µA 49 µA FIGURE 2-8 Average current calculations .06 µs 8.2 ms Iawake 1750 µA 1036 µA 674 µA 486 µA 390 µA 343 µA 207 µA 206 µA 64 µA Iavg 5. The change in state of the input pin can awaken the chip and resume execution at the same point simply by using what would normally be an external interrupt pin for this purpose.5 µs 130 µs 122 µs Texec Time to execute 100 clock periods) 50. changing the module’s frequency or stopping it is usually not an option.6 µA 8.03 µs 4. waiting for the completion of a serial transfer). If code execution includes a delay caused by an internal module (e. A second way to reduce the current draw while waiting for the completion of an external event makes use of the chip’s interrupt circuitry.8 µs 102 µs 203 µs 406 µs 810 µs 1. At the other extreme. However. then the clock for the module is usually the same as that used to clock the CPU.02 µs 2.25 ms 13. The choice of a high value of FOSC minimizes current draw. When the pin changes state. In this case.25 kHz Pcpu Actual CPU clock period 0.25 kHz 31.10 µs 16. the CPU clock is switched back to the normal clock and code execution continues using fast clock cycles. The simplest approach is to slow the CPU clock.62 ms 3. 25 kHz Irun Run mode current (CPU on.46 . As shown in Figure 2-9.48 .8 The Qwik&Low Board 27 Clock source INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTOSC INTRC Nominal Fosc 8 MHz 4 MHz 2 MHz 1 MHz 500 kHz 250 kHz 125 kHz 31. In contrast.68 . Here are its salient features: • It uses peripherals whose current draw can be reduced to zero (either under control of the PIC18LF4321 MCU or by opening a switch or jumper) to monitor the MCU current. These microcontrollers include an idle mode.8 THE QWIK&LOW BOARD This book is intended to be supported by the Qwik&Low board shown in Figure 2-10. the leveling off of both the run-mode current and the idlemode current of the chip when clocked by the INTOSC oscillator and its scaler for its lower frequencies may be a reflection of the substantial current drawn by the 8-MHz oscillator itself.49 . peripheral on) 1750 µA 1036 µA 674 µA 486 µA 390 µA 343 µA 207 µA 206 µA 64 µA Iidle Idle mode current (CPU off: peripherals on) 834 µA 503 µA 325 µA 235 µA 179 µA 158 µA 148 µA 140 µA 5 µA Iidle Irun . .08 FIGURE 2-9 Idle mode current compared with run mode current discussed can be used.46 . stopping the clock to the CPU while maintaining it to the chip’s peripheral modules cuts the current draw by one half for any but the lowest frequencies of the INTOSC oscillator.71 .Section 2. When the IDLEN bit in the OSCCON register is set.25 kHz 31.48 . the subsequent execution of a “sleep” instruction will stop the clock to the CPU. The 92% reduction in current when clocking only the chip’s peripheral modules with the INTRC oscillator may be a reflection of how little current the low-power oscillator itself draws. It will be described in more detail in Chapter Three. • It includes a prototype area to allow the use of additional peripheral devices. • It uses an eight-character LCD having a PIC18LF6390 chip as its controller. to reduce the LCD-plus-LCD-controller current draw to 5 µA. 2. Virtually all of the internal peripheral modules include an interrupt mechanism that can be set up to awaken the CPU when its task is complete.48 . but maintain it to the peripheral modules. . There are several reasons for C to be preferred: • C code. and table lookup that are built into standard C. Thus it is easier for others to understand and augment the original developer’s code. Then a free QwikBug utility (discussed in Chapter Three) running on the PC can download and run a C-compiled “hex” file on the PIC18LF4321. single stepping. division. and variable watching and modifying. 2. is close to being self-documenting. • The C compiler. handles functions such as multiplication.9 CODING IN C Most microcontroller applications developed professionally have had their code written in C rather than in the microcontroller’s assembly language. A window in QwikBug’s display can be written to by a user program to extend the display capability of the board beyond that of the eight-character LCD. even without comments. rather than the code developer.28 Chapter 2 Low-Power Operation FIGURE 2-10 Qwik&Low board • The PIC18LF4321 can be programmed with Microchip’s low-cost ($35) PICkit 2 programmer shown probing the Qwik&Low board in Figure 2-11. the PIC18LF4321 can be linked to a PC via either a $5 serial cable (for PCs having a DB-9 serial port) or a $10 USB-to-serial adapter. QwikBug supports debugging with breakpoint capability. • Alternatively. • C compliers are generally expensive.Section 2. for issues that really matter. bypassed by the code developer. Although this is becoming a common skill for electrical and computer engineering students. familiar with writing code in C. This is generally not a problem. addressing modes. their student version is available free to anybody and provides exactly the same features and optimized compilation for 60 days. While there is some justification for lamenting the resulting loss of control over how algorithms are carried out by the microcontroller. Writing code in C is not without its downsides: • The resulting machine code will be larger than if it had been written in the microcontroller’s assembly language. However. whereas the commercial version of Microchip’s C18 compiler is pricey.. thereby. such as measuring a pulse width precisely. as long as the microcontroller has sufficient program memory to hold the machine code. independent of the speed of execution of the program code. and instruction set) is passed to the C compiler and. • The code developed in C may not execute as fast as if it had been developed in assembly language. only the optimization is reduced.9 Coding In C 29 FIGURE 2-11 PICkit 2 programmer • The need to understand the role of the microcontroller’s CPU structure (i. the resulting machine code is generally satisfactory. the microcontroller includes resources to take over this role. its registers. • The code writer must be. or become. Even so. However. After that. .e. there is the compensating accuracy of the resulting C implementation. g. The understanding of how to deal with peripheral devices will be a central theme of this book. Ultimately. whether implemented in C code or assembly language code. However. student projects can build on a given template by “doing more of the same” with an added peripheral device. a temperature sensor) as well as peripheral modules within the chip. setting or clearing control bits in registers. These template programs can progress through a sequence of increasingly complex tasks. it is the author’s experience that template programs can be used for this purpose. Along the way. Program control of these peripherals will reduce to testing status bits in registers.30 Chapter 2 Low-Power Operation it is certainly not universally so. . These steps are virtually the same. and reading from and writing to registers.. the role of the developer of a microcontroller application is to understand the functioning of peripheral devices external to the chip (e. Chapter 3 QWIK&LOW BOARD 3.1 OVERVIEW The chapter begins with a brief list of items needed to support the book using the Qwik&Low board. The I/O and support circuitry surrounding the PIC18LF4321 on the board are described, as is the board’s LCD circuitry. 3.2 EQUIPMENT SETUP The Qwik&Low Board is built and tested by Microchip Technology and available as their Part No. DM183034 (minus the needed CR2032 coin cell). For purchase information, see. Also needed are the supplies listed in Figure 3-1. A digital multimeter (DMM) with a microammeter scale having a resolution of 1 µA will serve, but the normal test probes need to be replaced with test leads having banana jacks on each end. An excellent, low-cost DMM that has been found by the author to be sturdy and reliable in his Georgia Tech instructional laboratory is available from (Part No. F01DMMAS830). They also have banana plug test leads (Part No. F05ALS4). The Qwik&Low board comes with the PIC18LF4321 programmed with QwikBug. Consequently, the reader does not need to purchase a programmer. Rather, access the 31 32 Chapter 3 Qwik&Low Board FIGURE 3-1 Required Qwik&Low supplies author’s website,, to obtain and install the QwikBug utility to run on a PC. This free utility, prepared by Ryan Hutchinson and Kenneth Kinion not only allows the user to download and run a compiled C file on the PIC18LF4321, but also to stop at a breakpoint and single step line by line through the C source file while monitoring and optionally modifying selected watch variables. If the user chooses to overwrite the QwikBug utility in the chip, Microchip’s PICkit 2 programmer ($35) will be needed. If the user later decides to reinstall QwikBug into the board’s MCU (microcontroller unit, the PIC18LF4321), a QwikProgram 2 utility developed by Louis Howe is available to download from the website and then install and run on a PC. QwikProgram 2 programs not only the QwikBug utility itself but also the normally inaccessible Background Debug Mode vector located at address 0x200028. QwikBug employs a serial connection to a PC. To meet the requirements of the RS232 standard, such a connection requires the transmit and receive lines of the MCU to be inverted and voltage-translated so that the MCU’s 0 V and 3 V levels communicate appropriately with the PC’s +15 V and −15 V levels. However, for this nonstandard test serial port, the Qwik&Low board employs transmit and receive signal inversion built into the MCU itself. The MCU’s receive input is clamped to the 0 V and 3 V levels by protection diodes built into the chip, with current limited by a 1 MΩ series resistor. The MCU’s transmit output voltage swing of 0 V to 3 V does not meet the RS-232 standard, but is sufficient to be interpreted satisfactorily by every PC and every serial-toUSB adapter the author and his students have tried. This simplified connection causes minimal current draw on the coin cell with and without the serial cable connected. If the reader’s PC includes a serial port with its 9-pin male DB-9 connector, all that is needed is the normal straight-through DB-9M to DB-9F serial cable. “Straight through” means that the pins of the DB-9M connector are connected to the corresponding pins of Section 3.3 Input/Output Peripheral Power 33 the DB-9F connector. If the reader has an up-to-date notebook computer, it probably does not include a serial port. In this case, the USB-to-serial adapter will be needed at a cost of $10–$15, available by Googling USB to serial adapter to find any one of many sources. One last, but more expensive, piece of test equipment that finds repeated utility with the Qwik&Low board is an oscilloscope. Both the PIC18LF4321 MCU and the PIC18LF6390 LCD controller have their internal CPU (central processing unit) clock (FOSC/4) brought out to a test point on the board. By probing this point for the MCU, a user can see when the chip is awake and when it is asleep, and thereby discern the MCU’s duty cycle and the effect that a low duty cycle has on current draw. The LCD controller only awakens when a new display string is sent to it by the MCU. The scope can monitor the duration of the serial transfer. It can also monitor the LCD controller’s CPU clock (FOSC/4), to discover how long the LCD controller takes to process a received display string from the MCU before returning to sleep. 3.3 INPUT/OUTPUT PERIPHERAL POWER As shown in Figure 3-2, each of the peripheral components on the Qwik&Low board is connected to the MCU in a way that permits power to be removed from the component. In some cases, an MCU output pin provides the peripheral power. In other cases, the power is applied or removed with a jumper or a switch. To understand how this control of power to a peripheral translates into average current draw, consider the 20-kΩ one-turn potentiometer. If it were powered directly from the 3-V coin cell supply, it would draw a constant 150 µA, completely overriding those things that can be done to otherwise reduce the average current draw on the coin cell to a few microamperes. By setting bit 7 of PORTA and thereby driving the RA7 pin to 3 V, then converting the analog input to AN0, and finally clearing bit 7 of PORTA, the average current draw is reduced by an amount proportional to the duty cycle of this operation. For example, assume it takes 30 µs to power-up the potentiometer, enable the analog-to-digital converter (ADC) module, carry out the conversion, power down the potentiometer, and disable the ADC module. If a conversion is carried out every 200 ms (i.e., five times a second), the average current draw due to the potentiometer will be reduced by a factor of 30 µs 30 µs _______ = _________ = 0.00015 200 ms 200000 µs The 150 µA instantaneous current becomes a negligible 0.023 µA average current. Each of the peripheral devices will be discussed as it is used in subsequent chapters. For now, the role of Figure 3-2 is to illustrate this control of current draw by each device. In the case of the LED, its current draw when turned on is on the order of 1 mA (given a voltage drop of about 2 V in the LED). Although this is higher than desirable as a constant load, if the LED is blinked for just 16 ms every 4 s for a duty cycle of 0.004, a visible blink of light will occur while contributing about 4 µA to the average current draw. Such blinking will be helpful for telling when an undebugged user program is running and not stuck somewhere due to a bug. The jumper allows the relatively heavy LED current to be shut down until such a bug is removed. 34 Chapter 3 Qwik&Low Board PIC18LF4321 Test points TP6 External interrupt INT2 FOSC/4 RE2 (RB2) RE1 RE0 RD7 1 MΩ Interrupt Direction 22.6 kΩ Detented rotary pulse generator (30 increments/revolution) with integral pushbutton Jumper RD4 1 kΩ LED LED (blinked for low duty cycle) switched power RD3 TP5 RD2 SSN ADC RD6 (RA3) VREF+ (RA1) AN1 switched power RA7 (RA0) AN0 20 kΩ One-turn potentiometer TP4 Ratiometric temperature sensor TP3 switched power Silicon serial number with one-wire interface 4.99 kΩ SPI SDO SCK (RC5) (RC3) RD5 VDD TP8 TP9 TP10 4PDT switch Controller + LCD Eight-character starburst LCD FIGURE 3-2 Qwik&Low MCU control of peripheral power Section 3.5 PICkit 2 Programmer Connection 35 3.4 POWER SWITCHING AND CURRENT MONITORING Figure 3-3 illustrates the circuit used to switch on and measure the coin cell current. If the digital multimeter (DMM) is not connected to the board, the power switch works alone to control the supply current. With the DMM connected to the board and set to its “off ” position, the board can be powered in either of two ways: • Flick on the power toggle switch for simplicity, without monitoring the current. • With the power switch off, rotate the DMM’s control knob to its “2 mA” (i.e., 2,000 µA full scale) position to monitor the supply current. Depending on what scales are traversed between the DMM’s “off” setting and its “2 mA” setting, the MCU may experience one or more voltage steps as the control knob is turned. For example, the DMM of Figure 2-10 has an internal resistance of 100 Ω on its “2 mA” scale. But it traverses a “200 µA” scale along the way having an internal resistance of 800 Ω. With its default startup FOSC = 1 MHz, the MCU draws about 400 µA initially, so with a coin cell voltage of 3.00 V, the MCU’s VDD steps through the sequence of 0 V to 2.67 V to 2.96 V (even with the LCD’s controller switched off). This sequence does not seem to produce a faulty startup. However, if a different DMM is used that causes an unreliable startup of the MCU when powered up in this way, the power-up sequence can be altered to: 1. Turn on the power switch. 2. Turn the DMM’s control knob from its “off” position through its various scales to its “2 mA” position. 3. Turn off the power switch. This discussion raises another point worth noting. Most low-cost DMMs feature a 2,000-count scale for all their measurements. That means that a “2 mA” (or a “2,000 µA”) scale has a resolution of 1 µA. If there is also a “200 µA” scale, it will have a resolution of 0.1 µA (good) but also an internal resistance that is, perhaps, eight times higher than that of the “2 mA” scale (bad). With the MCU being operated in an intermittently awake mode with a current in the range of a milliampere, VDD may exhibit a negative blip of tens or hundreds of millivolts each time the MCU awakens to do its useful work. This will not make a difference for digital transducers but may affect the behavior of transducers with analog voltage outputs as well as the MCU’s analogto-digital converter (ADC). Given this situation, a user can simply turn on the power switch for best results from an analog measurement, and turn off the power switch while making the corresponding coin cell current measurement. 3.5 PICkit 2 PROGRAMMER CONNECTION A new Qwik&Low board comes with its MCU already programmed with QwikBug. Consequently, it does not need the PICkit 2 programmer to load a user program into the chip. Instead, QwikBug uses the serial port connection for this purpose. QwikBug’s executive program, residing in the high addresses of the MCU’s program memory, 36 Chapter 3 Qwik&Low Board Header for MCU PICkit 2 PGC PGD GND VDD VPP DMM with 1 – 2000 µA scale − + 51.1 kΩ VDD Test leads with banana plugs I Power switch GND PGD/RB7 PGC (RB6) PIC18LF4321 (44 pins) NC Reset pushbutton VPP/MCLR CR2032 3 V coin cell + “Switch to QwikBug” signal Debug port (cable to PC serial port or USB to serial adapter) 5 1 MΩ 3 2 DB-9F serial connector 1 kΩ 100 kΩ TP1 (RX and TX are internally inverted) TP2 (RC7) (RC6) UART RX TX (RC0) 32768 Hz watch crystal Timer1 oscillator T1OSO (RC1) T1OSI 15 pF 15 pF FIGURE 3-3 Qwik&Low MCU support circuitry these are both good for more than three-quarters of the coin cell’s life.6 Effect Of Coin Cell Aging 37 reads in a user program downloaded from a PC and writes it into the low addresses of the MCU’s program memory. as shown in Figure 3-3.9 V. It uses the PGC (RB6) pin of Figure 3-3 to let the PC’s QwikBug utility get the attention of the MCU when it is running a user program.Section 3. the user program will be interrupted and will vector to the QwikBug executive program in the MCU. the characteristic shows no appreciable droop in the voltage over the first half of its rated life. the voltage is only down to 2. By sending a serial character to the Qwik&Low board. Whether or not it is asleep. Even after three-quarters of its rated life. An especially useful feature of a lithium cell is the flatness of its discharge characteristic. QwikBug takes advantage of the same debug mode employed by the PICkit 2 programmer. as shown in Figure 3-4. the clock rate used by the QwikBug executive and by the LCD controller. The user program will be paused and control will return to QwikBug. With a fixed load of 20 µA. Volts 3 2 Normal life 1 458 days Days 120 240 360 480 Nominal capacity = 220 mAh 220 mAh Life with 20 µA load = = 458 days 20 µA FIGURE 3-4 CR2032 discharge characteristic at room temperature with a 20 µA load current . The two exceptions are the temperature sensor (down to 2. But. All but two of the peripheral parts on the Qwik&Low board will operate down to 2. This will awaken the MCU if it is asleep.6 EFFECT OF COIN CELL AGING Over time. Both the MCU and the LCD controller are specified to operate down to 2.8 V).42 V even with FOSC as high as 8 MHz. 3.42 V. again.7 V) and the silicon serial number part (down to 2. the resulting wiggling of the MCU’s RX UART pin also wiggles the PGC pin. the CR2032 lithium coin cell will exhibit a decrease in its loaded output voltage. up to 2 s. The LCD controller’s CPU sleeps constantly until the MCU awakens it with a falling edge on its INT0 interrupt input. This oscillator (shown in Figure 3-3) can be used to clock either of two internal 16-bit counters. For such. The PIC18LF6390’s CPU then receives a serially sent string of ASCII-coded characters over an interval of 100 µs–200 µs. it provides an alternative to the use of the INTRC oscillator and the watchdog timer mechanism of Figure 2-6 and its low-current draw of 2. translates them.768-Hz watch crystal to provide 50 parts per million (ppm) frequency accuracy. together with the Timer1 counter. When the switch goes from off to on. Considering Figure 2-5.3) is made by turning on or off a low-power Timer1 oscillator configuration bit. drops to about 1. together with the Timer1 counter.7 WATCH CRYSTAL CIRCUITRY The Qwik&Low board’s MCU includes an optional low-power oscillator that can employ an external 32. and goes back to sleep. The author’s experience is that with the configuration selection LPT1OSC = OFF the Timer1 oscillator will reliably start up and run in less than 0. As such.8 QWIK&LOW LCD The PIC18LF6390 LCD controller. with the configuration selection LPT1OSC = ON the Timer1 oscillator may not start up and run at all. It includes a 3-V regulator to maintain the accuracy of the crystal oscillator even as VDD varies.2 s after it is enabled and will draw. For those boards that do start up. drawing just 5 µA to do so. the LCD. the LCD has little impact on current draw. push-to-break switch of Figure 3-5 permits power and input connections to be disconnected from the MCU and grounded. even as the rest of the chip sleeps. • It powers the LCD up and initializes it for reliable operation.38 Chapter 3 Qwik&Low Board 3. and the surrounding circuitry and connections are illustrated in Figure 3-5. stores the translated data into LCD registers in the chip. The low-power option is intended for use with VDD above 4 V.2 µA. the startup time can be measured in seconds. The Timer1 oscillator has two alternative configurations. Thus. With its inputs seeing very slow (37 Hz) changes to what is essentially a very low capacitive load. the Microchip application engineers do not recommend using the low-power option. the current draw. For operation of the chip with power from a 3-V coin cell. In contrast.5 µA. the display treats that operation as a reliable power-on reset. the switch serves two purposes: • It powers the LCD down to remove its current draw from a measurement of the board’s total current draw. Then the LCD module within the chip refreshes the display. the watch crystal oscillator plus Timer1 combination can provide any interval. about 6.5 µA. The configuration selection (discussed in Section 4. . Tperiod. 3. The 4PDT push-to-make. 1 µF GND VDD RB5 INT0 SPI SCK (RC3) TP11 (RC3) (RC5) SDO PIC18LF4321 TP13 FOSC/4 Test 4PDT points switch TP10 (RC4) VDD TP12 FIGURE 3-5 Qwik&Low LCD SEG0 Header For LCD PICkit 2 .8 Qwik&Low LCD 39 LCD PGC PGD GND VDD VPP 32 SEG31 COM3 COM2 COM1 COM0 Four backplane drivers Serial Peripheral Interface SCK SDI VPP/MCLR 475 kΩ VDD GND PGD PGC LCDbias3 32 frontplane drivers 0.1 µF 475 kΩ 0.Section 3.1 µF PIC18LF6390 LCD controller (64 pins) LCDbias2 LCDbias1 VDD 475 kΩ GND 0.1 µF 475 kΩ 0. note the shrouded 10-pin header located in the lower right-hand corner of the Qwik&Low board. the reset input pin). it is much more convenient to probe it at the test point labeled RB0/INT0 on the H4 header pattern.com. Figure 3-7 indicates that RB0.. The connection draws essentially no current from the Qwik&Low coin cell. and the eight other MCU pins shown in Figure 3-6. residing just to the left of the proto area. 3. While it could be probed as pin 8 of the MCU chip. 3. an analog-to-digital input).g.pin shrouded male header to mate with 10-conductor ribbon cable female header VDD RA2 Key RA5 RB1 RD0 RB0 RB3 RD1 RA4 FIGURE 3-6 Qwik&Low expansion header The LCD PICkit 2 connection is required during the manufacture of the board and probably not thereafter. for example. When looking for an otherwise unused pin. or in a supportive role (e. Later in the book the connection of the Qwik&Low board to a stepper motor driver board will be considered. . the occurrence of some event can be sensed by the CPU and signaled to a user by setting an otherwise unused pin high. or as a general-purpose I/O pin. It is designed to provide a 10-conductor ribbon cable connection for power. External to the chip. For example.. is available for this purpose. the LCD source code developed by Alex Singh is available at www. ground.10 SUMMARY OF MCU PIN USE Each of the pins of the PIC18LF4321 chip may be used for its dedicated internal function (e.40 Chapter 3 Qwik&Low Board 5 × 2 .g. That board and its associated stepper motor employ their own wall transformer power supply. a pin takes on a role determined by its connection to other devices.9 EXPANSION HEADER Referring again to Figure 2-10. If there is a feature to be added to the PIC18LF6390.qwikandlow. the chart of Figure 3-7 will be of assistance. SPI clock for LCD Optional stepper DIR (pin 9 of H6) Optional stepper STEP (pin 10 of H6) I/O for DS2401 Power for DS2401 silicon serial number SPI input SPI output to LCD TX output to PC TP6 TP9 TP5 TP8 TP1 FIGURE 3-7 MCU pins and their uses.10 Summary Of MCU Pin Use 41 H4 Proto Area x x x x x x x x x x x x x x x x Pin Function Qwik&Low Function 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 RC7/RX RD4 RD5 RD6 RD7 GND VDD RB0/INT0 RB1/INT1 RB2/INT2 RB3/CCP2 ICPGC ICPGD RB4 RB5 RB6/PGC RB7/PGD MCLR/VPP RA0/AN0 RA1/AN1 RA2/AN2 RA3/AN3/VREF+ RA4 RA5 RE0 RE1 RE2 VDD GND RA7 Fosc/4 T1OSO ICRST ICPORTS T1OSI RC2/CCP1 RC3/SCK RD0 RD1 RD2 RD3 RC4/SDI RC5/SDO RC6/TX RX input from PC or from RX' proto pin Red LED Chip select for starburst LCD Power for temperature sensor Pushbutton input TP2 TP10 x x RPG interrupt input x (Unused debugging feature) (Unused debugging feature) (Reserved by background debug mode) (Reserved by background debug mode) Reset pushbutton AN0 input from potentiometer Input from temperature sensor Connected to RD6 for VREF+ input x x x TP4 x x x TP3 Power for pushbutton and RPG direction RPG direction input Power for RPG interrupt input Power for potentiometer Output of CPU clock 32768 Hz watch crystal for Timer1 osc. H6 Connector x x x x x x H3 PICkit 2 Pin Number Test Point .Section 3. (Unused debugging feature) Tied to VDD to avoid 28-pin emulation 32768 Hz watch crystal for Timer1 osc. 42 Chapter 3 Qwik&Low Board If a new peripheral chip is added to the board in the proto area. . Figure 3-7 will help to select MCU pins that will not conflict with an already dedicated external connection. MCU pins that are brought out to the H4 header pattern simplify the connections between the MCU and the peripheral chip. The first 10 lines of T1. it should be pointed out that multiple lines of comments can be inserted into a source file by bracketing the comments between /* and */ Alternatively. with indenting used to indicate that three functions are called from the main program. It explains the code and its implications. 4.c indicate what the program does. It concludes with information on how to obtain. The Program Hierarchy consisting of the next few lines lists the functions making up the program.1 OVERVIEW This chapter introduces the first template program.c TEMPLATE PROGRAM The first program to be considered is listed in Figure 4-1.Chapter 4 A FIRST TEMPLATE PROGRAM (T1.2 A T1. The function 43 . //. and run Microchip’s free C18 compiler. If the reader is not familiar with coding in C. a double slash. tells the C compiler to ignore the remainder of a line.c) 4. install. * Sleep for 16 ms (nominal). * Toggle RC2 output every 16 milliseconds for measuring looptime with scope.c template . RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period. // Counter for blinking "Alive" LED /******************************* * Constant strings ******************************* */ FIGURE 4-1 T1. * Blink LED on RD4 for 16 ms every four seconds. RA6=Fosc/4.1V.44 Chapter 4 A First Template Program (T1. * * Current draw = 4 uA (with LED and LCD switched off) * ******* Program hierarchy ***** * * main * Initial * BlinkAlive * Pushbutton * ******************************* */ #include <p18f4321. nominal Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. * Check pushbutton and turn on LED continuously while it is pressed.c ****************** * * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz. using watchdog timeout for wakeup. nominal Deselect low-power Timer1 oscillator // Define PIC18LF4321 registers and bits /******************************* * Global variables ******************************* */ unsigned int DELAY. // Counter for obtaining a delay unsigned char ALIVECNT.c) /******* T1. // Initialize everything while (1) { PORTCbits. } } /******************************* * Initial * * This function performs all initializations of variables and registers. // Sleep.2 A T1. for measuring loop time BlinkAlive(). // Blink "Alive" LED Pushbutton(). letting watchdog timer wake up chip Nop().c Template Program 45 /******************************* * Variable strings ******************************* */ /******************************* * Function prototypes ******************************* */ void Initial(void).RC2. ******************************* */ void Initial() { OSCCON = 0b01100010. } /////// Main program /////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). // Toggle pin. /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x.RC2 = !PORTCbits. // Turn on LED while pushbutton is pressed Sleep(). // Use Fosc = 4 MHz (Fcpu = 1 MHz) FIGURE 4-1 (continued) . void Pushbutton(void). while(--DELAY){ Nop().Section 4. Nop(). void BlinkAlive(void). } } // Turn off LED // Increment counter and return if not 250 // Reset ALIVECNT // Turn on LED for 16 ms every 4 secs /******************************* * Pushbutton * * This function overrides the role of the BlinkAlive function and turns on * the LED for the duration of a pushbutton press. TRISE = 0b00000010. Nop(). } // Power up the pushbutton // Delay one microsecond before checking it // If pressed // turn on LED // Power down the pushbutton FIGURE 4-1 (continued) .RA3 pins analog. PORTE = 0. ******************************* */ void Pushbutton() { PORTEbits. TRISB = 0b01000100. count 250 looptimes ******************************* */ void BlinkAlive() { PORTDbits. TRISD = 0b10000100.RD7) { PORTDbits.RD4 = 1. } PORTEbits.RE0 = 1. PORTB = 0.RE0 = 0.SBOREN = 0. if (++ALIVECNT == 250) { ALIVECNT = 0.RA1.SWDTEN = 1. } // // // // // // // RA0. Delay(50000). PORTC = 0. WDTCONbits.RD4 = 1. * With a looptime of about 16 ms.RD4 = 0.c) ADCON1 = 0b00001011.RA2.46 Chapter 4 A First Template Program (T1. PORTDbits. RCONbits. Enable watchdog timer /******************************* * BlinkAlive * * This function briefly blinks the LED every four seconds. TRISC = 0b10000000. TRISA = 0b00001111. PORTD = 0b00100000. PORTA = 0. if (!PORTDbits. ALIVECNT = 247. Section 4.3 Configuration Selections 47 name main is used by C programs to indicate to the C compiler where program execution is to begin. The line #include <p18f4321.h> is needed by the C compiler to assign addresses to register names like OSCCON, TRISA, and WDTCON. Also listed in the p18f4321.h file are the bit numbers associated with bit names like RC2, SBOREN, and SWDTEN. For example, SWDTEN is the name of bit 0, the least-significant bit of the WDTCON register. Because the compiler knows SWDTEN is the name of bit 0, it is not necessary for the user to know it. Knowing the names of bits and the registers in which they reside is sufficient. 4.3 CONFIGURATION SELECTIONS Listed next are the configuration choices for the MCU. Actually, these choices have already been made when QwikBug was programmed into the chip. When T1.hex (the compiled version of T1.c) is downloaded to the Qwik&Low board, QwikBug ignores the configuration selections. They are shown here to indicate the configuration options under which the T1.c template program will run. And they indicate an essential part of the T1.c file were it to be programmed into the MCU with the PICkit 2 programmer instead of being downloaded by QwikBug. Many of these configuration choices are described in Figure 4-2, which shows the choice selected in boldface. The two watchdog timer choices for WDT and WDTPS were described in Figure 2-6. OSC = INTIO1 Selects internal oscillator block; uses RA6 for Fosc/4 output; uses RA7 for I/O. = INTIO2 Selects internal oscillator block; RA6 and RA7 both available for I/O. = RCIO Selects external RC oscillator on RA7; RA6 available for I/O. = LP Uses RA6 and RA7 for 32768 Hz crystal oscillator. = XT Uses RA6 and RA7 for 1-4 MHz crystal oscillator. = HS Uses RA6 and RA7 for 4-25 MHz crystal oscillator. = HSPLL Uses RA6 and RA7 with 10 MHz crystal and phase-locked loop for 40 MHz oscillator. = EC Uses an external oscillator into RA7; uses RA6 for Fosc/4 output. = ECIO Uses an external oscillator into RA7; uses RA6 for I/O. (a) Oscillator power-up configuration PWRT = ON = OFF Introduces a delay of about 66 ms after the chip detects that power has been turned on and before CPU clocking begins. No 66 ms delay. (b) Power-up timer FIGURE 4-2 Configuration selections 48 Chapter 4 A First Template Program (T1.c) CCP2MX = RB3 = RC1 CCP2 input/output is multiplexed with the RB3 pin. CCP2 input/output is multiplexed with the RC1 pin. (c) CCP2 configuration LPT1OSC = ON = OFF Timer1 oscillator is configured for low-power, 32768 Hz operation. Timer1 oscillator is configured for higher-power, higher frequency operation. (d) Timer1’s oscillator configuration DEBUG = ON = OFF Background debugger is enabled - needed by QwikBug. Background debugger is disabled; RB6 and RB7 available for I/O. (e) Background debug mode use LVP = OFF = ON This choice is needed for normal, fast start from reset. This choice can cause a delay of several seconds coming out of reset. (f) In-circuit serial programming (ICSP) option that permits programming voltage = VDD MCLRE = ON = OFF RE3/MCLR pin is an active dedicated active-low master reset input. RE3/MCLR pin is a general purpose RE3 I/O pin. (g) Optional reset pin PBADEN = DIG = ANA PORTB bits 4,3,2,1,0 are configured as digital I/O pins at reset. PORTB bits 4,3,2,1,0 are configured as analog input pins at reset. (h) PORTB reset configuration FIGURE 4-2 (continued) The OSC choice of INTIO1 selects the primary, power-on reset, oscillator for the chip. This choice can be overridden at any time by the user program by changing the content of the OSCCON register (see Figure 2-3). The brownout-reset options are described in Figure 4-3. The original intent of a brownout reset was to stop the clocking of the CPU when VDD drops below a specified threshold level, as when a power switch is opened. Here, the brownout-reset mechanism is used at startup, to hold the chip in the reset state until sometime after the power switch connects the coin cell to the VDD line supplying the MCU. With BORV = 3 and with the power-up timer enabled with PWRT = ON, clocking of the CPU begins about 66 ms after VDD rises above about 2.1 V. Should the power Section 4.3 Configuration Selections 49 Supply voltage 3.0V 2.8V 2.1V 2.0V 1.0V Time FCPU with BORV = 3 and PWRT = ON OFF OFF ON PWRT delay (66 ms) FCPU with BORV = 2 and PWRT = ON OFF OFF ON PWRT delay (66 ms) (a) Power-on behavior of brownout reset BOR = SOFT Brownout reset controlled by SBOREN bit in RCON register and enabled at reset = OFF Brownout reset disabled (0 µA current draw) = ON Brownout reset enabled (≈34 µA current draw) = NOSLP Brownout reset in run and idle modes; disabled in sleep mode (b) Brownout-reset configuration SBOREN =1 =0 Brownout feature enabled Brownout feature disabled (c) Software control of the brownout-reset feature when BOR = SOFT (SBOREN is bit 6 of the RCON register) FIGURE 4-3 Brownout-reset options 50 Chapter 4 A First Template Program (T1.c) switch exhibit contact bounce, a reliable startup will ensue, even after one or more false starts. With BOR = SOFT, the brownout feature can be disabled after startup by clearing the SBOREN bit in the RCON register to eliminate its current draw of about 34 µA. 4.4 GLOBAL VARIABLES The Global variables section of T1.c assigns two variables to the program, both as unsigned numbers. The unsigned int variable, DELAY, ranges from 0 to 65,535. The unsigned char variable, ALIVECNT, ranges from 0 to 255. Sophisticated C code writers may note that the DELAY variable is used only within the Initial function. Once initialized, ALIVECNT is used only within the BlinkAlive function. In both cases, the variable could have been defined to be local to the function within which it is used. However, because the definition of local variables produces extra machine code and extra execution time by Microchip’s C18 compiler, only global variables will be used throughout this book. 4.5 BIT MANIPULATIONS As a programming language, C offers no direct support for defining a bit type or for testing or modifying 1 bit of a register or variable. Microchip’s C18 compiler alleviates this deficiency in the case of registers. Thus WDTCONbits.SWDTEN = 1; will set the SWDTEN bit in the WDTCON register. For testing or manipulating a bit of a variable, the C18 compiler does not provide the same support. Thus ALIVECNTbits.7 = 0; will generate a compiler error rather than generating code that will clear bit 7 of the RAM variable, ALIVECNT. When writing code for a microcontroller, a commonly recurring need arises for flag bits that can be set, cleared, and tested. Because the PIC18LF4321 has 512 bytes of RAM available, dedicating some of these to serve as two-valued flags is not unreasonable. Thus, in the template program of the next chapter, a char (8-bit) variable named PBFLAG is introduced to distinguish between operation before the pushbutton is first pressed and subsequently. Before the pushbutton is first pressed, PBFLAG is cleared to zero with the line PBFLAG = 0; and the display shows the message PRESS PB After the pushbutton is pressed, PBFLAG is set to one with PBFLAG = 1; Section 4.7 A Calibrated Delay Macro 51 and the display switches to its ongoing program use. The flag is tested with if (!PBFLAG) { <do these tasks before pushbutton is first pressed> } or with if (PBFLAG) { <do these tasks if pushbutton has already been pressed> } The pushbutton can be powered up, as shown in Figure 3-2, by setting RE0. Then RD7 can be read to set NEWPB if RD7 is low (i.e., if the pushbutton is pressed) NEWPB = !PORTDbits.RD7; This flag is compared with the value of NEWPB found some time earlier and saved in OLDPB with if (!OLDPB && NEWPB)// Look for last time = 0, now = 1 { <do these tasks if pushbutton is newly pressed> } 4.6 FUNCTION PROTOTYPES Each function, other than main, must be listed in the Function prototypes section, to indicate the type (e.g., char) of any parameters to be passed to the function other than the global variables, and the type of any parameter to be returned by the function. Throughout this book all parameters will be passed to a function as global variables. Furthermore, within a function, local variables will be avoided. The reasons for these decisions are: • Parameters passed in the call of the function add significantly to both the resulting function code and its execution time. The latter issue is a major theme of this book because an increase in execution time translates into a proportional increase in average current draw. • Local variables do the same, increasing both the amount of code and the execution time. Furthermore, only global variables can serve as watch variables for QwikBug. Thus, this decision fosters the debugging of new program code. 4.7 A CALIBRATED DELAY MACRO The Macros section of T1.c includes a single macro definition: #define Delay(x) DELAY = x; while(--DELAY){ Nop(); Nop(); } 52 Chapter 4 A First Template Program (T1.c) This tells the C18 compiler that, when it subsequently sees the character sequence: Delay(50000) it should make the substitution: DELAY = 50000; while(--DELAY){ Nop(); Nop(); } The compiler will generate code that, when executed, will load 50,000 into the unsigned int variable, DELAY, then decrement DELAY. If the decremented value of DELAY equals zero, then the execution of the macro is done. Otherwise two Nop() macros are executed before DELAY is decremented again. Each Nop() macro is compiled to a “no operation” assembly language instruction. What is interesting here is the relationship between the parameter value and the duration of the resulting delay. The insertion of the line Delay(value); (4-1a) will create a delay in the program execution of exactly delay = (10 × value) clock periods for value < 256 or delay = (10 × value) + 1 clock periods for value ≥ 256 Ignoring the additional clock period for value ≥ 256 and the 2% accuracy of the internal clock, this macro can be used to generate a calibrated delay. With FOSC = 4 MHz, the CPU clock period equals one microsecond and the delay will equal delay = 10 × value microseconds given the global variable declaration unsigned int DELAY; (4-1b) (4-1c) In general, it is difficult to predict how the C18 compiler will optimize the code of a program. Alex Singh discovered that without the inclusion of any assembly language code within the Delay() macro, it would be compiled in three different ways in different source files (optimized for speed of execution, optimized for minimal code generation, or not optimized at all). However, with the inclusion of any assembly code in a macro definition, the macro is always compiled to the same machine code. 4.8 MAIN FUNCTION The main function begins with a call of Initial. Then the main function enters an infinite loop in which it toggles a pin that can be probed on one of the Qwik&Low board’s H4 header pins. With the help of a scope, the time the CPU takes to traverse the loop can be measured as the time from a rising edge of the RC2 pin to the next falling edge. The main program then calls BlinkAlive and Pushbutton in succession before executing the Sleep macro. Note that the C compiler identifies the RC2 bit within the PORTC register as PORTCbits.RC2 and toggles it with PORTCbits.RC2 ^= 1; selects FOSC = 4 MHz and a CPU clock rate of FCPU = 1 MHz. Its output can be left justified into ADRES. 4.RB0 = 0. accessed as ADRESH. will generate a 1-µs positive pulse on the RB0 pin.9 8-BIT AND 16-BIT REGISTERS The role of the Initial function is to initialize registers. and status bits associated with that function will be described.Section 4. Then the C code to make use of that function will reduce to interactions with those registers and bits. the 10-bit output of the analog-to-digital converter can be right justified into the 16-bit register. Inserting the macro Nop(). it draws 1. control and status bits. and treated as an unsigned int variable ranging from 0 to 1. range from 0 to 255. Most of the PIC18LF4321 registers are 8 bits long. PORTBbits. it can be seen that the first line of the Initial function of Figure 4-1 OSCCON = 0b01100010.RB0 = 1.6 relative to the average current draw with FOSC = 8 MHz. this means that a sequence like PORTBbits. Throughout this book.6 _______ × 100 = 18% 5. The least-significant 2 bits of the 10-bit conversion reside in the upper 2 bits of ADRESL and are ignored. as a multiple-function hardware module of the PIC18LF4321 chip is discussed. considerably better.10 CLOCK RATE CHOICE Referring back to Figure 2-3. All of the registers. The upper 8 bits. it will be dealt with one function at a time. ADRES. control bits. . The few that are 16 bits long generally carry two names. it is sometimes useful to use the analog-to-digital converter as an 8-bit converter. an application suffers an average current draw penalty of 6. For intermittent sleep mode operation with FOSC = 4 MHz. This illustrates that while the MCU is awake and running with FOSC = 8 MHz. The decision to select FOSC = 4 MHz rather than the higher value of 8 MHz is driven largely by the data of Figure 2-4.023. On the other hand. Since most instructions are executed in one CPU clock period. a heavy current for the coin cell while undebugged code leaves the chip constantly awake.7 Clock Rate Choice 53 4. For example. The choice of FOSC = 4 MHz drops this steady current draw of a malfunctioning program to a milliampere. Sometimes a short pause is required between the activation of a process and the reading of the output of the process. can be used to insert a pause of 1 µs in the execution of the code as the CPU executes a single-cycle “no operation” machine instruction.6 − 5.750 mA. and variables. These are RD0 and RD1. the brownout reset module is shut down. and VREF+/AN3 Adding one or two additional analog input channels will be discussed in Chapter Nine. the slow INTRC internal oscillator of Figure 2-3 or the slow Timer1 crystal oscillator of Figure 3-3 will present an excellent alternative for applications that can deal with the slow execution of a CPU clock that executes only about eight machine instructions every millisecond. Input/output configuring is carried out by setting (input) or clearing (output) the TRIS register bits. 4. given that the applications discussed in this book will usually operate in the intermittent sleep mode. 5.13 BROWNOUT MODULE DISABLING After initializing the oscillator and the states of the I/O pins. and the watchdog timer of Figure 2-6 is started counting (from zero). These pins are shown in Figure 3-2. MCU pins not connected to anything on the Qwik&Low board should be made outputs. For now it is left to idle high. and 0 as outputs. the brownout reset mechanism will have resolved any powering-up issues and the LCD controller will have had time to initialize itself. sets up bits 7 and 2 of PORTD as inputs and bits 6. Given the Qwik&Low I/O connections of Figure 3-2. 4. the choice used in the T1. 3.c. During this time. Thus the initialization TRISD = 0b10000100.11 ANALOG PINS VERSUS DIGITAL I/O PINS The initialization of ADCON1 in general selects which of the chip’s possible 13 inputs to the analog-to-digital converter will be used as analog inputs and which will be used as digital I/O pins.c) The choice of FOSC = 4 MHz versus an even slower clock rate is driven by Figure 2-8. AN1.54 Chapter 4 A First Template Program (T1.12 DIGITAL INPUTS VERSUS OUTPUTS Each digital I/O pin used by the Qwik&Low board must be properly configured as either an input or an output. The user program variables (ALIVECNT in this case) are initialized. At the completion of the delay. All of the PORTD output port pins are initialized to zero except for RD5 that is set to one via the line PORTD = 0b00100000.c code is to select the four ADC pins AN0. When such is not the case. 4. also set up as outputs. to eliminate a current draw of about 34 µA on the coin cell. the Initial subroutine uses the Delay macro to wait half a second before continuing. whether or not it is used by the code of T1. 4. AN2. 1. A 1→0 transition from this output pin will be used to wake up the LCD controller. . The pins that are unused by the board are indicated as such in Figure 3-7. the time selected by the WDTPS = 4 configuration choice (see Figure 2-6).c input/output connections . As shown in Figure 4-4. Thus the BlinkAlive MCU TRISE PORTE 7 6 5 4 3 2 1 0 0 TRISD PORTD RE0 22. For slow events.14 MAIN LOOP Upon returning from the Initial function. the main function toggles the RC2 output pin.12 Main Loop 55 4. the resulting loop times can be counted to derive the event timing.Section 4. a scope can probe this pin (labeled RC2/CCP1 on the H4 strip) to verify that the watchdog timer’s timeout period is close to 16 ms.6 kΩ RD7 Jumper RD4 LED Pushbutton 7 1 6 5 4 0 3 2 1 0 TRISC PORTC 1 kΩ 7 6 5 4 3 2 0 1 0 Oscilloscope RC2 FIGURE 4-4 T1. 000 ms = 4 s the ALIVECNT variable will have been incremented to 250.56 Chapter 4 A First Template Program (T1.15 COMPILATION Set up a folder C:\WORK to hold source files (e.c) as well as the files generated as a result of the compilation of source files. Consequently.qwikandlow. a Sleep macro should always be followed by a Nop macro (translated to the chip’s “no operation” one cycle instruction). For Windows XP.bat and two desktop short cuts Work DOS for work that can be downloaded to the reader’s desktop. Download from www. the CPU may not carry out the operation of the next instruction correctly.com website has a batch file MakeWork. reset to zero.exe and the source file T1.. Clicking on the DOS for Work desktop icon opens a DOS window with a C:\Work> prompt. so every 250 × 16 ms = 4. Each call occurs approximately 16 ms after the previous one. and the LED driven from RD4 will be turned on. the. 4. it is useful to have a desktop icon that opens into this folder and another desktop icon that opens a DOS window into this folder.com into the new C:\Work folder the batch file C18. PORTDbits.c) function is called during each pass around the main loop.c .qwikandlow. It remains on until 16 ms later when BlinkAlive is again called and RD4 is cleared with the opening statement of BlinkAlive. In addition. The batch file creates a new folder C:\Work Clicking on the Work desktop icon opens the C:\Work folder. Note this use by the C compiler of the term PORTDbits rather than the term PORTD when accessing a specific bit (RD4) in a register (PORTD). Upon awakening from sleep. The main function closes with a Sleep macro that is translated by the C compiler into the PIC18LF4321’s “sleep” instruction. By having that next instruction be a “nop” instruction.RD4 = 0. T1. no intended operation is passed over. It understands C and it flags syntax errors.c file. Texec.15 Compilation 57 Finally.com. about 16 ms). The duration between blinks should be 32 loop times (i. install the student version of Microchip’s C18 compiler including their pathlist settings.e. measure both Tperiod and the maximum value in each case of Tactive. FOSC/4 at test point TP6. click on the DOS for Work icon. Each blink should last for one loop time (i.c file in which the BlinkAlive function and its call are removed from the file. This will produce the conditions for measuring PCPU.c file into T1faster. type C18 T1 To edit the T1. any text editor can be used. Then after the C:\Work> prompt.5. This can be found on the Microchip website by Googling +“MPLAB C18 compiler” +“Student Edition” To try compilation. instead of executing the 100 clock periods called for there. Make sure that the MCU sleeps between loop times. Recompile. you will carry out the eight INTOSC clock source tests of Figure 2-8. and run the result. However. . about 0. Initialize OSCCON to 0b01110010 and OSCTUNE to 0b10000000.Section 4. In response to each pushbutton press. make two measurements.. download. 4-2 Pushbutton modification Form a T1pb.crimsoneditor. The Crimson editor is a popular and free one..c file. a) Measure the current draw with the LED jumper removed.5 second). How do these compare between the programs? 4-5 Oscillator Control For this project. just execute enough code to switch the oscillator frequency to the next value in response to a pushbutton press. Referring to Figure 2-5. Modify the Pushbutton function so that it blinks on for only 16 ms in response to each pushbutton press. blink the LED twice. To change OSCCON just once for each pushbutton press. and Iavg for the first row of the table of Figure 2-8. PROBLEMS 4-1 Faster blinking Modify the T1. 4-4 Measurements For each of the above programs. Each of the seven pushes of the pushbutton will yield the conditions for the remaining rows (ignoring the row for the INTRC clock source).c so as to blink the LED every second. available from. Is there any measurable difference between the current draw for these programs? b) Probe the MCU’s CPU clock. define and use the two flag variables NEWPB and OLDPB discussed at the end of Section 4. 4-3 Another pushbutton modification Form a T1pb2. as shown in Figure 5-1b.Chapter 5 SPI BUS AND THE LCD (T2. The SPI bus is a fast serial interface. introduces a Display function for sending a variable string to the display. as shown in Figure 5-1a.c) 5. He has developed an elegant implementation of the LCD controller specification of this chapter. The chapter begins with an explanation of the MCU’s and the LCD controller’s Serial Peripheral Interface (SPI) and how it is used for the fast serial transfer of display strings to update the LCD. 5. In response to writing a byte to the MCU’s SSPBUF register. the 8 bits are shifted out of its SDO (serial data out) pin. T2.c. 58 . synchronized to eight clock pulses on its SCK (serial clock) pin.2 SERIAL PERIPHERAL INTERFACE The PIC18LF4321 MCU and the PIC18LF6390 LCD controller each use their SPI for the communication of display messages from the MCU to the LCD controller.1 OVERVIEW This chapter is based on the development of the firmware for the LCD controller by Alex Singh. A template program. Section 5. its LCD module refreshes the LCD display at a 37 Hz refresh VDD 4PDT switch VCC VDD MCU PIC18LF4321 RD5 INT0 SCK SPI master SDO SDI GND SCK SPI slave VDD LCD controller PIC18LF6390 LCD GND (a) Connections between MCU and LCD controller Wake up LCD controller RD5 Clear flag SSPIF f lag SCK Flag set automatically upon completion of transfer SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 Write to SSPBUF to initiate 8-bit transfer 8 µs (b) Waveforms FIGURE 5-1 MCU’s SPI use for LCD display . and load the results into LCD data registers before returning to sleep. interpret them into their 14-segment “starburst” representation.2 Serial Peripheral Interface 59 The MCU signals the LCD controller to wake up with a one to zero falling edge from its RD5 output pin to the LCD controller’s INT0 interrupt input pin. the LCD controller’s CPU awakens to receive a string of characters from the MCU. While the LCD controller’s CPU sleeps. Upon reception of this falling edge. the LCD controller can accept SPI inputs at any of the MCU’s SPI clock rates.60 Chapter 5 SPI Bus And The LCD (T2. With each 1-byte transfer taking just the 8 µs dictated by an SCK clock output that consists of eight pulses of the MCU’s FOSC/4 CPU clock. and program execution waits until the SSPIF flag is set before clearing SSPIF and writing the next byte to SSPBUF. the first byte of the sequence is written to the SSPBUF register. . For the connection of Figure 5-1a to function properly. It is also important for the MCU and the LCD controller to agree on the polarity of the SCK pulses. The MCU’s SPI registers and their initialization to produce the waveform of Figure 5-1b are illustrated in Figure 5-1c.c) TRISC 7 6 5 4 3 2 1 0 x x 0 x 0 x x x Makes SCK/RC3 an output Makes SDO/RC5 an output SSPSTAT SSPCON1 PIR1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 SSPIF = SSPBUF 1: Transfer completed 0: Must be cleared before transfer A write to SSPBUF initiates a transfer (most-significiant bit first) (c) MCU’s SPI registers FIGURE 5-1 (continued) rate. With its use of FOSC = 8 MHz. very slow refresh rate. this interface helps to minimize the awake time of both the MCU when it deals with the display and the LCD controller when it awakens to receive an update. To send a sequence of bytes. Figure 5-1b also illustrates the role of the MCU’s SSPIF flag that is set upon the completion of the 1-byte transfer. It is this combination of sleeping CPU. it is important for the MCU’s SPI to be set up as master and the LCD controller’s SPI to be set up as slave. • Whether it uses its fastest clock rate of Fosc/4 or a slower rate. The SPI has many options: • Whether the SPI module drives SCK (master mode) or uses SCK as a clock input (slave mode). • Whether the SCK pin idles high (as in Figure 5-1b) or low. The initialization of SSPSTAT and SSPCON1 shown in Figure 5-1c produces the waveforms of Figure 5-1b and produces the idlehigh SCK that the LCD controller expects. and low capacitance loading by the LCD pins that produces the small 5-µA current draw of the LCD and its controller when it is not being updated by a display string from the MCU. the SSPIF flag is cleared. The sequence begins with the dropping of the RD5 pin from one to zero. 5 6 7 8'' will produce . Before the first byte is written to SSPBUF. Before each subsequent byte is written to SSPBUF. the CPU waits for the automatic setting of the SSPIF flag at the completion of the 1-byte transfer before clearing the flag and writing the next byte. it is unimportant when this pin is raised again.3 Display Strings 61 Wake up LCD controller RD5 SSPIF flag SDO Clear SSPIF Write to SSPBUF CH0 CH1 CH2 CH3 CH4 CH5 CH6 CH7 Raise RD5 any time before sending another display string FIGURE 5-2 Display string format consisting of nine bytes (eight ASCII-coded characters plus an optional ASCII-coded decimal point) 5. with subsequent characters appearing in order to the right of this position. It is only necessary that it be high again when a subsequent message string is ready to be sent. 5 6 7 8 (b) Display strings and the LCD result FIGURE 5-3 Display string positioning of characters . Thus the first character sent will appear in the leftmost character position. Since the LCD controller only reacts to this falling edge. the decimal point is displayed with the character that precedes it.3 DISPLAY STRINGS The sequence of operations needed to update the entire display’s eight characters plus an optional decimal point via a new message string is shown in Figure 5-2. CH0 CH1 CH2 CH3 CH4 CH5 CH6 CH7 (a) LCD display. the SSPIF flag is cleared. the characters in a display string are arranged in the same order as shown in Figure 5-3b. If the 9 bytes include a decimal point. and then returns to sleep. the LCD controller interprets and displays the bytes. the ninth byte received is ignored. After receiving the 9 bytes. showing names of character positions ''1 2 3 4 5 6 7 8 '' will produce ''1 2 3 4 1 2 3 4 5 6 7 8 1 2 3 4 . If no decimal point is included in the string. With the character positions named as in Figure 5-3a.Section 5. 62 Chapter 5 SPI Bus And The LCD (T2.c) 5. FIGURE 5-4 Displayable characters .. x y z (b) Reinterpreted characters is reinterpreted as ° (degree symbol for temperature) A B C . The ASCII code for a question mark (0x3F). Character sent ? a b c . given the limitations of a starburst character representation. If any unrecognized codes are received.. it is reinterpreted as the corresponding upper-case character.....+−*/<>^ (a) Characters displayed in response to their ASCII codes.5 DECIMAL POINT Because the LCD includes an optional decimal point with each character position. the LCD controller treats the reception of the ASCII code for a decimal point as a special case.4 DISPLAYABLE CHARACTERS Any byte that is received by the LCD controller will be interpreted as: • A displayable character (see Figure 5-4a) • A reinterpreted character (see Figure 5-4b) ASCII code does not include the degree symbol for units of temperature. X Y Z Turn on all segments for that character position (c) Unaccounted-for 8-bit codes. If the LCD controller receives any lower-case letter.5678 Numbers: Upper-case letters: Recognized symbols: 0123456789 A B C . 5. For example. will be reinterpreted to display the degree symbol. X Y Z ()'. the LCD controller will turn on all segments of that character position to alert the user of a faulty choice.5678″ will show up as 1234. the nine-character display string ″1234. if received by the LCD controller. A more readable result will occur by sending "0. * Increment LCD's CHAR0:CHAR1 every second.C.Section 5. Consequently the display string ".c. * Blink LED on RD4 for 16 ms every four seconds.6 T2. The template program also illustrates several new considerations arising because of interactions with a second microcontroller. * Post PRESS PB message on LCD until first pushbutton push.1234567 5.c ****************** * * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz. A Display Template 63 with both the 4 and the decimal point in the CHAR3 position. * * Current draw = 7 uA (with LED and LCD switched off) * ******* Program hierarchy ***** * * main * Initial * Display * BlinkAlive * Time * Pushbutton * UpdateLCD * Display * ******************************* */ FIGURE 5-5 T2.12345678" will be displayed as . A DISPLAY TEMPLATE The template program of Figure 5-5 illustrates how to deal with the LCD display.1234567" to produce the following display 0.6 T2. one on the right side of each character position. using watchdog timeout for wakeup. * Sleep for 16 ms (nominal). The LCD display on the Qwik&Low board has eight decimal points. * Increment LCD's CHAR3:CHAR4 for each pushbutton press. /******* T2.c template . * Toggle RC2 output every 16 milliseconds for measuring looptime with scope.1234567 with the last character (8) ignored. // char NEWPB. // char LCDSTRING[] = "PRESS PB ". // unsigned char TENS. Display(void).h> #include <string. set if pushbutton is now pressed Flag. BlinkAlive(void). Flag. // unsigned char ALIVECNT. unsigned char i // Define PIC18LF4321 registers and bits // Used by the LoadLCDSTRING macro // // // // // // // // // // // Use internal osc. // /******************************* * Function prototypes ******************************* */ void void void void void void Initial(void). // char LCDFLAG. set if pushbutton was pressed last loop Scale-of-248 counter for blinking "Alive" LED Scale-of-62 counter of loop times = 1 second For display of seconds For display of pushbutton count Index into strings Sixteen-bit counter for obtaining a delay LCD display string /******************************* * Macros ******************************* */ FIGURE 5-5 (continued) . // char OLDPB. set after first press of pushbutton Flag. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period. nominal Deselect low-power Timer1 oscillator /******************************* * Global variables ******************************* */ char PBFLAG. Time(void). // unsigned char PBTENS.1V. Pushbutton(void). UpdateLCD(void). // unsigned int DELAY. // unsigned char TIMECNT. set to send string to display Flag.c) #include <p18f4321. RA6=Fosc/4. // unsigned char ONES.64 Chapter 5 SPI Bus And The LCD (T2. unsigned char PBONES. nominal Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. 6 T2.RA3 pins analog. // except RD5 that drives LCD interrupt PORTE = 0. for measuring loop time Blink "Alive" LED Display seconds Display pushbutton count Update LCD Sleep. PORTC = 0. // UpdateLCD(). others digital TRISA = 0b00001111. } } Initialize everything Toggle pin. // Send a blank to initialize state of SPI Delay(50000). // while (1) { PORTCbits. // Set I/O for PORTE PORTA = 0. letting watchdog timer wake up chip /******************************* * Initial * * This function performs all initializations of variables and registers. FIGURE 5-5 (continued) . // Reset TIMECNT TENS = '5'.RA2. ADCON1 = 0b00001011. // RA0. SSPBUF = ' '. // BlinkAlive(). // Set I/O for PORTA TRISB = 0b01000100. Nop(). // Pushbutton(). // Time(). A Display Template 65 #define Delay(x) DELAY = x. // Set I/O for PORTC TRISD = 0b10000000. // Initialize to 59 so first display = 00 ONES = '9'.RA1. // Now disable brown-out reset PBFLAG = 0. // Pause for half a second RCONbits.RC2 ^= 1. } #define LoadLCDSTRING(lit) strcpypgm2ram(LCDSTRING. PORTD = 0b00100000. // Set initial state for all outputs low PORTB = 0.Section 5. // Sleep(). // Nop().(const far rom char*)lit) /////// Main program /////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). // Set I/O for PORTB TRISC = 0b10000000. // Use Fosc = 4 MHz (Fcpu = 1 MHz) SSPSTAT = 0b00000000.c. // Flag to signal LCD update is initially off TIMECNT = 0. // Set I/O for PORTD TRISE = 0b00000010. ******************************* */ void Initial() { OSCCON = 0b01100010.SBOREN = 0. // Set up SPI for output to LCD SSPCON1 = 0b00110000. while(--DELAY){ Nop(). // Clear flag until pushbutton is first pressed LCDFLAG = 0. // Set flag to display } } } FIGURE 5-5 (continued) . /******************************* * BlinkAlive * * This function briefly blinks the LED every four seconds. // Update display string LCDSTRING[1] = ONES.c) PBTENS = '0'. ******************************* */ void Time() { if (PBFLAG) // After pushbutton is first pushed. count 4x62 = 248 looptimes ******************************* */ void BlinkAlive() { PORTDbits. // Reset ALIVECNT PORTDbits. PBONES = '1'. // Turn off LED if (++ALIVECNT == 248) // Increment counter and return if not 248 { ALIVECNT = 0. WDTCONbits.66 Chapter 5 SPI Bus And The LCD (T2. } } LCDSTRING[0] = TENS. LoadLCDSTRING("00 01 } // Initialize count of pushbutton presses // // // // // Initialize to unpressed pushbutton state Blink immediately Enable watchdog timer Display initial "PRESS PB" message Reinitialize LCDSTRING "). { if (++TIMECNT == 62) // count TIMECNT to 1 second { TIMECNT = 0.RD4 = 0. Display(). LCDFLAG = 1. display seconds. * With a looptime of about 16 ms. // Turn on LED for 16 ms every 4 secs } } /******************************* * Time * * After pushbutton is first pushed. // Reset TIMECNT for next second if (++ONES > '9') // and increment time { ONES = '0'. OLDPB = 0. ALIVECNT = 247. if (++TENS > '5') { TENS = '0'.RD4 = 1.SWDTEN = 1. // Synchronize LED blinking to counting TIMECNT = 61. // Save present pushbutton state } /******************************* * UpdateLCD * * This function updates the 8-character LCD once the pushbutton has * first been pressed.6 T2.c. // Update display immediately } else // Take action for subsequent PB presses { if (++PBONES > '9') // and increment count of PB presses { PBONES = '0'. if (++PBTENS > '9') { PBTENS = '0'. A Display Template 67 /******************************* * Pushbutton * * After pushbutton is first pressed. LCDFLAG = 1. } } FIGURE 5-5 (continued) . LCDFLAG = 0. // Delay one microsecond before checking it NEWPB = !PORTDbits.RE0 = 0. } } } LCDSTRING[3] = PBTENS.RD7. display pushbutton count. ******************************* */ void UpdateLCD() { if(PBFLAG && LCDFLAG) { Display(). // Set flag to display } OLDPB = NEWPB. // Power down the pushbutton if (!OLDPB && NEWPB) // Look for last time = 0.RE0 = 1. ALIVECNT = 0. // Update display string for simulated LCD LCDSTRING[4] = PBONES. // Set flag if pushbutton is pressed PORTEbits. if Time or Pushbutton has set LCDFLAG. // Power up the pushbutton Nop(). now = 1 { if (!PBFLAG) // Take action for very first PB press { PBFLAG = 1. ******************************* */ void Pushbutton() { PORTEbits.Section 5. 7 INITIALIZATION OF TWO MICROCONTROLLERS The PIC18LF4321 MCU and the PIC18LF6390 LCD controller each has its own poweron reset circuit. Thus. Subsequently. proper initialization sequence of instructions. // Send byte while (!PIR1bits. Also. driven high.c template program. the RD5 pin of PORTD is set up as an output. and SDO will have been correctly initialized. The LCD controller powers up in the same way. all three output lines. // Wait for transmission to complete } PORTDbits.SSPIF = 0. the MCU’s Initial function includes a half-second delay followed by a disabling of the brownout-reset circuit.RD5 = 1.68 Chapter 5 SPI Bus And The LCD (T2.SSPIF). First. // Wake up LCD display for (i = 0. RD5. // Clear SPI flag SSPBUF = LCDSTRING[i]. but with enough leeway to account for any difference in the brownout modules’ threshold voltages and for the more extensive initialization required by the LCD controller. when the MCU is ready to send its first display string to the LCD controller. 5. Also it is important for the LCD controller to have initialized itself before the first display string is sent to it by the MCU. it is called . // Return RB5 high.8 SPI INITIALIZATION The initialization of the serial peripheral interface consists of the initialization of the SSPSTAT and SSPCON1 registers with the values shown in Figure 5-1c.c) /******************************* * Display() * * This function sends LCDSTRING to the LCD. 5.RD5 = 0. it is called in the Initial function when it displays “PRESS PB”. It uses a shorter delay. followed by the shutting down of the brownout-reset module to eliminate its constant 34 µA current draw on the coin cell. Each one has to deal with contact bounce in the power switch. ******************************* */ void Display() { PORTDbits. Accordingly. i++) { PIR1bits.9 THE DISPLAY FUNCTION AND LCDSTRING The Display function is called twice within the T2. Any power switch contact bounce occurring during this half second will reset the MCU and start up again with the same. SCK. i <= 8. ready for next string } FIGURE 5-5 (continued) 5. to keep from being corrupted by power switch contact bounce. The function then waits for the completion of the transfer (signaled by the setting of the SSPIF flag) before sending the next character. when the Time function and the Pushbutton function update individual characters in LCDSTRING. the Pushbutton function increments a counter. After clearing the SPI’s SSPIF flag.11 The Pushbutton Function 69 by the UpdateLCD function after the pushbutton has first been pressed. and LCDSTRING[1] = UNITS. the sequence of events shown in Figure 5-2 occur. it is called by the UpdateLCD function to display the elapsed seconds and to update the number of pushbutton presses. the displayed time is incremented every second (within the accuracy of the watchdog timer’s nominal 16 ms timeout period).10 THE TIME FUNCTION Within the Time function. 5. the line char LCDSTRING[] = "PRESS PB ". 5. insert the ASCII characters stored in the TENS and ONES variables into the first 2 bytes of LCDSTRING.c template program does this in several ways. RD5 is raised. The Display function begins by dropping RD5 to awaken the LCD controller. The T2. The lines leading up to these lines increment the two-digit ASCIIcoded number in TENS:ONES from 00 to 59 and back to 00. // LCD display string both defines LCDSTRING as a char array and initializes it to contain the nine characters between the quotes. Thereafter. The test of PBFLAG maintains the initial startup message on the display PRESS PB until the first press of the pushbutton. When the Pushbutton function has updated LCDSTRING in response to . PBTENS: PBONES. In the Global variables section. At the end of the Initial function. ready for the next call of Display. When the string of characters is sent to the display. After all characters have been sent. each character is written to the SPI’s SSPBUF register. the lines LCDSTRING[0] = TENS. the Display function sends this message string to the display and then uses a LoadLCDSTRING macro to reinitialize LCDSTRING with the initial values of the numbers that will be displayed subsequently. Before the Display function is called. It sends the nine characters to the display via the SPI bus. By counting 62 loop times in TIMECNT between each increment of TENS:ONES.Section 5. The setting of the LCDFLAG at the end of the Time function is used to signal the UpdateLCD function that LCDSTRING has been changed and that the LCD should be updated accordingly. LCDSTRING must be loaded with the nine ASCII-coded characters to be sent to the display.11 THE PUSHBUTTON FUNCTION Like the Time function. when the first press occurs. to signal the UpdateLCD function to overwrite the PRESS PB message with a time of 00 and a number of keypresses of 01. RD7 will be read as a one and NEWPB will be zero. To understand how the MCU detects a pushbutton press. 5-3 Blast off counter Change the display of elapsed time to count down from an initial value of 10. the RD7 input will be read as a zero and the line NEWPB = !PORTDbits. The state of the pushbutton one loop time (i. as per Figure 2-7. When zero is reached: a) Fill the screen with eight asterisks and stop further updating of the display.RD7. Before the first press after reset. After another 12 loop times. the ASCII values held in PBTENS and PBONES are incremented and then displayed by the UpdateLCD function. PBFLAG will be set and the initialization of ALIVECNT and TIMECNT will occur just for this initial press. RE0 is first raised. b) Move the count of pushbutton presses to the CHAR5:CHAR6 position on the display. If the pushbutton is not pressed. If the pushbutton is pressed.c) a pushbutton press. the UpdateLCD function will update the display during that same pass around the main loop. A 1-µs pause is introduced by the Nop() macro to allow time to change whatever capacitance is associated with the RE0 trace on the Qwik&Low board. write asterisks to the middle six character positions. b) Blank the screen. The ASCII values for zero and one initialized into PBTENS and PBONES are copied into LCDSTRING[3] and LCDSRING[4] and LCDFLAG is set.70 Chapter 5 SPI Bus And The LCD (T2. Twelve loop times later write asterisks to the middle two character positions. fill the screen with eight asterisks and stop any further updating of the display. it sets LCDFLAG. will put a nonzero value into the NEWPB byte serving as a flag. 16 ms) ago is held in OLDPB. refer back to the circuit of Figure 3-2. write asterisks to the middle four character positions. Consequently. After another 12 loop times. PBFLAG will equal zero. Keybounce has been suppressed by the loop time sampling of the keyswitch state.e. PROBLEMS 5-1 Initial message Change the initial message from “PRESS PB” to “WELCOME”. Accordingly. just as was done by the Time function. whenever either a 1-s tick or a pushbutton press occurs. after another 12 loop times.. The combined condition !OLDPB && NEWPB detects the beginning of a keypress. . On subsequent keypresses. Finally. 5-2 Relocation of display elements a) Move the elapsed time to the CHAR1:CHAR2 position on the display. The chapter begins with an examination of the MCU’s UART module. The chapter ends with the Measure. In contrast. scope measurements of execution 71 . its measurement results of cycle counts do not vary as the same code is run on multiple Qwik&Low boards. Consequently. For example.c program that compares the execution time of four functions that convert a variable into a decimal display. the Console window within QwikBug can provide the Qwik&Low board with two distinct opportunities: • It can be used by a user’s application program to supplement the eight-character LCD.Chapter 6 PC MONITOR USE (MEASURE.c) 6. it can display the 16-hex-digit serial number read from the DS2401 silicon serial number IC of Chapter Fifteen.1 OVERVIEW Because a user program has access to the same UART module in the MCU that is used by QwikBug. the counting of CPU cycles explored here produces exact CPU cycle counts. • It can be used by a user’s test program that exercises a user algorithm or function as a way to report measurement results. For example. and its ability to transmit data reliably to the PC using the MCU’s internal oscillator having a ±2% frequency accuracy. its setup. this chapter will end with a Measure. When compared with the use of a scope to measure execution times in units of microseconds.c template program. Thus. with the chip’s internal oscillator being divided down by either 16 or 64 followed by a divide-by-(N + 1) counter. each frame consisting of 160 ticks is sampled at the 24th.200 baud ± 4. Each byte is framed between a high start bit and a low stop bit.200 baud by the MCU is illustrated by the circuit of Figure 6-3a. . as shown in Figure 6-2.72 Chapter 6 PC Monitor Use (Measure. A maximum deviation of the MCU baud rate from the nominal baud rate of 19. the PC’s UART registers a framing error. The PC knows that each byte of data is framed between low idle bits or between the low trailing stop bit of a frame and the high leading start bit of the following frame. 6. just the opposite of what would be expected from a UART whose output is inverted externally. relative to the nominal 19.200 baud follows from this of 7 Baud rate = 19. universal asynchronous receiver transmitter. a transmission rate in which the duration of each bit is 1 1 bit time = ______ s ≈ 50 µs 19. signaling the reception of possibly erroneous data. As pointed out in conjunction with Figure 3-3. Because of its sampling of the received waveform.2 WAVEFORMS AND BAUD RATE ACCURACY The UART. The PC’s crystal baud rate oscillator with a frequency accuracy of better than 100 parts per million will introduce an error.200 The protocol employed for the asynchronous serial data transmission from the MCU to the PC is illustrated in Figure 6-1 for a 3-byte transfer.c) times in units of microseconds will vary from board to board because of variations in the 2% accurate internal clock frequency. Because both clock and data are combined in the single TX output from the MCU. 136th ticks to read the 8 data bits.200 baud rate. .200 baud by a sufficient amount. is a module in the MCU that is used by the QwikBug utility to send and receive information between the PC and the MCU. the PC’s UART can miss the time of the rising edge of the start bit by up to one tick. of no more than 0. the PC employs a baud rate of 19. If the input is high at the 152nd tick because of the MCU’s baud rate clock frequency being off from the nominal 19. . The effect of a slow MCU baud rate clock is to stretch the waveform of Figure 6-2 relative to the PC’s tick clock.200 baud ± ____ × 100% = 19. For this transmission. the TX signal idles low to drive the RS-232 cable going to the PC. the PC must synchronize on the serial data stream in order to read the data bits reliably. a framing error will occur. The resulting relationship . Thus. If this stretching is as much as 160 – 152 – 1 = 7 ticks relative to the 152 ticks when the stop bit is read.01%. .60% 152 The generation of a baud rate approximating 19. This low-to-high transition triggers a counter in the PC’s UART that divides each bit time into 16 “ticks”. The PC’s UART actually reads each bit in the middle of each bit time as measured by counting ticks. It finally samples the input at the 152nd tick and expects to read the low stop bit. that is.200 baud. the MCU is able to implement the signal level inversion for its output to the PC that is normally implemented with an external chip. producing a 10-bit frame having a duration of about half a millisecond. Section 6. FIGURE 6-1 Transmission of a three-byte string 73 .2 One frame One frame One frame Idle bits One bit time 1 = sec 19200 ≈ 50 µs Idle bits • • • • • • TX 8 data bits 8 data bits Waveforms and Baud Rate Accuracy 8 data bits Start bits Stop bits Idle-to-start transition Stop-to-start transition Receiver synchronizes on Idle-to-start transition and resynchronizes on each subsequent stop-to-start transition. c) .74 One frame start bit bit 0 bit 7 stop bit start bit • • • TX 16 24 32 128 136 01 8 144 152 160 one tick Chapter 6 FIGURE 6-2 Division of one frame into 160 ticks PC Monitor Use (Measure. 77°F) over the full supply voltage range of 2.e. BRGH.16% 0 0 1 1 25 12 25 12 (c) BRGH and SPBRG settings for 19200 baud FIGURE 6-3 Baud rate generation by the MCU .16% −0. Using the MCU’s INTOSC internal oscillator.16% baud-rate error of Figure 6-3c are comfortably less than the ±4.16% −0... .Section 6...0 V to 5. SPBRG N Equal TXSTA BRGH Comparator Baud rate clock .60% accuracy required by the PC’s UART. N.. and SPBRG is shown in Figure 6-3b. ÷4 for BRGH = 1 ÷16 for BRGH = 0 FOSC Synchronous reset (a) MCU’S UART baud-rate generator circuit BRGH = 1 FOSC = 4 (SPBRG + 1) Baud rate FOSC = 16 (SPBRG + 1) Baud rate (b) Baud rate derivation from FOSC BRGH = 0 FOSC 8 MHz 4 MHz 2 MHz 1 MHz BRGH SPBRG Baud rate error −0. . The frequency error of the INTOSC oscillator is specified to be less than ±2% at 25°C (i..16% −0.200-baud rate of the PC can be approximated by any of the four settings of Figure 6-3c. depending upon the Fosc value selected. 0. the 19..2 Waveforms and Baud Rate Accuracy 75 between FOSC. This error plus the 0. 1. baud rate. N.. 2. 0..5 V. .3 UART’S TX CIRCUITRY AND USE The circuitry of Figure 6-4 implements the TX (transmit) portion of the UART module in the MCU. An alternative flag (TXIF) could have been used that signals when TXREG is ready for a new byte. it is necessary to pause while TRMT = 0 so that no intended byte being sent to the PC is aborted when FOSC is stopped. However. 6. This flag provides the benefit of allowing 2 bytes to be written to the UART before the first half-millisecond pause occurs. It consists of two registers plus a TRMT (transmit) flag that can be used for flow control. The baud rate settings of Figure 6-3c for FOSC = 4 MHz are reflected in the register contents of Figure 6-5.4 UART INITIALIZATION The UART module in the MCU must be initialized before it can be used. before the chip is put to sleep.76 Chapter 6 PC Monitor Use (Measure.c) TXREG Automatically transfer TXREG to TSR when TSR has been emptied Stop bit = 0 0 Start bit = 1 Data is transmitted LSb first TX (RC6) pin TSR (transmit shift register) Automatically set TRMT flag when TSR is empty TXSTA x x x x x x TRMT flag x TRMT remains cleared while byte is being transmitted by TSR FIGURE 6-4 TX circuitry 6. before a new byte is written to TXREG. a pause until the present byte in the UART has been completely transferred can be implemented by pausing while TRMT = 0. When a string of bytes is sent to the display. TXSTA = 0b00100000. For a different oscillator frequency. } // // // // Enable UART Enable TX Set baud rate Invert TX output (b) Initialization FIGURE 6-5 UART registers and initialization for TX output .4 UART Initialization 77 TRISC x 0 x x x x x x TX/RC6 configured as an output BAUDCON 0 1 1 1 1 0 0 0 TXCKP RCSTA 1 x x x x x x x SPEN TXSTA 0 0 1 0 0 0 0 TRMT 1: 0: 1: 0: Flag indicates TSR is empty Flag indicates TSR is transmitting Transmit function is enabled Transmit function is disabled 1: 0: Serial port is enabled Serial port is disabled 1: 0: TX data is inverted TX data is not inverted BRGH = 0 for FOSC = 4 MHz (see Figure 6-3c) TXEN SPBRG PIR1 x x x 12 x x x x Baud-rate generator for 19200 baud with FOSC = 4 MHz (see Figure 6-3c) TXIF TXREG 1: 0: TXREG is ready to receive a byte TXREG is full. It assumes * Fosc = 4 MHz. waiting upon TSR Transmit register (a) Registers /******************************* * InitTX * * This function initializes the UART for its TX output function. use Figure 6-3c to * change BRGH and SPBRG appropriately. BAUDCON = 0b00111000.Section 6. ******************************* */ void InitTX() { RCSTA = 0b10010000. SPBRG = 12. #define TXascii(in) TXREG = in. TXascii('A'). each of these variables began with the ASCII code for zero. The macro does two things: • It sends its ASCII-coded parameter.TRMT) (a) TXascii macro definition TXascii(HUNDREDS). The macro definition and examples of its use are shown in Figure 6-6. TXascii('\n').6 NUMBER-TO-ASCII CONVERSION In the last chapter. while(!TXSTAbits. the baud rate settings must be reinitialized to the settings shown in Figure 6-5 in order to have the PC accept the MCU output correctly at 19. 6. TXascii(0x0D). TXascii(0x0A). TXascii('\r'). TXascii(0x41). QwikBug handles these shared registers with care. saving user contents on entering QwikBug at a breakpoint or after a single step. // Display ASCII-coded content of HUNDREDS // Display the letter A // Carriage return // Line feed // Display the letter A // Carriage return // Line feed (b) Useful invocations FIGURE 6-6 TXascii macro definition and several useful invocations . to TXREG for transmission to the PC. 6.5 TXASCII MACRO The fundamental building block for sending an ASCII-coded character to the PC is a TXascii macro. and restoring the user contents on exiting back to the user program.78 Chapter 6 PC Monitor Use (Measure. these values were updated by incrementing to the next ASCII code or by resetting to '0'.200 baud. run it. • It waits for the completion of the transfer by testing the TRMT bit of Figure 6-5a and pausing until it becomes set. Thereafter. and aid in debugging it.c) Even though QwikBug has already initialized the UART in order to download a user program. ASCII-coded characters were formed in the Time function (and similarly in the Pushbutton function) by starting with ONES = '0' and TENS = '0' That is. For a user program operating with FOSC = 4 MHz. whether a constant or a char variable. QwikBug has done so with FOSC = 8 MHz. ready for display. The third line forms TENS by repeatedly subtracting 10 from what remains in NUMBER.6 Number-to-ASCII Conversion 79 More generally. In Figure 6-8. } // Form HUNDREDS FIGURE 6-7 Conversion of the char variable NUMBER ranging from 0 to 255 . unsigned char HUNDREDS. to three ASCII-coded digits * by performing successive subtractions. the int version of NUMBER by adding the extra lines of code needed to generate one more digit. For each of these algorithms. two versions will be developed. least-significant-digit first. most-significant-digit first.ONES. ******************************* */ void ASCII() { ONES = TENS = HUNDREDS ='0'.535 can be held in BIGNUM.TENS. This value is added to the ASCII-coded zero initialized into ONES. Takes up to 98 cycles. NUMBER -= 100. with the functions shown in Figure 6-7. restricting the conversion to any four-digit number up to 9. ASCII4 and ASCII4D operate on BIGNUM. The first breaks out the digits. (a) Definitions // Eight-bit number to be converted // ASCII coding of digits /******************************* * ASCII * * This function converts the unsigned char parameter passed to it * in NUMBER. two algorithms will be considered. Global variables: unsigned char NUMBER. ASCII and ASCIID convert NUMBER.Section 6. The second line forms HUNDREDS by repeatedly subtracting 100 from NUMBER until NUMBER is less than 100. In this section. Function prototypes: void ASCII(void). The first line of ASCII initializes the three output variables to ‘0’. The fourth line is reached with NUMBER having a value ranging between zero and nine. by successive divisions. a number will be obtained as a result of a measurement and will need to be converted to ASCII-coded char variables: ONES TENS HUNDREDS THOUSANDS etc. The second breaks out the digits. Although numbers up to 65. * Simplified by Chad Kersey. by successive subtractions.999 will serve the needs that arise in this book. void ASCIID(void). //Initialize to ASCII zeroes while (NUMBER >= 100) { HUNDREDS++. ranging from 0 to 255. a value ranging from 0 to 255. c) while (NUMBER >= 10) { TENS++. Using Start. // Form TENS HUNDREDS = '0' + (NUMBER / 10).7 MEASURE. } // Form TENS // Form ONES (b) ASCII for conversion by successive subtractions /******************************* * ASCIID * * This function converts the unsigned char parameter passed to it * in NUMBER. They are reasonable values for estimating worst-case cycle counts for the successive-division algorithms. and Send functions that will be developed in Chapter 13.c template program that will evaluate the number of cycles needed to execute each function. For these reasons.c template. The numbers used for the conversions NUMBER = 199 and BIGNUM = 9. The successive-subtraction algorithms require. this section introduces in Figure 6-9 a Measure. and sends the resulting number of cycles to the QwikBug Console. Stop. Determining the actual worst-case cycle count for each of the two successive-division algorithms is left as end-of-chapter problems. the successive-subtraction algorithms produce cycle counts that are proportional to the sum of the digits in the result. . ranging from 0 to 255. NUMBER -= 10. Furthermore. Measure. ******************************* */ void ASCIID() { ONES = '0' + (NUMBER % 10).c starts a counter of CPU clock cycles (Timer0) immediately before the call of each ASCII conversion function. stops the counter immediately after the conversion. } ONES += NUMBER. TENS = '0' + (NUMBER % 10)..80 Chapter 6 PC Monitor Use (Measure.e. // Form HUNDREDS } (c) ASCIID for conversion by successive divisions FIGURE 6-7 (continued) 6. // Form ONES NUMBER = NUMBER / 10.c.6 ready for use. to three ASCII-coded digits * by performing successive divisions. A CYCLE COUNTING PROGRAM With the four functions of the last section and the TXascii macro of Section 6. and can thus produce a significantly reduced cycle count in a specific case. Takes up to 357 cycles. ASCII and ASCII4 are used throughout the rest of the book whenever a conversion is needed.999 represent worst-case values (i. values that produce the most cycles) for ASCII and ASCII4. The resulting numbers of cycle counts are listed in the header of the Measure. the successive-subtraction algorithms. in the worst case. about a quarter of the number of cycles of the successive-division algorithms. // Ranges from 0 to 9999 unsigned char THOUSANDS. } // Form ONES += BIGNUM. } // Form while (BIGNUM >= 10) { TENS++. ******************************* */ void ASCII4D() { ONES = '0' + (BIGNUM % 10). void ASCII4D(void). BIGNUM -= 1000. to four ASCII-coded digits * by performing successive divisions. (a) Definitions /******************************* * ASCII4 * * This function converts the unsigned int parameter passed to it * in BIGNUM. TENS = '0' + (BIGNUM % 10). //Initialize to ASCII while (BIGNUM >= 1000) { THOUSANDS++.Section 6.HUNDREDS.c. // Form HUNDREDS THOUSANDS = '0' + (BIGNUM / 10).7 Measure. // Form ONES BIGNUM = BIGNUM / 10. * Simplified by Chad Kersey. BIGNUM -= 100. // Form TENS BIGNUM = BIGNUM /10. } // Form while (BIGNUM >= 100) { HUNDREDS++.ONES. Takes up to 1498 cycles. // Form } (b) ASCII4 for conversion by successive subtractions /******************************* * ASCII4D * * This function converts the unsigned int parameter passed to it * in BIGNUM. to four ASCII-coded digits * by performing successive subtractions. zeroes THOUSANDS HUNDREDS TENS ONES FIGURE 6-8 Conversion of the int variable BIGNUM ranging from 0 to 9999 . ranging from 0 to 9999. // ASCII coding of digits Function prototypes: void ASCII4(void). HUNDREDS = '0' + (BIGNUM % 10). // Form THOUSANDS } (c) ASCII4D for conversion by successive divisions cycles.TENS. A Cycle Counting Program 81 Global variables: unsigned int BIGNUM. Takes up to 353 ******************************* */ void ASCII4() { ONES = TENS = HUNDREDS = THOUSANDS ='0'. ranging from 0 to 9999. BIGNUM -= 10. 1V.82 Chapter 6 PC Monitor Use (Measure. the result is displayed on the LCD. RA6=Fosc/4. * Then a number between 0 and 255 is converted to ASCII-coded digits two ways: * ASCII forms each digit by successive subtractions (up to 98 cycles). * For each one.c . * ASCII4D forms each digit via two divisions (up to 1498 cycles). The Send function sends the time to the PC monitor. * ASCIID forms each digit via two divisions (up to 357 cycles).c ************* * * A number between 0 and 9999 is converted to ASCII-coded digits two ways: * ASCII4 forms each digit by successive subtractions (up to 353 cycles). * * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz. nominal Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2.h> // Define PIC18LF4321 registers and bits /******************************* * // #pragma config CCP2MX = RB3 // #pragma config BOR = SOFT // #pragma config BORV = 3 // #pragma config LPT1OSC = OFF // Use internal osc. * The execution time (cycles)is displayed on the PC * Execution stops with a sleep command. nominal Deselect low-power Timer1 oscillator FIGURE 6-9 Measure. * * Start and Stop functions are added to measure the execution time of the * code between them. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period.c) /******* Measure. * ******* Program hierarchy ***** * * main * Initial * InitTX * Start * Stop * Send * TXascii * ASCII4 * ASCII4D * ASCII * ASCIID * Display * ******************************* */ #include <p18f4321. void ASCII4(void). // ASCII coding of digits unsigned char i.TRMT) /////// Main program ////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). Nop(). // Convert BIGNUM Takes 353 cycles FIGURE 6-9 (continued) . LCDSTRING[0] = THOUSANDS. } #define TXascii(in) TXREG = in. void Display(void). void ASCII(void). // Sixteen-bit number to be converted unsigned char THOUSANDS. // Initialize everything InitTX().ONES. // Nine-character display string /******************************* * Function prototypes ******************************* */ void Initial(void). Stop(). // Result of Timer0 counting cycles char LCDSTRING[] = " ". /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x.c. LCDSTRING[1] = HUNDREDS. LCDSTRING[2] = TENS. // and the UART as well BIGNUM = 9999. void ASCII4D(void). A Cycle Counting Program 83 /******************************* * Global variables ******************************* */ unsigned int DELAY. void InitTX(void). // Eight-bit number to be converted unsigned int BIGNUM.HUNDREDS. Start(). // Sixteen-bit counter for obtaining a delay unsigned char NUMBER. while(!TXSTAbits. void Start(void). void ASCIID(void). void Send(void).Section 6. while(--DELAY){ Nop(). ASCII4().TENS. void Stop(void). // Index into strings unsigned int CYCLES.7 Measure. Sleep(). // Send cycle count to PC for display // Use decimal point as separator // Convert BIGNUM THOUSANDS. ASCII().c) LCDSTRING[3] = ONES. TENS. HUNDREDS.84 Chapter 6 PC Monitor Use (Measure. ONES. // Convert NUMBER ' '. BIGNUM = 9999. Send(). Takes 357 cycles // Send this cycle count to PC for display // Verify correct conversions on LCD // Sleep forever /******************************* * Initial * * This function performs all initializations of variables and registers. LCDSTRING[4] = '. HUNDREDS. Delay(50000).'. Stop(). Start(). Display(). ASCIID(). NUMBER = 199. Stop(). HUNDREDS. LCDSTRING[0] = LCDSTRING[1] = LCDSTRING[2] = LCDSTRING[3] = Send(). Start(). Delay(50000). Takes 1498 cycles // Send this cycle count to PC for display // Verify correct conversions on LCD Delay(50000). TENS. ONES.'. TENS. Delay(50000) // Two-second pause NUMBER = 199. ASCII4D(). ONES. Takes 98 cycles // Send cycle count to PC for display // Use decimal point as separator LCDSTRING[4] = '. Start(). LCDSTRING[5] = LCDSTRING[6] = LCDSTRING[7] = LCDSTRING[8] = Send(). LCDSTRING[5] = LCDSTRING[6] = LCDSTRING[7] = LCDSTRING[8] = Send(). } // Convert NUMBER ' '. Display(). ******************************* */ FIGURE 6-9 (continued) . Stop(). TRISC = 0b10000000. Delay(50000). SSPCON1 = 0b00110000. TRISA = 0b00001111.RA3 pins analog. Set up Timer0 to count CPU clock cycles Clear Timer0 Start counting FIGURE 6-9 (continued) . TRISE = 0b00000010. TRISD = 0b10000000. TRISB = 0b01000100.7 Measure.RA1. } // Use Fosc = 4 MHz (Fcpu = 1 MHz) // Set up SPI for output to LCD // // // // // // // // RA0. PORTC = 0. others digital Set I/O for PORTA Set I/O for PORTB Set I/O for PORTC Set I/O for PORTD Set I/O for PORTE Set initial state for all outputs low // except RD5 that drives LCD interrupt // Send a blank to initialize state of SPI // Pause for half a second // Now disable brown-out reset /******************************* * InitTX * * This function initializes the UART for its TX output function. // Set baud rate BAUDCON = 0b00111000. // Enable UART TXSTA = 0b00100000. SSPSTAT = 0b00000000. PORTD = 0b00100000. // } then starts it counting. RCONbits. ADCON1 = 0b00001011.Section 6. // Enable TX SPBRG = 12. SSPBUF = ' '. // TMR0H = 0. A Cycle Counting Program 85 void Initial() { OSCCON = 0b01100010. For a different oscillator frequency.RA2.c.SBOREN = 0. PORTB = 0. PORTA = 0. PORTE = 0. use Figure 6-3c to * change BRGH and SPBRG appropriately. It assumes * Fosc = 4 MHz. ******************************* */ void InitTX() { RCSTA = 0b10010000. // TMR0L = 0.TMR0ON = 1. T0CONbits. // Invert TX output } /******************************* * Start * * This function clears Timer0 and ******************************* */ void Start() { T0CON = 0b00001000. // Send four-digit number TXascii(HUNDREDS).SSPIF). i <= 8. } /******************************* * Display() * * This function sends LCDSTRING to the LCD. CYCLES -= 3. TXascii(ONES). // Convert TXascii('\r'). TXascii(TENS). ******************************* */ void Display() { PORTDbits. i++) { PIR1bits.RD5 = 0. and reads the result into CYCLES. // Load ASCII4’s input parameter ASCII4().c) /******************************* * Stop * * This function stops counting Timer0. // Stop counting CYCLES = TMR0L. // Send line feed TXascii(THOUSANDS). ready for next string } FIGURE 6-9 (continued) . ******************************* */ void Send() { BIGNUM = CYCLES. // Send byte while (!PIR1bits. // Clear SPI flag SSPBUF = LCDSTRING[i]. ******************************* */ void Stop() { T0CONbits. // Return RB5 high. // Wake up LCD display for (i = 0.TMR0ON = 0.86 Chapter 6 PC Monitor Use (Measure. // Send carriage return TXascii('\n').SSPIF = 0. // Remove 3 counts so back-to-back Start-Stop } // functions produce CYCLES = 0 /******************************* * Send * * This function converts CYCLES to four ASCII-coded digits and sends * the result to the PC for display. // Wait for transmission to complete } PORTDbits.RD5 = 1. // Form CYCLES from TMR0H:TMR0L CYCLES += (TMR0H * 256). to three ASCII-coded digits * by performing successive subtractions. // Form TENS HUNDREDS = '0' + (NUMBER / 10). that ranges between 0 and 255. ******************************* */ void ASCII() { ONES = TENS = HUNDREDS ='0'. // Form ONES } /******************************* * ASCIID * * This function converts the unsigned char parameter passed to it * in NUMBER. ******************************* */ void ASCIID() { ONES = '0' + (NUMBER % 10). that ranges between 0 and 9999. BIGNUM -= 10. Takes a maximum of 98 cycles. Takes up to 357 cycles. BIGNUM -= 1000. } // Form TENS ONES += NUMBER.Section 6. // Form HUNDREDS } /******************************* * ASCII4 * * This function converts the unsigned int parameter passed to it * in BIGNUM. // Form ONES } FIGURE 6-9 (continued) . * Simplified by Chad Kersey. NUMBER -= 10. } // Form HUNDREDS while (NUMBER >= 10) { TENS++. // Form ONES NUMBER = NUMBER / 10. //Initialize to ASCII zeroes while (BIGNUM >= 1000) { THOUSANDS++. A Cycle Counting Program 87 /******************************* * ASCII * * This function converts the unsigned char parameter passed to it * in NUMBER. } // Form TENS ONES += BIGNUM. * Simplified by Chad Kersey. BIGNUM -= 100. Takes a maximum of 353 cycles. } // Form THOUSANDS while (BIGNUM >= 100) { HUNDREDS++.c. NUMBER -= 100. TENS = '0' + (NUMBER % 10). //Initialize to ASCII zeroes while (NUMBER >= 100) { HUNDREDS++. to four ASCII-coded digits * by performing successive subtractions. to three ASCII-coded digits * by performing successive divisions. } // Form HUNDREDS while (BIGNUM >= 10) { TENS++. that ranges between 0 and 255.7 Measure. ******************************* */ void ASCII4() { ONES = TENS = HUNDREDS = THOUSANDS ='0'. // Form TENS BIGNUM = BIGNUM /10. HUNDREDS = '0' + (BIGNUM % 10). Then form AVG = (int)(SUM >> 8) to divide SUM by the 256 trials to get the average number of cycles. send MIN and MAX to the QwikBug Console for display. 6-5 Display execution time Display function. 256 times with each possible value of NUMBER. Each run is to (possibly) update two int values MIN and MAX and to update a short long (i. Send AVG out for display.e. // Form THOUSANDS } FIGURE 6-9 (continued) PROBLEMS 6-1 ASCIID worst case Modify the Measure. TENS = '0' + (BIGNUM % 10).c) /******************************* * ASCII4D * * This function converts the unsigned int parameter passed to it * in BIGNUM. 24-bit) value SUM. to four ASCII-coded digits * by performing successive divisions.999 cases of the four-digit successivesubtraction algorithm. 6-4 ASCII4 worst case Repeat for the 0–9. Measure the number of cycles taken to execute the . that ranges between 0 and 9999.c. 6-3 ASCII4D worst case Repeat for the 0–9. This program is to run the successive-division algorithm. // Form HUNDREDS THOUSANDS = '0' + (BIGNUM / 10). ******************************* */ void ASCII4D() { ONES = '0' + (BIGNUM % 10).c template to form a MeasureASCIID.88 Chapter 6 PC Monitor Use (Measure.. Takes up to 1498 cycles.999 cases of the four-digit successive-division algorithm. 6-2 ASCII worst case Repeat the last problem for the ASCII successivesubtraction algorithm. At the conclusion. ASCIID. // Form ONES BIGNUM = BIGNUM / 10. 2 LOW. an alternative approach for awakening the chip is employed.Chapter 7 REORGANIZATION OF TIMING VIA INTERRUPTS (T3.c) 7. The MCU’s low-power Timer1 oscillator runs continuously and is able to clock its Timer1 counter regardless of whether the remainder of the MCU is asleep or awake. In this chapter. Then the low-power watchdog timer has awakened the chip every 16 ms to repeat the mainline tasks. It also supports a score of interrupt sources. also clocked by the Timer1 oscillator. The MCU also has a Timer3 counter. if a low-priority interrupt 89 .AND HIGH-PRIORITY INTERRUPTS The PIC18LF4321 supports two levels of interrupts. Furthermore. Tasks requiring faster periodic “ticks” can easily do so by using Timer3 to produce high-priority interrupts. 7. The Timer1 counter is used to control the loop time by awakening the chip periodically with an interrupt. any one of which can be used to suspend the CPU’s execution of the main program and divert the CPU to either a high-priority interrupt service routine (HPISR) or a low-priority interrupt service routine (LPISR).1 OVERVIEW The code of the template programs to this point has put the MCU to sleep after carrying out the main loop tasks. Now the watchdog timer remains disabled. 535 and then rolls over.5 µA.c) has interrupted the main program and the CPU has begun executing the LPISR when a high-priority interrupt source requests service.c plus the initialization of Timer1 as a low-priority interrupt source and Timer3 as a high-priority interrupt source. is introduced that still carries out the tasks of the T2. back to 0 to Power up to main function Initial Main loop tasks Sleep LPISRFLAG = 1 ? Yes No Timer1 wakeup with low-priority interrupt Timer3 wakeup with high-priority interrupt Reload Timer1 Set LPISRFLAG Reload Timer3 Do “tick-time” tasks FIGURE 7-1 Reorganization to use Timer1 for controlling loop time and Timer3 for controlling faster recurring tasks Return from interrupt Return from interrupt .768-Hz watch crystal and the Timer1 and Timer3 counters continue to run.c. but with the code reorganized as shown in Figure 7-1. T3. Then the CPU puts itself to sleep.90 Chapter 7 Reorganization of Timing Via Interrupts (T3. The current draw of the MCU drops to 6. A new template program. the CPU automatically suspends the LPISR and executes the HPISR before returning to where it left off in the LPISR. The new main function calls the Initial function where it carries out all of the initialization tasks of T2. Timer1 is a 16-bit timer that counts from 0 up to 65.c template. Timer1 is used to produce a 10-ms loop time for all of the main loop tasks. Only the Timer1 oscillator with its external 32. . draws about 6. the task is to produce a 1-µs-positive pulse every 4 ms on an output pin. 0x0018. this oscillator can be configured to operate reliably with VDD = 3 V using the configuration selection LPT1OSC = OFF This choice uses a somewhat higher power driver in its oscillator circuit than is used by the circuit selected with the configuration choice LPT1OSC = ON The “OFF” choice also removes a 3-V regulator from the circuit.7. Its external circuitry consists of the 32. The difference lies in its being called by a hardware-initiated event (e.e.Section 7. The “OFF” choice is needed for reliable operation with the Qwik&Low board’s 3-V VDD supply. The sequencing of the two interrupt service routines is illustrated in Figure 7-2. providing the timing accuracy associated with a 50 parts per million (i. the setting of an interrupt flag by a timer). The rollover produces a low-priority interrupt. the CPU sets aside its present state and loads its program counter with the low-priority interrupt vector address. perhaps being briefly extended by a concurrent HPISR. The Qwik&Low board can use the Timer1 oscillator for loop-time control.4 TIMER1 OSCILLATOR The Timer1 oscillator is a module that can function independently of the Timer1 counter. To the writer of user code.3 INTERRUPTS AND THE C18 COMPILER When a low-priority interrupt occurs.. Note how the LPISR is executed every 10 ms. As mentioned in Section 3.g. The C18 compiler generates the code to begin execution of the LoPriISR shown in Figure 7-3.768counts/s 100 Timer3 is set up to produce faster “tick time” interrupts in the same manner. Timer1 is reloaded with a number that cuts out all but 328 counts so that the next rollover will occur in 1 1 328counts × ______________ ≈ ____ s = 10ms 32. ±0. each interrupt service routine is written with the same form as any other function. use of the . For now. 7.5 µA. together with its clocking of both Timer1 and Timer3 while the CPU sleeps. In contrast. Within the LPISR.768-Hz crystal and two 15-pF capacitors of Figure 3-3.4 Timer1 Oscillator 91 continue counting. 7. The crystal oscillator runs even as the rest of the chip sleeps. The oscillator. The pulse can be monitored with a scope or used to step the stepper motor of Chapter Eight at a rate of 250 steps/s.005%) crystal. The code to set aside CPU registers upon entry to an interrupt service routine and to later restore CPU registers back to their state at the time of the interrupt is handled transparently by the compiler. intended for use with a higher VDD value. 92 CPU asleep Power up • • • Main function Initial function Low-priority ISR Chapter 7 High-priority ISR 4 ms 10 ms 4 ms 4 ms 4 ms 10 ms 4 ms 4 ms Reorganization of Timing Via Interrupts (T3.c) FIGURE 7-2 Sequencing of the two interrupt service routines . 4 Timer1 Oscillator 93 /******************************* * (a) Handling of vectoring to HiPriISR and LoPriISR /******************************* * HiPriISR ******************************* */ void HiPriISR() { <Tasks to be done> } /******************************* * LoPriISR ******************************* */ void LoPriISR() { <Tasks to be done> } (b) Interrupt service routines themselves FIGURE 7-3 C18 compiler’s handling of interrupt vectoring .Section 7. Timer1 will not be incremented for 30. it automatically reenables low-priority interrupts by setting the GIEL bit and returns to the main loop and to the sleep instruction of Figure 7-1.768-Hz Timer1 oscillator. with the initialization shown. However. • Does not support fast counting as a side benefit.000030518 = 0.e. 4-ms minimum or some power of two greater than this). • Does so with the much larger error specification of ±14%.010009765 + 0. a high-priority interrupt can be accepted and acted on while the LPISR is being executed. The CPU awakens immediately and begins executing machine instructions at a rate of 1 (or.35 in parts cost (the cost of the crystal and its two capacitors) and draws only 2. which had been asleep.94 Chapter 7 Reorganization of Timing Via Interrupts (T3.4% Given the normal circumstance of the HPISR infrequently overlapping with the LPISR as in Figure 7-1. GIEL. The loop time will be 328 ______ = 0. awakens and the low-priority interrupt service routine is executed. the accuracy of this loop-time mechanism should be close to 0. .1% 32.2 µA. it is unlikely to cause even one count of Timer1 to be lost. • The TMR1IF flag in the PIR1 register must be cleared. Timer1 will be reinitialized before the counter is clocked again and any counts are missed. Even one lost count produces a loop time of 0. Two Timer1 housekeeping tasks must be carried out: • TMR1H:TMR1L must be reinitialized to eliminate all but 328 counts until the next interrupt. using the watchdog timer • Provides limited alternatives for a loop time (i. but not the GIEH bit. Unless a high-priority interrupt intervenes.1%. With its clock input from the 32. the TMR1IF flag in the PIR1 register is set and. 2) µs per instruction. The chip.010009765 s = 10 ms + 0. Because the low-priority interrupt automatically clears the low-priority global interrupt enable bit. 7..c) watchdog timer for loop-time control saves $1. When the CPU completes the execution of the LPISR.5 µs after the interrupt occurs.5 TIMER1 COUNTER The circuit of Figure 7-4 illustrates the use of the Timer1 counter in conjunction with the Timer1 oscillator.010040283 = 10 ms + 0. at most.768 If an intervening high-priority interrupt does occur in the few microseconds after Timer1 rolls over and interrupts the LPISR. a low-priority interrupt occurs. Each time the 16-bit TMR1H:TMR1L counter overflows. 5 µs 32768 Hz crystal 15 pF set PIR1 x x x x x x x TMR1IF TMR1H Overflow 8-bit counter Generate a low-priority interrupt GIEH GIEL TMR1IE PIE1 x x x x x x x 1 INTCON 1 1 x x x x x x TMR1IP IPR1 x x x x x x x 0 FIGURE 7-4 Timer1 use for controlling loop time 95 .5 RCON 1 x x x x x x x T1CON 0 1 0 0 1 1 1 1 TMR1ON 1: Enable Timer1 counter 0: Disable Timer1 counter Timer1 Counter IPEN = 1 : Enable two interrupt priority levels Timer1 oscillator T1OSI and T1OSO pins TMR1L 8-bit counter Frequency = 32768 Hz Period = 30.Section 7. c program of Figure 7-6 is used to exit from the while loop. synchronization causes the counter to stop being clocked when the chip is put to sleep.c TEMPLATE PROGRAM The T3. The initialization of the Timer1 oscillator. The addition of the Interrupt vectors section.96 Chapter 7 Reorganization of Timing Via Interrupts (T3.6 TIMER3 COUNTER The Timer3 counter is identical in performance to Timer1.c template program is listed in Figure 7-6. . and Timer3 to run and to produce interrupts.c) 7. It differs from T2. TMR3IP. • The addition of a LoopTime function that handles the wakeup from the Sleep instruction in one way for Timer1 interrupts and in another way for Timer3 interrupts.c in the following ways: • • • • The addition of LoopTime. 7.7 THE T3. To have it generate a high-priority interrupt rather than Timer1’s lowpriority interrupt. Upon entry to the LoopTime function. Timer1. a) Describe the program flow when the chip is asleep and a Timer3 interrupt occurs. • The replacement of the Sleep macro in the main loop with the call of a LoopTime function. Using the option of stopping the counter. Timer1’s LPISR will set the LPISRFLAG bit. b) Describe the program flow when the chip is asleep and a Timer1 interrupt occurs. It (as well as Timer1) also has the option of synchronizing the edges of the slow Timer1 oscillator to the edges of the faster FOSC/4 CPU clock. even though the Timer1 oscillator is still running. It will remain asleep until either Timer1 or Timer3 causes an interrupt. PROBLEMS 7-1 LoopTime function The testing of the LPISRFLAG in the LoopTime function located at the end of the T3. As part of its execution. and then starting it again is done instead. Its registers are illustrated in Figure 7-5. the CPU immediately goes to sleep. However. HiPriISR and LoPriISR function prototypes. Timer3 (as well as Timer1) has a TMR3ON bit in its T3CON control register that can be used to stop the counter for its reinitialization. The creation of the LoPriISR and HiPriISR functions. in the IPR2 register. Switching synchronization on and off also does not provide satisfactory operation because it results in lost counts. reinitializing it. it is only necessary to set its interrupt priority bit. The latter option is helpful if the counter is to be read or written to as it is being clocked without occasionally obtaining a garbled result. c Template Program IPEN = 1 : Enable two interrupt priority levels Timer1 oscillator T1OSI and T1OSO pins TMR3L 8-bit counter Frequency = 32768 Hz Period = 30.Section 7.7 RCON 1 x x x x x x x T3CON 0 0 0 0 0 1 1 1 TMR3ON 1: Enable Timer3 counter 0: Disable Timer3 counter The T3.5 µs 32768 Hz crystal 15 pF set PIR2 x x x x x x x TMR3IF TMR3H Overflow 8-bit counter Generate a high-priority interrupt GIEH INTCON 1 x x x x x x x TMR3IP IPR2 x x x x x x 1 x TMR3IE PIE2 x x x x x x 1 x FIGURE 7-5 Timer3 use for generating fast ticks 97 . * Timer1 and Timer3 are both clocked by the Timer1 crystal oscillator. Timer1 awakens chip every 10 ms * within LoopTime function. * Post PRESS PB message on LCD until first pushbutton push.98 Chapter 7 Reorganization of Timing Via Interrupts (T3. .h> // Define PIC18LF4321 registers and bits // Used by the LoadLCDSTRING macro /******************************* * // Use internal osc. * LoopTime function puts chip to sleep. * Timer3 generates high-priority interrupts every 4 ms to step motor.c template. * Toggle RC2 output every 10 milliseconds for measuring looptime with scope. increment and display LCD's CHAR0:CHAR1 every second * and increment and display LCD's CHAR3:CHAR4 for each pushbutton press. RA6=Fosc/4. nominal Enable master clear pin PORTB<4:0> = digital FIGURE 7-6 T3. * Thereafter.c) /******* T3.c. * Same mainline code as for T2. * * Current draw = 31 uA (with LED and LCD switched off but whether * or not the stepper motor is connected. CPU adjusts Timer1 content for it to timeout * after another ten milliseconds.c ****************** * * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz.h> #include <string. * Blink LED on RD4 for 10 ms every four seconds. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period.) * ******* Program hierarchy ***** * * main * Initial * Display * BlinkAlive * Time * Pushbutton * UpdateLCD * Display * LoopTime * * LoPriISR * * HiPriISR * ******************************* */ #include <p18f4321. // char LPISRFLAG. void Pushbutton(void). // unsigned char TIMECNT. // unsigned char UNITS. // char LCDSTRING[] = "PRESS PB ". void BlinkAlive(void).7 The T3. nominal Deselect low-power Timer1 oscillator /******************************* * Global variables ******************************* */ char PBFLAG. // unsigned int STEPCNT. // char LCDFLAG.(const far rom char*)lit) /******************************* * Interrupt vectors ******************************* */ FIGURE 7-6 (continued) . void HiPriISR(void). void Display(void). Flag. // unsigned char PBTENS. Nop(). // unsigned char TENS. void UpdateLCD(void). set if pushbutton is now pressed Flag. set if pushbutton was pressed last loop Flag. // char NEWPB. set to send string to display Flag. void LoPriISR(void).0V. // char OLDPB.Section 7. void LoopTime(void). // unsigned int DELAY. set after first press of pushbutton Flag. // unsigned int ALIVECNT. unsigned char i. // /******************************* * Function prototypes ******************************* */ void Initial(void).number of counts between steps Scale-of-100 counter of loop times = 1 second For display of seconds For display of pushbutton count Index into strings Sixteen-bit counter for obtaining a delay LCD display string /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x.c Template Program 99 #pragma #pragma #pragma #pragma config config config config CCP2MX = RB3 BOR = SOFT BORV = 3 LPT1OSC = OFF // // // // Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. while(--DELAY){ Nop(). set when LP interrupt has been handled Scale-of-400 counter for blinking "Alive" LED 65536 . } #define LoadLCDSTRING(lit) strcpypgm2ram(LCDSTRING. void Time(void). unsigned char PBUNITS. * Add STEPCNT = 65536+1-131 = 65406 counts to Timer3. for measuring loop time Blink "Alive" LED Display seconds Display pushbutton count Update LCD Use Timer1 to wakeup and loop again /******************************* * HiPriISR * * This high-priority interrupt service routine creates a positive pulse on * RD1 every 4 ms.c) // /////// Main program ////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). Four milliseconds = 4000 * 0.RC2 ^= 1. * The +1 in the above equation results because the 0-to-1 transition when * Timer3 is reenabled increments Timer3. // } } Initialize everything Toggle pin. // BlinkAlive(). // UpdateLCD(). ******************************* */ void HiPriISR() { T3CONbits. // Add into lower byte FIGURE 7-6 (continued) .TMR3ON = 0.032768 = 131 Timer3 counts. // Time(). // LoopTime(). // Disable clock input to Timer3 TMR3L += STEPCNT.100 Chapter 7 Reorganization of Timing Via Interrupts (T3. * RB0 is toggled to measure step period. // while (1) { PORTCbits. // Pushbutton(). // except RD5 that drives LCD interrupt PORTE = 0. // RA0.7 The T3. // Upper byte of Timer1 will be 0xFE PIR1bits.RD1 = 1. // Send a blank to initialize state of SPI Delay(50000). others digital TRISA = 0b00001111.TMR3ON = 1. ******************************* */ void LoPriISR() { T1CONbits. // Set I/O for PORTE PORTA = 0. // Toggle pin to measure step period } /******************************* * LoPriISR * * This low-priority interrupt service routine updates Timer1 to interrupt * every 10 ms.RB0 ^= 1. Add 65536+1-328 = 65209 = 0xFEB9 to Timer1 = 0x0000 (or * at most a count or two higher if the HPISR intervenes). // Set I/O for PORTC TRISD = 0b10000000.Section 7. // Set a flag for LoopTime } /******************************* * Initial * * This function performs all initializations of variables and registers. // Use Fosc = 4 MHz (Fcpu = 1 MHz) SSPSTAT = 0b00000000. // Reenable Timer3 PIR2bits. // Set I/O for PORTB TRISC = 0b10000000. // Clear flag until pushbutton is first pressed FIGURE 7-6 (continued) . // Set I/O for PORTA TRISB = 0b01000100. SSPBUF = ' '.TMR1ON = 0. // Create 1 us wide positive pulse PORTDbits. // Pause for half a second RCONbits. Ten ms = 10000 * 0. // Clear interrupt flag LPISRFLAG = 1.032768 = 328 to cut out all * but 328 counts.SBOREN = 0. // Set I/O for PORTD TRISE = 0b00000010. // Now disable brown-out reset PBFLAG = 0. PORTC = 0. // Set initial state for all outputs low PORTB = 0. // Set up SPI for output to LCD SSPCON1 = 0b00110000.c Template Program 101 TMR3H = (TMR3H + STATUSbits. ******************************* */ void Initial() { OSCCON = 0b01100010. PORTD = 0b00100000.C) + (STEPCNT >> 8).RD1 = 0. // to step motor PORTBbits.TMR1IF = 0. // Clear interrupt flag PORTDbits.RA1.TMR1ON = 1.TMR3IF = 0. ADCON1 = 0b00001011. // and into upper byte T3CONbits.RA3 pins analog.RA2. // Resume Timer1 counter TMR1H = 0xFE. // Pause Timer1 counter TMR1L += 0xB9. // Cut out all but 328 counts of Timer1 T1CONbits. 102 Chapter 7 Reorganization of Timing Via Interrupts (T3.c) LCDFLAG = 0; LPISRFLAG = 0; TIMECNT = 0; TENS = '5'; UNITS = '9'; PBTENS = '0'; PBUNITS = '1'; ALIVECNT = 300; STEPCNT = 65406; OLDPB = 0; T1CON = 0b01001111; T3CON = 0b00000111; TMR1H = 0xFE; TMR1L = 0xB9; TMR3H = 0xFF; TMR3L = 0xAE; PIE1bits.TMR1IE = 1; PIE2bits.TMR3IE = 1; IPR1bits.TMR1IP = 0; IPR2bits.TMR3IP = 1; RCONbits.IPEN = 1; INTCONbits.GIEL = 1; INTCONbits.GIEH = 1; Display(); LoadLCDSTRING("00 01 } // // // // Flag to signal LCD update is initially off Flag to signal that LPISR has been executed Reset TIMECNT Initialize to 59 so first display = 00 // Initialize count of pushbutton presses // // // // // // // // // // // // // // // // // // Blink immediately Cut out all but 131 counts of Timer3 Initialize to unpressed pushbutton state Timer1 - loop time via low-pri interrupts Timer3 - step motor via hi-pri interrupts Set Timer1 to be 10 ms away from next roll over (65536 + 1 - 328 = 0xFEB9) Set Timer3 to be 4 ms away from next roll over (65536 + 1 - 131 = 0xFF7E) Enable local interrupt source Enable local interrupt source Use Timer1 for low-priority interrupts Use Timer3 for hi-priority interrupts Enable high/low priority interrupt feature Global low-priority interrupt enable Enable both high and low interrupts Display initial "PRESS PB" message Reinitialize LCDSTRING "); /******************************* * BlinkAlive * * This function briefly blinks the LED every four seconds. * With a looptime of about 10 ms, count 400 looptimes. ******************************* */ void BlinkAlive() { PORTDbits.RD4 = 0; // Turn off LED if (++ALIVECNT == 400) // Increment counter and return if not 400 { ALIVECNT = 0; // Reset ALIVECNT PORTDbits.RD4 = 1; // Turn on LED for one looptime } } /******************************* * Time * * After pushbutton is first pushed, display seconds. ******************************* */ FIGURE 7-6 (continued) Section 7.7 The T3.c Template Program 103 void Time() { if (PBFLAG) { if (++TIMECNT == 100) { TIMECNT = 0; if (++UNITS > '9') { UNITS = '0'; if (++TENS > '5') { TENS = '0'; } } LCDSTRING[0] = TENS; LCDSTRING[1] = UNITS; LCDFLAG = 1; } } } // After pushbutton is first pushed, // count TIMECNT to 1 second // Reset TIMECNT for next second // and increment time // Update display string // Set flag to display /******************************* * Pushbutton * * After pushbutton is first pressed, display pushbutton count. ******************************* */ void Pushbutton() { PORTEbits.RE0 = 1; // Power up the pushbutton Nop(); // Delay one microsecond before checking it NEWPB = !PORTDbits.RD7; // Set flag if pushbutton is pressed PORTEbits.RE0 = 0; // Power down the pushbutton if (!OLDPB && NEWPB) // Look for last time = 0, now = 1 { if (!PBFLAG) // Take action for very first PB press { PBFLAG = 1; ALIVECNT = 399; // Synchronize LED blinking to counting TIMECNT = 99; // Update display immediately } else // Take action for subsequent PB presses { if (++PBUNITS > '9') // and increment count of PB presses { PBUNITS = '0'; if (++PBTENS > '9') { PBTENS = '0'; } FIGURE 7-6 (continued) 104 Chapter 7 Reorganization of Timing Via Interrupts (T3.c) } } LCDSTRING[3] = PBTENS; LCDSTRING[4] = PBUNITS; LCDFLAG = 1; } OLDPB = NEWPB; } // Update display string for simulated LCD // Set flag to display // Save present pushbutton state /******************************* * UpdateLCD * * This function updates the 8-character LCD if Time * or Pushbutton has set LCDFLAG. ******************************* */ void UpdateLCD() { if(PBFLAG && LCDFLAG) { Display(); LCDFLAG = 0; } } /******************************* * Display * * This function sends LCDSTRING to the LCD. ******************************* */ void Display() { PORTDbits.RD5 = 0; // Wake up LCD display for (i = 0; i < 9; i++) { PIR1bits.SSPIF = 0; // Clear SPI flag SSPBUF = LCDSTRING[i]; // Send byte while (!PIR1bits.SSPIF); // Wait for transmission to complete } PORTDbits.RD5 = 1; // Return RB5 high, ready for next string } /******************************* * LoopTime * * This function puts the chip to sleep upon entry. * For a Timer3 interrupt, it executes the HPISR and then returns to sleep. * For a Timer1 interrupt, it executes the LPISR and then exits. ******************************* */ FIGURE 7-6 (continued) Section 7.7 The T3.c Template Program 105 void LoopTime() { while (!LPISRFLAG) { Sleep(); Nop(); } LPISRFLAG = 0; } // Sleep upon entry and upon exit from HPISR // Return only if LPISR has been executed, // which sets LPISRFLAG // Sleep upon next entry to LoopTime FIGURE 7-6 (continued) c) Describe the program flow when the chip is awakened by a Timer1 interrupt but a Timer3 interrupt intervenes just before the LPISR sets the LPISRFLAG. 7-2 Timer1 interrupt interval When the low-priority interrupt service routine cuts out all but 328 counts in its count sequence, it rolls over approximately every 10 ms. As pointed out in Section 7.5, the exact time is 10,009.765 µs. a) How many parts per million is this off from the nominal 10 ms? b) How does this compare with the 50-ppm accuracy of the crystal oscillator? c) Repeat parts (a) and (b) if the number of counts of the Timer1 oscillator between Timer1 rollovers were reduced to 327. 7-3 Effect of stopping-starting Timer1 Consider that the output of the Timer1 oscillator is a squarewave, and that the Timer1 counter is clocked on the rising edge of this squarewave. With an oscillator period of about 30.5 µs, the oscillator output will be high for about 15 µs after the rising edge that produced the low-priority interrupt. During that time, the CPU wakes up and switches on its FCPU = 1 MHz clock. It takes several microseconds to set aside the program counter and a few other CPU registers before clearing the TMR1ON bit to block clock edges from reaching the Timer1 counter. It takes 2 µs to update TMR1L before setting the TMR1ON bit again. As shown in Figure 7-4, both the TMR1ON bit and the Timer1 oscillator’s squarewave output are inputs to an AND gate whose output clocks the Timer1 counter. a) Draw a timing diagram showing the inputs and output of the AND gate assuming the clearing and setting of TMR1ON takes place during the first 15 µs after the Timer1 rollover that caused the interrupt. b) Now repeat this, assuming a high-priority interrupt intervenes and delays the entry into the LPISR from the time of the Timer1 rollover by 30.5 × n + 15 µs, where n is 0 or 1 or 2. c) If the LPISR adds 65,536 + 1 − 328 = 65,211 to whatever number is in the Timer1 counter, how many Timer1 oscillator periods will occur between the last Timer1 rollover and the next one? Answer this for both parts (a) and (b). 106 Chapter 7 Reorganization of Timing Via Interrupts (T3.c) 7-4 Reinitializing Timer1 versus adding into it The LoPriISR of Figure 7-6, the T3.c program, adds 0xFEB9 to Timer1. A slightly simpler procedure would be to load 0xFEB9 into Timer1. In both cases, assume TMR3ON = 0 when the low byte, TMR1L, of Timer1 is updated. a) If this adding or loading takes place within 15 µs of when Timer1 rolled over, what will be the time until the next rollover in each case? b) Now assume that the adding or loading takes place 31.5 × 2 + 5 = 68 µs after the Timer1 rollover, delayed by an exceptionally long intervening highpriority interrupt service routine. What will be the time until the next rollover in each case? 7-5 Effect of 8-bit add Instead of adding 0xFEB9 to TMR1H:TMR1L, the LoPriISR of the T3.c template program simply adds 0xB9 to TMR1L and loads 0xFE into TMR1H. The possible clocking of TMR1L is prevented by making TMRON = 0 during the addition on the chance that the CPU and the Timer1 oscillator might both try to change TMR1L at the same time. No such issue arises for TMR1H, which will contain 0x00 after the rollover and until 0x100 − 0xB9 counts of the Timer1 oscillator’s clock periods have occurred. a) How long is this? b) Using the simplified update scheme for TMR1H:TMR1L of the LoPriISR at any time short of this will produce what interval between the last interrupt and the next one? Explain. 7-6 Worst-case overlapping of interrupts The machine code generated by the line TMR1L += 0xB9 consists of a 1-µs-long instruction to load 0xB9 into a CPU register followed by a second 1-µs-long instruction to add the CPU register to TMR1L. An interrupt cannot break into the middle of the execution of an instruction. Hence, were the HPISR to interrupt during the execution of the LPISR’s execution of the add instruction, a) What would be the effect on the addition? b) What would be the effect on the counting of Timer1 oscillator clock edges if the HPISR that causes the CPU to digress from the LPISR at this precise point in its execution takes 20 µs to execute? c) What is the percent chance of a randomly occurring high-priority interrupt producing the effect of (b), given that the LPISR is executed every 10 ms = 10,000 µs? Chapter 8 STEPPER MOTOR CONTROL 8.1 OVERVIEW A stepper motor is a low-cost, high-resolution positioning actuator. Though it would not seem to fit in an environment powered solely by the coin cell of the Qwik&Low board, a $5-motor can be powered by a $5-wall transformer as shown in Figure 8-1 and driven with signals from the Qwik&Low board. The role of the driver chip is filled by a $3-part manufactured by Allegro Microsystems, a company with a long history of building sophisticated stepper-motor logic and current-switching technology into a chip. The resulting combination produces an actuator with a resolution of 200 steps per revolution that can be stepped at rates up to 800 steps/s or so. 8.2 STEPPER-MOTOR OPERATION Taking apart a 200 steps per revolution stepper motor illuminates its operation. Figure 8-2a shows that its rotor consists of two sets of laminations separated by a thin doughnut-shaped permanent magnet. Each set of laminations has 50 teeth that are offset by one-half of a tooth from the other set. The net result is to produce a low-cost rotor consisting of 50 N-S pole pairs. The two sets of laminations and their permanent magnet are mounted on a motor shaft with ball bearings on each end for support within the stepper-motor case. 107 Thus. the rotor rotates one full step. Let “B” and “B” do the same for current into the 2 – 4 – 6 – 8 windings. Fifty of these four-step sequences will result in the stepper motor turning one revolution. with every other winding connected together but wound in the opposite direction. and e illustrate the sequence of four steps that return to the winding excitation of Figure 8-3a. d. and 7 a south pole. 5 a north pole. Full stepping consists of sequencing the windings as follows: … A B A B A B A B A … . the 6 teeth on one pole are offset by 1. 1 – 2 – 3 – 4 – 5 – 6 – 7 – 8. Figures 8-3b. These teeth have the same pitch as the 50 teeth of a set of rotor laminations. note that each pole is broken into six teeth. It is this 1.25-tooth offset that produces the offset shown in Figure 8-3a. This accounts for the motor being designated a 200 steps per revolution motor. Backtracking to the photo of Figure 8-2b. In response. This is illustrated in Figure 8-3a.108 Chapter 8 Stepper Motor Control FIGURE 8-1 Stepper motor addition to the Qwik&Low board The stator of the stepper motor is shown in Figure 8-2b. c. Let “A” represent a current into the 1 – 3 – 5 – 7 windings while “A” represents the reverse current into the same windings. then a current into 1 – 3 – 5 – 7 that makes winding number 1 a north pole will make 3 a south pole. For this step. Furthermore. It consists of eight windings on eight poles. A 200 steps per revolution motor can be made to step 400 steps per revolution by means of half-step sequencing of the winding currents. the winding current in 1 – 3 – 5 – 7 is turned off while the winding current in 2 – 4 – 6 – 8 is turned on. where stator poles 1 and 5 and stator poles 3 and 7 are shown aligned with the rotor while stator poles 2 and 4 and stator poles 6 and 8 are shown offset by half a tooth.25 teeth from the 6 teeth on an adjacent pole. if the windings are numbered in order. A full step is illustrated by the change between the winding energization of Figure 8-3a and that of Figure 8-3b. 2 Stepper-Motor Operation 109 (a) Rotor (b) Stator FIGURE 8-2 Stepper motor .Section 8. 110 Chapter 8 Stepper Motor Control Stator poles 1 and 5 Stator poles 2 and 6 Stator poles 3 and 7 Stator poles 4 and 8 Rotor • • • S N ••• N S S N S ••• N S N S N S N ••• (a) Step position 0 Stator poles 1 and 5 Stator poles 2 and 6 Stator poles 3 and 7 Stator poles 4 and 8 Rotor ••• ••• N S N S S N N S S N ••• S N S N ••• (b) Step position 1 Stator poles 1 and 5 Stator poles 2 and 6 Stator poles 3 and 7 Stator poles 4 and 8 Rotor ••• S ••• S N N S N ••• S N S N S N S N ••• (c) Step position 2 Stator poles 1 and 5 Stator poles 2 and 6 Stator poles 3 and 7 Stator poles 4 and 8 Rotor ••• S N S N S S N N S S N N S ••• ••• N ••• (d) Step position 3 Stator poles 1 and 5 Stator poles 2 and 6 Stator poles 3 and 7 Stator poles 4 and 8 Rotor N ••• N S S N S ••• ••• S N S N S N S N ••• (e) Step position 4 (same as step position 0) FIGURE 8-3 Stepper motor operation . the winding excitation does not repeat before eight half steps have been taken. All high-performance stepper motors are built as bipolar stepper motors for several reasons: • For the same number of turns of wire on each pole and the same current in each winding. thus producing a higher maximum stepping rate. Half stepping is produced by the sequence: … A AB B AB A AB B AB A … Here. Six leads are brought out of the motor. Figure 8-4b shows one split winding of a unipolar stepper motor. • Reversing the current in a winding is more aggressively addressed with an Hbridge driver than with a unipolar driver. When full stepping is selected. the A current will flow. An alternate. each winding is energized with the 70.3 Bipolar Versus Unipolar Stepper Motors 111 where the winding excitation repeats every four steps. The larger flux means more torque is produced for each step.0% of the current established by the current-sensing resistor while a step position with two windings energized uses 70. 8. quarter stepping. the torque produced at each step is the same. the current is cut off.7% of that current for each winding. the A current will flow. When half stepping is selected. Because the magnetic flux produced is the same under all circumstances for all four stepping modes. a step position with only one winding energized uses 100. a bipolar motor produces twice the magnetic flux of that produced by a unipolar motor. the inductance of a . If the upper left and bottom right transistor switches are both turned on. It is driven by applying the motor supply voltage to the center tap and using either of two transistor switches to ground one side or the other. Contrast this with a modern bipolar stepper motor like that of Figures 8-1 and 8-2 for which each winding must be driven with current in either direction. If all transistor switches are turned off. An H-bridge driver such as that of Figure 8-4c provides the solution for reversing the current for each winding.3 BIPOLAR VERSUS UNIPOLAR STEPPER MOTORS Figure 8-4a illustrates in crude form the excitation of a winding with current in either direction. It does so by controlling not only the direction of the A and B currents but also their magnitude.7% of the current. if the upper right and lower left transistor switches are both tuned on. three for each winding. half stepping. In both cases. and eighth stepping. where only half of the winding is used at any one time. popular mode of full stepping makes use of the sequence … AB AB AB AB AB … The sophisticated Allegro Microsystems A3967 stepper-motor driver chip used in Figure 8-1 has two logic inputs that allow a user to select any of four stepping modes: full stepping.Section 8. In like manner. The effect is to help reduce vibration and noise. The chip itself can handle a motor supply voltage as high as 30 V and a maximum current per winding of ±750 mA.112 Chapter 8 Stepper Motor Control A VMOTOR A or VMOTOR (a) The problem VMOTOR A (split winding) (b) The unipolar stepper motor solution VMOTOR A A A Current-sensing resistor FIGURE 8-4 Two solutions to reversing the current in a stepper motor winding (c) The bipolar stepper motor H-bridge driver solution winding impedes the change. With all four leads of the bipolar stepper motor connected only to the A3967. the controller chip has full control of the winding voltages and currents. 8. . In contrast. A tradeoff is made between speed of decay and maximum breakdown voltage of the opened transistor switch that confronts the back emf of the collapsing magnetic field in the winding. The board includes (unpopulated) options for varying the drive parameters that are controlled by the $3 Allegro A3967 driver chip. A unipolar driver typically allows the current in a turned-off winding to decay through a diode-resistor circuit.4 STEPPER-MOTOR DRIVER The stepper-motor driver board (designed for use in conjunction with the Qwik&Low board and available as an option) is shown in Figure 8-5a and its circuit in Figure 8-5b. a bipolar driver chip such as Allegro’s A3967 deals with current control and the breakdown voltage limits of its output transistors as an integrated whole. “Step” and “Dir”. are low. as occurs with every other half step described in Section 8.1-kΩ pull-down resistors is 120 µA.3-V supply from the 12-V input.7 sq.5-Ω resistors shown in Figure 8-5b are used to set the “100%” current level in each of the stepper motor’s two windings.2.3 V minimum logic 1 voltage. When the inputs are both high. A 3.3-V regulator ensures that the logic inputs from the Qwik&Low board will never exceed this supply voltage and yet will exceed the 0. The provided supply is fine for the NEMA Size 17 (≈ 1.5-A limit is imposed by the A3967. the 20-V limit is imposed by the MC33269 voltage regulator). the outputs from the Qwik&Low board that drive these two inputs should be kept low except for the few microseconds needed to control them for each step. This supplies the 50-mA current draw of the logic circuitry of the A3967.4 Stepper-Motor Driver 113 The $5 regulated 12-V DC wall transformer shown in Figure 8-1 will supply a maximum current of 250 mA per winding. The resulting current draw on the Qwik&Low coin cell is essentially zero when the two inputs. that is.7 × 3. The 1.) stepper motor shown in Figure 8-1. Consequently. This current is specified by Allegro to be 100% current = ____ Vref 8 Rs (8-1) (a) Board FIGURE 8-5 Stepper motor driver board . the current draw by the two 51. The circuit shown in Figure 8-5b derives a 3.5 A (the 1. in.Section 8. This supply can be replaced by a supply of up to 20 V @ 1.3 V = 2. the current level set when one winding is being driven while the other winding is turned off. 114 Chapter 8 Stepper Motor Control Blue Bipolar stepper motor rating: 1.1 kΩ . 1 w 4 .5 Ω. Less than 12 V 2.5 Ω current-sensing resistors shown below R3 Example: Jameco 163395 51.1 mm barrel connector (b) Circuit (not shown are unpopulated options) FIGURE 8-5 (continued) .5 Ω.3 V GND 115 VAC 2. 4 w .25 A with default 1.5 A VCC = 3.01 µF C3 Red TB1 White Terminal block 1 2 3 4 Yellow REF RC2 SLEEP OUT2B U1 PFD RC1 RESET 24 23 22 21 R8 51.01 µF C4 GND H3 10-pin header 1 for ribbon cable from Qwik&Low 9 board 2 OUT1B LOAD 20 + 33 SUPPLY SUPPLY 33 + µF µF GND GND 5 LOAD 10 STEP DIR 6 7 GND GND 8 SENSE2 SENSE1 9 OUT2A STEP DIR OUT1A 19 18 17 16 15 14 13 10 11 ENABLE VCC MS2 R1 51.5 A wall transformer (Digi-key T983-P5P) VMOTOR = 12 V@0.1 kΩ R2 51.001 µF C2 VMOTOR Current sensing resistor R4 1.1 kΩ 12 MS1 Allegro A3967SLB-T Digi-Key 620-1073 $2.1 kΩ . Current per winding will be 0.001 µF C6 VMOTOR Current sensing resistor R6 1 1.75 VMOTOR VCC GND Toggle switch LED S S R B CON1 D1 10 kΩ 1N5818 TB2 Terminal block ON Semiconductor MC33269 Voltage regulator 3 U2 4 + C8 10 µF 1 12 VDC regulated @0. 5 STEPPING Stepper motors are widely used as open-loop positioning actuators because of being able to reach a given position by counting steps from the present position.RD1 = 1. //Clockwise //Pause 1µs //Take step //Zero the pulldown resistor currents A CCW step is simpler: PORTDbits.7% to 0% current. The driver board includes the provision for replacing the resistor in each RC circuit with a one-turn trimpot. RD0 and RD1. 563 steps CW followed by 563 steps CCW will return the motor output to the same position from which it started. These options provide refinements to what is. in deference to the 0. The Allegro chip pulse-width-modulates the current to each motor winding. the following sequence is executed: PORTDbits. as long as no steps are lost by stepping too fast.5-Ω (1/4-W) resistor on the board. 8.7% current or from 70. the 100% current has been set to a quarter of an ampere. A third option is to add jumpers to the MS1 and MS2 inputs that allow the default full-stepping mode to be replaced by half stepping. Furthermore.5-A power supply. namely the regulated 3. With the 1. the error in step position never accumulates. quarter stepping. that is. PORTDbits. turning on the two diagonal transistor switches of the H-bridge driver when the current is low and opening the upper transistor switch when the current has risen to the 100% level. Or the MS1 and MS2 pins can be connected to pins on the 10-pin header connected to the Qwik&Low board to allow this choice to be made by the MCU. With the 10-pin ribbon cable connected between the Qwik&Low board and the stepper-motor controller board as shown in Figure 8-6a. should a user wish to experiment with the PWM frequency.3-V supply voltage.RD0 = 1. Another optional potentiometer can be connected to the PFD pin to control how fast the current in a winding decays for a half step from 100% current to 70. The RC circuits connected to RC1 and RC2 control the PWM frequency. Nop(). as indicated in Figure 8-6b. the two MCU pins.RD0 = 0.5 Stepping 115 where Vref is the voltage connected to pin 1 of the chip.5-Ω resistors) plus two jumpers to select one pair or the other. PORTDbits. control stepping.RD1 = 0. The board also includes the option of installing alternate current-setting resistors (alternate to the 1. Thus to take a CW step.RD1 = 0. an excellent and clean application of Allegro’s superb driver chip. refer to Appendix A4. //Take step //Zero the pulldown resistor current . For more information on the stepper-motor driver board.RD1 = 1. by default. PORTDbits.Section 8. or one-eighth stepping. PORTDbits. Within the data sheet. Consider Figure 8-3a and also the photograph of a) On the photograph.RD0 = 1: Take a step 1: CW 0: CCW (b) Control by MCU FIGURE 8-6 Stepper motor connections and control PROBLEMS 8-1 Stepper-motor operation Figure 8-2b.25tooth offset between adjacent stator poles. . PORTDbits. 8-2 Quarter stepping To get to the data sheet for Allegro Microsystem’s A3967 stepper-motor driver chip. Google “A3967”. Given the 1. b) Now do the same with a different color for the excitation of Figure 8-3b. it explains the movement of the rotor by one-quarter of the distance from one of its north poles to an adjacent north pole.116 Chapter 8 Stepper Motor Control Qwik&Low R B WY Stepper Driver RD1 RD0 STEP DIR Ribbon Cable BRS S (a) Connections PORTDbits RD1 = 0 MCU Stepper motor connections Power switch connections LED connections Power supply connector . find its specification for the two winding currents at each quarter-step position. label the poles that are north poles and those that are south poles. This illustrates how the stator north and south poles move. com) or of Marlin P. each stepper winding is energized with a current that is 70.1-mm barrel connector that can be used with the stepper-motor driver board. what resistance value is optimum? b) The driver board has provision for adding a second pair of current-sensing resistors plus two 3-pin headers and two jumpers so that the switch from one pair to the other involves moving two jumpers.2. what should be the resistance of the current-sensing resistor to produce a winding current of 70. The board uses Type 1210.7% of the “100%” current set by the current-sensing resistor via Equation 8-1 of Section 8.2 Ω. Look in the on-line catalog of surplus parts of Herbach and Radman (www. Digi-Key also stocks T986-P5P.5 Stepping 117 a) What is maximum current in a winding relative to the “100% value” of Equation 8-1? b) If used with the 12 V @ 0. another resistor might be used to control the current that drives the stepper motor harder. an 18 V @ 0. and what is the resulting 70.Section 8.5 A regulated supply discussed here (Digi-Key T983-P5P). 1. 1. (www. Consequently. . … Which resistors are a good choice for the second pair.mpja. 1.8 Ω.5 A regulated supply that must supply current for two windings.5 Ω. The sizes supplied by Digi-Key are: ….33 A regulated supply with the same 2.c steps the stepper-motor CCW.com) for any bipolar (or “four wire”) stepper motors that specify a voltage and either current per phase or resistance per phase that can be used with the stepper-motor driver board with the 18-V supply. 2. 1/4-W surface-mount parts for these resistors.4. a) Modify it to step CW.5 A regulated supply of Figure 8-5b. what current-sensing resistors should be used to limit the supply current to the 0.2 Ω. As pointed out there.5 A of the power supply? 8-3 Current-sensing resistor The stepper-motor driver board of Figure 8-5 uses. Jones & Assoc. a) What is the part number and what are its specifications? b) Using Equation 8-1 in the text. b) Check the current draw on the coin cell with and without the steppermotor ribbon cable attached to the Qwik&Low board. a) Given the 12 V @ 0. by default.7% of the value set by Equation 8-1? 8-5 Clockwise stepping The code of T3. the full-stepping mode described at the close of Section 8. 1.7% current that will excite each winding? 8-4 Alternate power supply Along with the 12-V DC @ 0.0 Ω.herbach. 032768 = 131 Timer3 counts This leads to STEPCNT = 65.536 + 1 − 131 = 65. Timer3 must roll over every 4. also switches the stepping rate between 250 steps/s and 500 steps/s.c uses an int variable. to control the stepping rate. .118 Chapter 8 Stepper Motor Control 8-6 Variable stepping rate The code of T3. To step every 4 ms (i.000 × 0.e.c so that each press of the pushbutton. in addition to incrementing the displayed pushbutton count. at a rate of 250 steps/s).406 Modify the Pushbutton function of T3. STEPCNT.. pressure. any one of which can be multiplexed into its 10-bit converter.Chapter 9 ANALOG-TO-DIGITAL CONVERTER 9.2 QWIK&LOW ANALOG VERSUS DIGITAL PINS The PIC18LF4321’s ADC has 13 possible analog inputs. acceleration. For example. • A conversion time of 24 µs. 9. weight. as shown in Figure 9-1. This module greatly extends the reach of the MCU into applications that employ any of the wealth of transducers (of temperature. • The inclusion of a multiplexer that allows up to 13 pins to be used as analog inputs. etc. The figure illustrates that each analog input is shared with a digital input or output on a port pin. The ADC is a versatile module in the MCU with the following features: • A resolution of 1 part in 1. • A choice of reference voltages.024.1 OVERVIEW This chapter discusses the features and use of the analog-to-digital converter (ADC) module in the PIC18LF4321. the 119 .) that produce a voltage output. Figure 9-2 shows how the choice is made. The 4-bit number loaded into the port configuration control bits of ADCON1 can select any number of the 13 possible analog inputs to actually serve in this capacity. the specification of . Because this input shares a pin with the RA0 bit of PORTA.120 Chapter 9 Analog-to-Digital Converter PIC18LF4321 PORTB RB4 RB3 RB2 RB1 RB0 ADC Ten-bit converter MUX AN12 AN11 AN10 AN9 AN8 AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0 Qwik&Low resources Undedicated digital I/O *# Undedicated digital I/O * Undedicated digital I/O *# Undedicated digital I/O *# Interrupt input from RPG Power for RPG interrupt input RPG direction input Power for pushbutton and RPG direction Undedicated analog/digital pin *# Reference voltage input from RD6 Undedicated *# Analog input from temperature sensor Analog input from potentiometer Analog input VREF+ Key VDD VREF− * Pin brought out to proto area (H4) # Pin brought out to ribbon cable connector (H6) PORTA RA0 RA1 RA2 RA3 RA5 PORTE RE0 RE1 RE2 FIGURE 9-1 Analog-to-digital converter pin connections both within the PIC18LF4321 and to Qwik&Low resources Qwik&Low board’s potentiometer is connected to the ADC’s AN0 input. with the remaining inputs serving as digital I/O pins. a choice between these two uses of the pin must be made. Unlike some other PIC microcontrollers. Also. the choice is critical in the following sense: • Any pin that is selected to be an analog pin has its digital I/O circuitry disabled. • A temperature sensor. Port configuration control bits 1: VREF+ = AN3 pin VCFG0 0: V REF+ = VDD 1: VREF− = AN2 pin VCFG1 0: V REF− = GND Unused AN12 AN11 AN10 AN9 AN8 AN7 AN6 AN5 AN4 AN3 AN2 AN1 D D A A A A A A Number of analog channels 0 1 2 3 4 5 6 7 • • • PCFG control bits 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 • • • 1 1 0 0 1 1 0 0 1 0 1 0 1 0 1 • • • D D D D D D A A D D D D D A A A D D D D A A A A D D D A A A A A D A A A A A A A FIGURE 9-2 Selection of I/O pins to be analog inputs the number of analog inputs selected also specifies which pins will be the analog pins. The two devices designed into the Qwik&Low board having analog inputs are: • The potentiometer.2 Qwik&low Analog versus Digital Pins 121 ADCON1 0 0 0 0 1 1 0 0 PCFG. the digital circuitry will exhibit excessive leakage current.Section 9. for an analog input in the middle voltage range (well above 0 V and well below 3 V). • Any pin that is selected to be a digital pin can then be set up to be a digital (high-impedance) input and also used as an analog input. the output pin of the MCU that powers the temperature sensor is used as the VREF+/AN3/RA3 pin. However. These have been assigned to AN0 . taking advantage of a sensor whose voltage output is proportional to its supply voltage as well as its temperature. Furthermore. the output voltage will not subject the also enabled digital input circuitry to a leakage-current-inducing voltage in the middle range. Whether initialized high or low. . AN1. the 2 bytes of which can be identified as ADRESH FIGURE 9-3 ADC result alternatives ADCON2 x x x x x x x ADFM 1: 0: Right justify result Left justify result (a) ADC format control bit ADRESL ADRESH ADRES 0 0 0 0 0 0 b b b b b b b b b b for ADCON2bits ADFM = 1 . Consider again Figure 9-1. One more analog device can easily be added to the proto area of the Qwik&Low board by connecting the analog device’s output to the MCU’s AN2 input. ADRES. 9. ADRESL ADRESH ADRES b b b b b b b b b b 0 0 0 0 0 0 for ADCON2bits ADFM = 0 (b) Two alternative sixteen-bit result formats ADRES 0 0 0 0 0 0 b b b b b b b b b b (with ADFM = 1) (c) Sixteen-bit result in ADRES ranging from 0–1023 as input ranges from 0 V to VDD ADRESH b b b b b b b b (with ADFM = 0) (d) Eight-bit result in ADRESH ranging from 0–255 as input ranges from 0 V to VDD ADRESL b b b b b b b b (with ADFM = 1) (e) Eight-bit result in ADRESL ranging from 0–255 for inputs less than VDD/4 = 750 mV or .122 Chapter 9 Analog-to-Digital Converter inputs AN0. any that are unused will be set up as outputs. Another analog input can be connected to the AN4/RA5 input pin if the port configuration control bits of Figure 9-2 are changed to 1010. and AN3 respectively so that a choice of 1011 for the Port Configuration control bits of Figure 9-2 will designate all but one (AN2) of the remaining pins to be available as possible digital I/O pins. Of these digital pins. the 10-bit result will be returned either right justified or left justified in the 16-bit register.3 ADC RESULT ALTERNATIVES Depending on the state of the ADFM (ADC format) bit of Figure 9-3a at the time of an ADC conversion. 5 ADC Timing 123 and ADRESL.8 V some time later.Section 9. By reading only this unsigned char variable. of an 8-bit output. The temperature sensor on the Qwik&Low board generates an output voltage proportional to temperature and to the supply voltage. the temperature sensor may see a supply voltage that is 80 mV less than VDD. Obtaining the output of the single-turn potentiometer on the Qwik&Low board as a number having 256 values can be achieved by first clearing ADFM to zero. the least significant 2 bits of the 10-bit conversion are ignored.023 range of the ADC output. In addition to controlling the left justify/right justify ADFM feature. this register controls the timing aspects of the converter. the temperature reading will be the same.8 V. 9. . as shown in Figure 3-2.. What remains in ADRESH is a value of 0 if the potentiometer is turned fully CCW and a value of 255 if the potentiometer is turned fully CW. 9. Given FOSC = 4 MHz. but somewhat uncertain. To use the full 0–1. TAD. ADFM should be set prior to the conversion. The clock period. When the conversion is complete. to left justify the result. This is equivalent to 26 counts of the ADC (for which each count represents 3. Normally both VCFG0 and VCFG1 will be initialized to zero. With an output impedance of the RD6 pin of perhaps 200 Ω driving the 400-µA current drawn by the temperature sensor. Another way is to load ADCON1 = 0b00011011 This value will make AN3 an analog input and will use the input on AN3 from the RD6 output as the VREF+ reference voltage pin for the ADC for this measurement. However. On its completion. The choice of Figure 9-3e provides the same resolution as using the 16-bit ADRES output of Figure 9-3b but with the computational advantage. This means that whether the supply voltage is 3 V early in the coin cell’s life or 2.5 ADC TIMING The ADCON2 register is described in Figure 9-4. for subsequent scaling of the output. the upper 8 bits of the conversion will reside in ADRESH. less than VDD/4). One way to handle this offset is as an added. ADRES can be read as the unsigned int variable of Figure 9-3c.4 µs. the sensor is powered from RD6. Another option arises for an analog device whose output has a range reaching up to less than 750 mV (i.000/1. The PIC18LF4321 specification indicates that the chip will produce a scaled 10-bit output even with (VREF+ − VREF-) down to 1.4 REFERENCE VOLTAGE CHOICE The ADCON1 register of Figure 9-2 contains 2 control bits that allow an analog input to be scaled by a reference voltage input. as shown in Figure 9-3b. as illustrated in Figure 9-3d. throwing away the extra resolution provided by those 2 bits. term in the temperature calculation. Figure 9-4a defines terms used in the specifications of Figure 9-4b. Then the analog input will be compared against a voltage range extending between GND and VDD.024 ≈ 3 mV ).e. of the ADC should be no shorter than 1. making TAD = 2 µs.124 Chapter 9 Analog-to-Digital Converter TAD TACQ RSOURCE VREF+ is the ADC clock period. The time between selecting which input pin is to be multiplexed into the ADC and when the conversion is begun is automatically controlled by the TACQ parameter. the two that a user has some control over are the source impedance of each analog source and the needed resolution of the result. Among the factors entering into the acquisition time determination. With TAD = 2 µs.8 V Conversion time = 12 TAD (b) PIC18LF4321 specifications ADCON2 0 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 TAD = 2 µs for FOSC = 1 MHz TAD = 2 µs for FOSC = 2 MHz TAD = 2 µs for FOSC = 4 MHz TAD = 2 µs for FOSC = 8 MHz TAD ≈ 2. sufficient for the two analog devices on the Qwik&Low board.3 (c) Initialization options for ADCON2 FIGURE 9-4 ADCON2 initialization Figure 9-4c indicates that the least significant 3 bits of ADCON2 should be initialized to 001. is the optional external high reference voltage (if used) (a) ADC definitions 2.5 µs > TAD > 1.4 µs TACQ > 3.0 V > VREF+ > 1. A value of TAD of 1 µs or less is too fast for accurate conversion while a TAD of 4 µs or greater will produce conversions that take 48 µs or 96 µs. the 10-bit conversion will take 12 × TAD = 24 µs.9 µs for RSOURCE ≤ 20 kΩ VDD + 3. Thevenin) resistance of the device whose voltage output is being measured. is the ADC acquisition time required between when an ADC channel has been selected and when a conversion can be initiated.5 µs using the ADC’s internal RC oscillator TACQ = 2 × TAD = 4 µs Unused ADFM 1: Right justify result 0: Left justify result See Figure 9. The 001 setting of Figure 9-4c selects an acquisition time of 4 µs. ..7 µs for RSOURCE ≤ 5 kΩ > 6.e. is the source (i. Section 9.6 ADC Input Selection and Conversion 125 Example 9-1 Determine the maximum source resistance of the 20-kΩ potentiometer. When the potentiometer is turned fully CCW. It also contains an ADON bit that selects whether the ADC module in the MCU is powered up or not. the source resistance is at its maximum of 10 kΩ to VDD in parallel with the 10 kΩ to ground. 9. That is. the source resistance is 0 Ω. the maximum source resistance is 5 kΩ. A small internal sampling capacitor in the ADC charges up to match the (Thevenin) voltage of the analog source. the short circuit to VDD (which is the same as a short circuit to ground.6 ADC INPUT SELECTION AND CONVERSION The ADCON0 register of Figure 9-5 contains bits to select the analog input. Solution The source resistance is really the Thevenin resistance of a source. the short circuit to ground. Then the GO_DONE bit becomes a flag that can be tested to determine whether the conversion has been completed. The RC time constant of this charging depends on internal resistances in the ADC in series with the source resistance. FIGURE 9-5 ADCON0 use ADCON0 0 0 ADON 1: ADC module is powered up 0: ADC module is powered down Set bit to initiate conversion Conversion is complete when bit returns to zero GO_DONE Unused 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 1 0 1 0 Select Select Select Select Select AN0 AN1 AN2 AN3 AN4 • • • . When the potentiometer wiper is at its midpoint. it contains a GO_DONE bit that is set to initiate a conversion. The source resistance affects the maximum acquisition time. Finally. assuming the coin cell has essentially zero internal resistance). When the potentiometer is turned fully CW. the source resistance is again 0 Ω. PORTAbits. // ADCON0 = 0x03. Such a low current draw suggests another way that conversions can be carried out.RA7 = 1. • Select an analog input. select pot input. start conversion // Wait for completion of conversion Power down potentiometer Power down ADC FIGURE 9-6 Use of ADC to read potentiometer Because the acquisition time setting in the ADCON2 register inserts a delay after the GO_DONE bit has been set and because the ADC module powers up essentially instantaneously relative to the 8 µs acquisition time selected. ADCON0 can be loaded with the one value that will: • Power up the ADC. Solution Figure 9-6 shows the code lines to use VDD as the reference voltage. the output on RA7 that powers the potentiometer must be set. // PORTAbits. The remaining lines power down the potentiometer and the ADC module as soon as possible before the result in ADRESH is read and used.ADON = 0.0 µA. to have the upper 8 bits of the 10-bit result put into ADRESH. left justify result Power up potentiometer (see Figure 3-2) Power up ADC.GO_DONE). as shown back in Figure 3-2. . Before the conversion is initiated.7 ADC CONVERSION DURING SLEEP When the ADC is on but not converting. If the setting of the GO_DONE bit is immediately followed by the Sleep instruction.RA7 = 0. the ADCON2 register’s bits for setting TAD offer the option of using the ADC’s own RC oscillator as its clock. it typically draws 1. The conversion of the potentiometer input to AN0 is then initiated. As indicated in Figure 9-4c. Using this RC oscillator allows a conversion to be carried out while the chip is asleep. // ADCON2 = 0x09. the current draw will be reduced. Then the ADFM bit is cleared. // while (ADCON0bits. to use the timing associated with FOSC = 4 MHz. Example 9-2 Show the code to convert the output of the potentiometer into an 8-bit value in ADRESH. // <read result from ADRESH> Initialize ADC for Q&L's four analog inputs ADC clock with Fosc = 4 MHz. and to form ADRESH. 9. // ADCON0bits. The result will be found in TACQ + 12 TAD = 4 + (12 × 2) = 28 µs with the automatic clearing of the GO_DONE bit signaling that ADRESH is ready with the result. • Initiate the conversion.126 Chapter 9 Analog-to-Digital Converter ADCON1 = 0x0b. If the CPU is awake for an extra 28 µs every tenth of a second.29 – 0. the converted output value is insensitive to whether the coin cell is new. its quiescent current of 1. with an output voltage of (say) 2.10 µA 100ms If the CPU spends 2 ms out of every 10 ms loop time doing useful work before going to sleep. since that is essentially the same whether carried out while asleep or awake. But between the setting of the GO_DONE bit and its automatic clearing at the completion of the conversion. the net benefit of doing 10 conversions/s while asleep is about 0.4. Referring back to Figure 2-4. By taking advantage of the ratiometric feature of the sensor.6 V. Furthermore. It also shows this same supply voltage serving as the reference voltage for the conversion. 9. by using this same supply voltage from RD6 (rather than VDD) as the reference voltage for the conversion. if the conversion is carried out while asleep.29 µA 100. Because the quiescent current is specified to be in the 350 µA–600 µA range over a supply voltage range of 2.7 V–3. the sensor needs to have its power switched off when it is not in use.036 mA was measured when the CPU was running with FOSC = 4 MHz but otherwise doing nothing to draw extra current. It is connected to the MCU as shown in Figure 3-2.000 regardless of how much current the ADC module draws. . or run down. with an output voltage of 3.0 µA = 0. the circuit of Figure 3-2 shows the sensor being powered from RD6. this is a ratiometric temperature sensor whose output voltage is not only proportional to temperature but also to its supply voltage.21 µA of average current.7 V.Section 9.036 µA = 0. As mentioned in Section 9.8 AD22103 TEMPERATURE SENSOR The Analog Devices AD22103 temperature sensor is the small three-terminal device housed in the TO-92 transistor-like package located in the upper left corner of the Qwik&Low board. a current draw of 1. what is the effect on average current draw of having the conversion take place during sleep versus while the MCU is awake? Solution The CPU will spend less time awake in the main loop if the conversion is put off until the chip sleeps.08 = 0. the awake CPU runs for the 28 µs pointed out at the end of the last section.8 AD22103 Temperature Sensor 127 Example 9-3 If the potentiometer output is read every tenth of a second. This will contribute some fraction of 10ms ______ × 1.0 V. Thus. the measurement is made insensitive to the output pin’s voltage drop due to its output impedance and the ≈400 µA current drawn by the sensor.0 µA while not converting will last for the duration of sleep within one pass through the main loop. On the other hand. this represents an extra average current draw by the CPU of 28 _______ × 1. 4°F. Over the full range for the part.4°F − 70.3 V. If the output voltage equals 3. if the sensor output voltage presently translates to a temperature of 71.8°F even though the absolute value of 71. With essentially no change between the first and the second reading.300 mV. VO. The typical error of a room temperature measurement should be within half a degree Centigrade. for a sensor supply voltage in the specified range of +2. VS. Obtaining a temperature reading from an ADC measurement is expedited by translating the expression of Figure 9-7b into an expression of temperature in terms not of voltage but of ADRES.024 = 77. Analog Devices provides a somewhat ambiguous accuracy specification for the AD22103. the typical error should be within ±0. Initiate the measurement.128 Chapter 9 Analog-to-Digital Converter Although Analog Devices does not specify a settling time for this temperature sensor. Wait for the completion of the conversion. Pause to allow the sensor to settle. the resolution produces temperature-difference measurements that are essentially correct. then the ADC converter would translate this to 3. By waiting perhaps 20 µs after raising RD6 and then making repeated full 10-bit ADC measurements spaced apart by the 24-µs conversion time of the ADC. For temperature changes. is given by the equation of Figure 9-7b.6°F. Often it is useful to obtain temperature measurements with a resolution that is finer than the absolute accuracy that is warranted for a sensor. namely 0°C–100°C. is 3. the output voltage. even though the ADC itself would show this result as 946.6 V.300 where. the 16-bit register that holds the 10-bit ADC output.050 _____ × 1. • Any longer asymptotic tail of this step response. Clear RD6 = 0 to power down the sensor.7 V to +3.6°F = 0.300 . whereas 10 min ago it translated to a temperature of 70.300 mV supply voltage.050 mV at 100°C when the supply voltage is 3. for the sake of the calculations that follow. then the increase over the last 10 min is actually quite close to 71. With the same 3.024 = 946. For example.75°C. evidently a 20-µs pause is sufficient. 0°C would translate to 250 _____ × 1. clearly this becomes an important consideration in the following sequence: • • • • • Set RD6 = 1 to power up the sensor.424 counts 3. More generally. the fast settling of the 10-bit readings can be verified. The transfer function of the AD22103 is illustrated in graphical form in Figure 9-7a when the sensor’s supply voltage.576 counts 3.4°F is probably less accurate. the three digits to the right of the decimal point are warranted as an intermediate result. The settling time of the sensor has two measurable components: • The settling out of its underdamped step response (≈10 µs). 424 − 77.8 AD22103 Temperature Sensor 129 VO 3050 mV 2000 mV 28 mV/°C 1000 mV 250 mV Centigrade 100°C (a) Transfer function for VS (the supply voltage) = 3.Section 9.68848 × Centigrade) + 77.3 V = 3300 mV VO = VS (volts) × 250 mV + (28 mV/°C) × Centigrade millivolts 3. these are the same readings that would be obtained with the measurements using the Qwik&Low circuit and its lower VDD and its even slightly lower RD6 supply voltage to both the temperature sensor and the VREF+ pin used by the ADC.575 100 − 0 = (8. again carrying extra (intermediate) digits of resolution.575 (c) Translation of (b) to counts of ADRES Centigrade = ADRES − 8.68848 °C (d) Reexpressing centigrade temperature as a function of ADRES Fahrenheit = 9 × Centigrade + 32 = ADRES + 15. .9285 8.576 × Centigrade + 77.82693 (e) Expressing Fahrenheit temperature as a function of ADRES FIGURE 9-7 AD22103 transfer function Because of the ratiometric feature of the sensor.3 (volts) (b) General transfer finction ADRES = 946.9287 5 4. The equation of Figure 9-7c expresses the resulting value of ADRES as a function of the Centigrade temperature. Instead of FIGURE 9-8 Temperature equations after converting voltage with ADCON2bits. If the terms in this equation are multiplied by 10.1˚F resolution . the resulting expression for the Centigrade temperature becomes that shown in Figure 9-8a. If the denominator of the quotient in Figure 9-7d is also multiplied by 64. If the Centigrade to Fahrenheit conversion of 9 F = __ C + 32 5 is applied to these equations.1˚C resolution Fahrenheit = (ADRES / 308.287 (d) For Fahrenheit measurement with 0. in effect. the integer result will be expressed in tenths of a degree Centigrade.ADFM = 0 (to left justify the output and. For example. Carrying out the calculation of Figure 9-7d using integer arithmetic (for speed) requires that numerator and denominator be multiplied by the same integer constant before the division takes place. Also. The conversion to Fahrenheit is shown in Figure 9-7e. Centigrade = (ADRES / 556. this multiplies ADRES by 64. multiply ADRES by 64). A calculation can be massaged to shorten its execution time.3°C. In effect. Recall from Figure 9-3b that clearing the ADFM bit of the ADCON2 register before the ADC conversion takes place will produce a leftjustified 10-bit result.9287 (c) For Fahrenheit measurement with 1˚F resolution TenthF = (ADRES / 30.130 Chapter 9 Analog-to-Digital Converter This is inverted in Figure 9-7d to express the Centigrade temperature as a function of the value of ADRES.9285 (a) For Centigrade measurement with 1˚C resolution TenthC = (ADRES / 55.285 (b) For Centigrade measurement with 0. a multiply or a divide of a multiple-byte number by 28 = 256 = 0x100 amounts to moving the bytes left or right by 1 byte. Note that a resulting integer of 253 represents a temperature of 25.6063) − 89. as shown in Figure 9-8b.8924) + 159. Note that multiply operations are significantly faster than divide operations.063) − 8.924) + 15. the equation is reexpressed in Figure 9-9a. 28 × 0x00001234 = 0x00123400 Applying these ideas to the equation of Figure 9-8d to obtain the temperature in tenths of a degree Fahrenheit. the equations of Figure 9-8c and d result. VALUE. broken down into separate steps that the C18 compiler handles better than a single-line calculation. The computation of Figure 9-9c is shown broken down into six steps for the benefit of optimization by the C18 compiler.287 (a) For Fahrenheit measurement with 0. FIGURE 9-9 Speeding up the calculation of temperature with 0. unsigned int BIGNUM.1˚F resolution 2^16 / 30. // 32 bits to avoid overflow // 32-bit repesentation // 16-bit representation // 16-bit representation (e) Calculation. VALUE >>= 8.121.8 AD22103 Temperature Sensor 131 dividing by the denominator of 30. VALUE += 159.8924 = 65536 / 30. The resulting equation is shown in Figure 9-9c. .8924 so that the denominator becomes 216 and also the division by 216 becomes two 1-byte shifts of the numerator. BIGNUM = VALUE.8924. The calculation in this form takes just 111 CPU clock periods. both the numerator and denominator can be first multiplied by 216 _______ = 2.43 30.121.8924 = 2121. ADRES can first be copied into the 4-byte-long variable.1˚F resolution TenthF = (ADRES / 30. (d) Definition of global variables VALUE = ADRES.8924) + 159.43 (b) Forming a multiplier for numerator and denominator that will make the denominator equal to 2^16 TenthF = ((2121 * ADRES ) >> 16 ) + 159 (c) Resulting equation unsigned long VALUE.Section 9. Execution takes 111 µs. To avoid overflow when the int register ADRES is multiplied by the int constant 2. VALUE *= 2121. VALUE >>= 8. collect three samples (for timing). b) Does the extra delay produce a difference between the two values? If so. Load this value into all eight RESULT[i] variables and form SUM equal to one of these. c) Compare the temperature you get with that of a mercury (or liquid) thermometer. . subtract RESULT[7] from SUM. Finally. BIGNUM (to divide it by eight. RESULT[1]. Clear it before the first loading of ADCON0 that produces a settled value of temperature. collect a new sample from the potentiometer.132 Chapter 9 Analog-to-Digital Converter PROBLEMS 9-1 Running average Write a Filter function that maintains an array of eight int values: RESULT[0]. RESULT[7] a) In the Initial function.c file on the 73. . and copy the sample value into RESULT[0]. Display these two samples side by side on the LCD using the format exemplified by 73. shifted left three places to multiply it by eight.1°C resolution.com web site so that after collecting a sample. b) Every tenth of a second. add it to SUM. qwikandlow. . Does the extra delay help? c) Set RB0 before the initial setting of RD6 that powers up the temperature sensor. .4 Update the values every half second.c file to use the equation of Figure 9-8b and a scheme analogous to that of Figure 9-9 to calculate the temperature with 0. and measure its execution time. shift SUM right three places into the int variable. 9-2 ADC timing a) Modify the Temperature function in the TenthsFahr. read a 10-bit value using the potentiometer output (as an easily available vehicle for averaging). immediately collect a second sample. . b) Set and clear RB0 around the calculation of Part (a).c file a) Modify the TenthsFahr. analogous to Figure 9-9e. but before powering down the sensor. throw away the first and display the second and third. What is the resulting sensor setup time? 9-3 TenthsCent. copy each RESULT value to the next location using a for loop. the number of samples in the running average) and then use the ASCII4 function from Figure 6-8b to break out the four digits and display them on the LCD. Because of its versatility. the RPG is used in many applications involving the entry of a multiple-valued parameter. It uses three internal electrical contacts to three tracks of a coded wheel. The little Bourns RPG on the left will be used to explain the operation of an RPG when polled from the main loop. If used to tune a radio. and ease of use with a microcontroller. 10. the sound level provides the feedback of its setting.2 RPG RESOLUTION Two RPGs are shown in Figure 10-1. For example. as illustrated in Figure 10-2a. This low-cost RPG shares the same features found on the more robust RPGs of commercial products and instrument designs. virtually every function generator uses an RPG rather than a keypad for controlling the frequency output. If used as an audio system volume control.Chapter 10 ROTARY PULSE GENERATOR (RPG. the use of the detented RPG found on the Qwik&Low board will be considered. a display provides frequency feedback. particularly if the parameter must be incremented or decremented to be useful.c) 10. also known as a rotary encoder. In this chapter. ruggedness. is a widely used device for parameter entry in an application. 133 .1 OVERVIEW The rotary pulse generator (RPG). The ALPS RPG. It provides a good example of polled operation. The inputs to RB1 and RB0 traverse through six cycles per revolution. the resulting changes can be used to increment or decrement the parameter being controlled. In the sections that follow. It also provides insight that will help clarify why an interrupt handler is used with the detented ALPS unit. The 24 or 30 increments per revolution resolution of these two RPGs is typical of the resolution found in many commercial products and instruments. also pictured in Figure 10-1 and actually used on the Qwik&Low board. Detented means that the unit includes a mechanism that causes the RPG shaft to “click” from one of its 30 increments to the next.134 Chapter 10 Rotary Pulse Generator (RPG.c) FIGURE 10-1 Two rotary pulse generators (Bourns 3315-C-001006L. the use of the Bourns RPG will be described first. By reading the RPG outputs at a faster rate than they change. has a resolution of 30 detented increments per revolution. a user will find it frustrating to have an undetented resolution so fine that one or more increments or decrements can occur when the knob is released. 10.3 RPG FUNCTIONALITY As an RPG is turned. and that holds the position when released. . Although it might seem that “finer is better”. its output pins traverse the 2-bit Gray code sequence … → 00 → 01 → 11 → 10 → 00 → … when turned in one direction and … → 00 → 10 → 11 → 01 → 00 → … when turned in the other direction. Each cycle produces four output states. giving 24 states per revolution. ALPS EC11G1524402) The pull-up resistors are powered up by raising RB3 when the RPG output is to be queried and powered down immediately afterwards. thus once again reducing the average current draw to a negligible amount. as shown in Figure 10-2b. At this maximum rate. every change of state will be detected.e.. By reading the RPG every time around the main loop (i.6 kΩ 22. because the application code integrates the effect of many rapidly occurring increments or decrements when the RPG is turned fast. missing any counts because of too-fast turning goes unnoticed. every 10 ms). The Bourns RPG carries a .Section 10. or 2 revolutions/s.3 RPG Functionality 135 PIC18LF4321 PORTB RB3 Three brushes 22.6 kΩ RB1 RB0 Conductive pattern Non-conductive pattern (a) Brush/wheel configuration One revolution (6 cycles) (24 states) One cycle (4 states) (b) Output FIGURE 10-2 RPG’s encoding wheel and brushes The Bourns unit has a specified maximum turning rate of 120 rpm. the minimum time between increments is about 20 ms. Furthermore. OLDRPG should be updated with the value of NEWRPG read at the beginning of the function rather than by reading and masking PORTB again. saving this value for use 10 ms later. RB1 and RB0 are compared with their state 10 ms earlier in the RPG function of Figure 10-3. to form NEWRPG. only the 00 and 11 states represent detented positions. its outputs would be sensed by raising RB3. If the bits have changed in a CW direction. care should be taken to read the pins just once. reading its output every 10 ms effectively debounces it. The ALPS unit with its detented output is used somewhat differently. Each time around the main loop. The RPG function compares the value of NEWRPG (0. next time around the main loop. The subroutine returns with DELRPG = 0x00 = = +1 -1 if no change if CW change if CCW change Other functions called within the main loop can use the value of DELRPG to increment or decrement a parameter value in response to a change in the RPG position. If these values differ. or 3) with the value found 10 ms ago. It is needed at the beginning of the function to compare with the state 10 ms ago. However. Consequently. the present state of NEWRPG is used to update OLDRPG. 1.c) maximum contact-bounce time specification of 5 ms. At the conclusion of the function. For bug-free code. waiting for 1 µs (with a Nop() macro) to allow for the 22. 10.6-kΩ resistors and the slight capacitive loading of the circuitry to charge up.136 Chapter 10 Rotary Pulse Generator (RPG. Its two output pins traverse the same 2-bit Gray code sequence … → 00 → 01 → 11 → 10 → 00 → … when turned in one direction and … → 00 → 10 → 11 → 01 → 00 → … when turned in the other direction. 2.4 THE RPG FUNCTION If the Bourns RPG were added to the Qwik&Low board as shown in Figure 10-2a. the state of PORTB is read and masked. When reading external pins from within a function. reading PORTB. one of the following four cases will have occurred: 00 → 01 01 → 11 11 → 10 10 → 00 . a change has taken place in the RPG position. In the case of the RPG function. and lowering RB3 again. // Wait a microsecond NEWRPG = PORTB & 0b00000011. // Clear for "no change" return value PORTBbits. and 0 for no change. // Read PORTB PORTBbits.Section 10. // Power up RPG pullup resistors Nop(). // Save present RPG state for next loop } (b) The function. // CCW change } else { DELRPG = +1. // CW change } } OLDRPG = NEWRPG.RB3 = 1. then: 00 → 10 10 → 11 11 → 01 01 → 00 . Nop(). OLDRPG = PORTB & 0b00000011.4 The RPG Function 137 PORTBbits.RB3 = 0. If the RPG is changed in a CCW direction. // // // // Power up RPG pullup resistors Wait a microsecond Load OLDRPG for RPG Power down RPG (a) Initial function additions /******************************* * RPG * * This function generates DELRPG = +1 for a CW increment of the RPG.RB3 = 0.RB3 = 1. FIGURE 10-3 RPG function Note that in every case the MSb (most-significant bit) of the new number is the same as the LSb of the old number. PORTBbits. // Power down RPG if (NEWRPG != OLDRPG) // Any change? { if (0b00000010 & (NEWRPG ^ (OLDRPG << 1))) // CW or CCW? { DELRPG = -1. ******************************* */ void RPG() { DELRPG = 0. * -1 for a CCW increment. to increment or decrement RPGNUM and to display it on the two rightmost characters of the LCD. The RPGcounter function of Figure 10-4 uses the RPG output. // Units digit LCDFLAG = 1. • Mask off all but bit 1 to obtain a nonzero value for a CCW change and a zero value for a CW change. ******************************* */ void RPGcounter() { RPGNUM += DELRPG. // Tens digit LCDSTRING[7] = '0' + (RPGNUM % 10). } else if (RPGNUM < 0) { RPGNUM = 99. * RPGNUM. // Set flag to display } (b) The function. two issues arise: RPGNUM = 0. DELRPG. RPGNUM is then displayed in LCDSTRING[6] and LCDSTRING[7].c) In every case the MSb of the new number is the complement of the LSb of the old number. // Update counter if RPG has been turned if (RPGNUM > 99) { RPGNUM = 0. 10. This information forms the basis for the test. } LCDSTRING[6] = '0' + (RPGNUM / 10). • Exclusive-OR the resulting shifted value in OLDRPG with NEWRPG.138 Chapter 10 Rotary Pulse Generator (RPG. The value of DELRPG is set accordingly. namely: • Shift OLDRPG left so that its bit 0 is moved to the bit 1 position. // Initialize to 0 (a) Initial function addition /******************************* * RPGcounter * * This function uses DELRPG to increment/decrement the signed char variable.5 THE DETENTED RPG When the same technique used for the Bourns RPG is applied to the detented ALPS RPG of Figure 10-1. FIGURE 10-4 RPGcounter function . In response to each interrupt. resolves these two issues. The interrupt approach of Figure 3-2. 3.g. RPG. to determine the direction of change. either a rising edge or a falling edge always occurs on the INT2 input. then an interrupt will occur in response to a falling edge into INT2. This match or mismatch condition is used by the high-priority interrupt service routine of Figure 10-6b.Section 10. repeated in Figure 10-5a. A complete. the pull-up resistor on the output that goes to the MCU’s interrupt pin must be continuously pulled high. Note . Thus RPGNUM simply accumulates all the increments and decrements of DELRPG into a value that is converted to a two-digit ASCII representation. every edge into INT2 will produce an interrupt. the RE2 pin that powers the pull-up resistor for the interrupt input produces a quiescent current draw of only 3 µA when the RPG outputs are at the “00” position (and 0 µA otherwise). Because more than one increment or decrement of DELRPG may take place during a 10-ms looptime. the two pins must use a shorter interval between samples (e. resulting in a continuous current draw when the RPG is left standing in state 00. Note that in going from one detented position to the next. • The 1-MΩ pull-up resistor on the INT2 interrupt input coupled with the associated low stray capacitance filters out the effect of contact bounce.. It increments a negative value of DELRPG toward zero while at the same time decrementing RPGNUM. for this CCW direction of motion. Consider the CCW rotation shown in Figure 10-5b. as shown in Figure 10-5c.5 The Detented RPG 139 • The output representing a change occurs only at each detented position when the two pins are either in state 00 or state 11. Furthermore.333 ms) to read each state reliably during the transition from one detented position to the next. is listed in Figure 10-7. use is made of an INTEDG2 control bit that determines whether the INT2 input will be sensitive to a rising or a falling edge: • If INTEDG2 = 1. The LCD is updated by setting LCDFLAG only when the RPG is turned. For this approach. CW rotation produces a mismatch between INTEDG2 and RE1. To determine the direction of rotation of the RPG. • If INTEDG2 = 0. then an interrupt will occur in response to a rising edge into INT2. On the other hand. the state of INTEDG2 at the time of the INT2 interrupt always matches the state of the RE1 input read from the other RPG output. But the transition state of 01 or 10 must also be read.c. INTEDG2 is toggled. The RPGcounter function of Figure 10-6c decrements a positive value of DELRPG toward zero while at the same time incrementing RPGNUM. • Because the detent mechanism inserts a snap into the movement. the HPISR may increment or decrement DELRPG more than once in that interval. Using a 1-MΩ pull-up resistor has two beneficial effects: • For an application that uses the RPG. Consequently. It includes the modification of the Initial function to handle the RPG shown in Figure 10-6a. testable source file. 140 Chapter 10 Rotary Pulse Generator (RPG.6 kΩ RE1 Detented RPG (a) RPG connections CCW direction of motion INT2 INTEDG2 Value = RE1 Value = RE1 Detented positions (b) CCW motion for which INTEDG2 = = RE1 at time of interrupt CW direction of motion INT2 INTEDG2 Value = RE1 Value = RE1 Detented positions (c) CW motion for which INTEDG2 != RE1 at time of interrupt 0 1 1 0 0 1 1 0 1 1 0 0 1 1 0 0 FIGURE 10-5 Determining the direction of rotation at the time of each interrupt that after RE2 of PORTE is set to power the 1-MΩ pull-up resistor for the interrupt input from the RPG. Unlike other inputs that can be read with only a microsecond pause after the associated pull-up resistor has been powered up.c) MCU RE2 1 MΩ RB2/INT2 or RE0 22. the . a 100-µs delay is inserted before RB2/INT2 is read and used to initialize INTEDG2 appropriately. } else { --DELRPG.INT2IF = 0. * DELRPG is returned to zero. // and initial RPG position of 00 LCDFLAG = 1.Section 10. // Enable INT2 interrupt source INTCON3bits. } PORTEbits. // Clear interrupt flag DELRPG = 0. FIGURE 10-6 Program code for detented RPG .RE0 = 1.INT2IP = 1. // Reset interrupt flag if (PORTEbits.RB2.5 The Detented RPG 141 PORTEbits.RE1 == INTCON2bits. // Toggle edge sensitivity } (b) High-priority interrupt service routine /******************************* * RPGcounter * * This function uses DELRPG to update the signed char variable. // Display initial 00 value (a) Initial function additions /******************************* * HiPriISR * * Respond to rising and falling edges on INT2 input from RPG. // Use INT2 for high-priority interrrupts INTCON3bits.INTEDG2 = !PORTBbits. // Power down pullup resistor INTCON2bits.RE0 = 0. // Power pullup resistor to read direction INTCON3bits. // Indicate no initial edge RPGNUM = 0. // Pause for 100 us INTCON2bits.INTEDG2 ^= 1. RPGNUM.INTEDG2) // Direction? { ++DELRPG. // Power up the pullup for the RPG's interrupt Delay(10). * LCDSTRING[6] and LCDSTRING[7] display RPGNUM. ******************************* */ void HiPriISR() { PORTEbits. ******************************* */ void RPGcounter() { while (DELRPG > 0) { --DELRPG.INT2IE = 1.INT2IF = 0. // Select initial interrupt edge INTCON3bits.RE2 = 1. FIGURE 10-6 (continued) /******* RPG. } TEMPCHAR = RPGNUM. // Set flag to display } while (DELRPG < 0) { ++DELRPG. * RPGcounter increments/decrements a two-digit number from DELRPG. * LED on RD4 is blinked for 10 ms every four seconds.c) if (++RPGNUM > 99) // Increment RPGNUM. if (--RPGNUM < 0) // Decrement RPGNUM. * Timer1 is clocked by the Timer1 crystal oscillator. modulo 100 { RPGNUM -= 100. LCDSTRING[7] = '0' + TEMPCHAR % 10. LCDFLAG = 1.142 Chapter 10 Rotary Pulse Generator (RPG. * with LED and LCD switched off) * ******* Program hierarchy ***** * * main * Initial * BlinkAlive * RPGcounter * UpdateLCD * Display FIGURE 10-7 RPG.c . * * Current draw = 16 or 19 uA (depending on RPG position. * LoopTime function puts chip to sleep. CPU adjusts Timer1 content for it to timeout * after another 10 milliseconds. * INT2 edges from RPG produce high-priority interrupts and inc/dec DELRPG. * RC2 output is toggled every 10 milliseconds for measuring looptime. LCDSTRING[6] = '0' + TEMPCHAR / 10. LCDFLAG = 1. // Set flag to display } } (c) RPGcounter function called from main. modulo 100 { RPGNUM += 100. Timer1 awakens chip every 10 ms * within LoopTime function. } TEMPCHAR = RPGNUM. LCDSTRING[6] = '0' + TEMPCHAR / 10. LCDSTRING[7] = '0' + TEMPCHAR % 10.c ************* * * Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz. // unsigned int DELAY. // Ongoing display string (9 characters) /******************************* * Function prototypes ******************************* */ void Initial(void). // signed char RPGNUM. // unsigned char i. set when LP interrupt has been handled Index into strings Sixteen-bit counter for obtaining a delay Scale-of-400 counter for blinking "Alive" LED RPG output For display of RPG position Temporary signed character 00 " ******************************* */ char LCDFLAG. FIGURE 10-7 (continued) . // unsigned int ALIVECNT. nominal Deselect low-power Timer1 oscillator Flag. // char LPISRFLAG. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. // signed char DELRPG. // signed char TEMPCHAR. RA6=Fosc/4.Section 10. // /******************************* * Variable strings ******************************* */ char LCDSTRING[] = " Use internal osc. set to send string to display Flag.0V.5 The Detented RPG 143 * LoopTime * * HiPriISR * * LoPriISR * ******************************* */ #include <p18f4321. 144 Chapter 10 Rotary Pulse Generator (RPG. Display(void). ******************************* */ void HiPriISR() { PORTEbits. // Power pullup resistor to read direction INTCON3bits. /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x. while(--DELAY){ Nop().RE0 = 1. } FIGURE 10-7 (continued) . LoopTime(void).c) void void void void void void void BlinkAlive(void). LoPriISR(void). // Reset interrupt flag if (PORTEbits.INT2IF = 0. RPGcounter(void). UpdateLCD(void).INTEDG2) // Direction? { ++DELRPG. HiPriISR(void). Nop(). } /******************************* * /******************************* * HiPriISR * * Respond to rising and falling edges on INT2 input from RPG.RE1 == INTCON2bits. for measuring loop time Blink "Alive" LED Update LCD Use Timer1 to wakeup and loop again /******************************* * Initial * * This function performs all initializations of variables and registers. } PORTEbits. // PIR1bits. // T1CONbits.INTEDG2 ^= 1. // } } Initialize everything Toggle pin.5 The Detented RPG 145 else { --DELRPG.TMR1ON = 0.Section 10.TMR1IF = 0.TMR1ON = 1. // LoopTime(). // TMR1H = 0xFE.RE0 = 0. // BlinkAlive(). // } Pause Timer1 counter Cut out all but 328 counts of Timer1 Resume Timer1 counter Upper byte of Timer1 will be 0xFE Clear interrupt flag Set a flag for LoopTime /////// Main program ////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). ******************************* */ FIGURE 10-7 (continued) .RC2 ^= 1. // LPISRFLAG = 1. } // Power down pullup resistor // Toggle edge sensitivity /******************************* * LoPriISR * * Control 10 ms looptime ******************************* */ void LoPriISR() { T1CONbits. // RPGcounter(). // while (1) { PORTCbits. // TMR1L += 0xB9. UpdateLCD(). INTCON2bits. PORTC = 0. INTCONbits.RA2.INTEDG2 = !PORTBbits. others digital Set I/O for PORTA Set I/O for PORTB Set I/O for PORTC Set I/O for PORTD Set I/O for PORTE Set initial state for all outputs low // except RD5 that drives LCD interrupt // // // // // // // // // // // Flag to signal LCD update is initially off Blink immediately Send a blank to initialize state of SPI Pause for half a second Now disable brown-out reset Timer1 .INT2IP = 1. PORTD = 0b00100000. // Clear interrupt flag DELRPG = 0. TRISE = 0b00000010. ALIVECNT = 300. INTCONbits.146 Chapter 10 Rotary Pulse Generator (RPG. // Use INT2 for high-priority interrrupts INTCON3bits. LPISRFLAG = 0. LCDFLAG = 0. PORTE = 0. SSPCON1 = 0b00110000. Delay(50000). // Indicate no initial edge RPGNUM = 0. // Display initial 00 value RCONbits.RA1.IPEN = 1. T1CON = 0b01001111. SSPSTAT = 0b00000000. * With a looptime of about 10 ms. TRISC = 0b10000000. SSPBUF = ' '. TRISD = 0b10000000. PORTB = 0.TMR1IP = 0. // Select initial interrupt edge INTCON3bits. // Enable INT2 interrupt source INTCON3bits.GIEL = 1. PIE1bits.GIEH = 1. ******************************* */ // Enable high/low priority interrupt feature // Global low-priority interrupt enable // Enable both high and low interrupts FIGURE 10-7 (continued) . // Power up the pullup for the RPG's interrupt Delay(10).TMR1IE = 1.INT2IE = 1.c) void Initial() { OSCCON = 0b01100010. // and initial RPG position of 00 LCDFLAG = 1.loop time via low-pri interrupts Set Timer1 to be 10 ms away from next roll over (65536 + 1 .RB2. count 400 looptimes.INT2IF = 0. } /******************************* * BlinkAlive * * This function briefly blinks the LED every four seconds. PORTA = 0. RCONbits. // Pause for 100 us INTCON2bits. IPR1bits. TRISB = 0b01000100. // Use Fosc = 4 MHz (Fcpu = 1 MHz) // Set up SPI for output to LCD // // // // // // // RA0. TMR1H = 0xFE.328 = 0xFEB9) Enable local interrupt source Use Timer1 for low-priority interrupts Flag to signal that LPISR has been executed PORTEbits. ADCON1 = 0b00001011. TMR1L = 0xB9.SBOREN = 0.RE2 = 1.RA3 pins analog. TRISA = 0b00001111. if (++ALIVECNT == 400) { ALIVECNT = 0.RD4 = 0. } TEMPCHAR = RPGNUM.Section 10. modulo 100 { RPGNUM -= 100.5 The Detented RPG 147 void BlinkAlive() { PORTDbits. ******************************* */ void RPGcounter() { while (DELRPG > 0) { --DELRPG. if (--RPGNUM < 0) // Decrement RPGNUM. // Set flag to display } while (DELRPG < 0) { ++DELRPG. LCDSTRING[6] = '0' + TEMPCHAR / 10. LCDSTRING[6] = '0' + TEMPCHAR / 10. } } // Turn off LED // Increment counter and return if not 400 // Reset ALIVECNT // Turn on LED for one looptime /******************************* * RPGcounter * * This function uses DELRPG to update the signed char variable. * LCDSTRING[6] and LCDSTRING[7] display RPGNUM. } TEMPCHAR = RPGNUM. modulo 100 { RPGNUM += 100. * DELRPG is returned to zero. LCDSTRING[7] = '0' + TEMPCHAR % 10. RPGNUM. LCDFLAG = 1. LCDSTRING[7] = '0' + TEMPCHAR % 10. ******************************* */ FIGURE 10-7 (continued) . PORTDbits. // Set flag to display } } /******************************* * UpdateLCD * * This function updates the 8-character LCD if the LCDFLAG is set. if (++RPGNUM > 99) // Increment RPGNUM.RD4 = 1. LCDFLAG = 1. RD5 = 1. // Send byte while (!PIR1bits. // Wake up LCD display for (i = 0. // Return RB5 high. ******************************* */ void Display() { PORTDbits. // Sleep upon next entry to LoopTime } FIGURE 10-7 (continued) RB2/INT2 pin exhibits a 75-µs rise time after RE2 is raised to 3 V when the RPG is in the “11” position. // Wait for transmission to complete } PORTDbits. ready for next string } /******************************* * LoopTime * * This function puts the chip to sleep upon entry.SSPIF = 0. Since RE2 will be left high thereafter.148 Chapter 10 Rotary Pulse Generator (RPG. // which sets LPISRFLAG Nop(). this 75-µs rise time occurs every time the RPG is changed from its “00” position to its “11” position. i < 9. i++) { PIR1bits.SSPIF). // Clear SPI flag SSPBUF = LCDSTRING[i]. Sleep(). } } /******************************* * Display * * This function sends LCDSTRING to the LCD. * It wakes up and executes a HPISR and then returns to sleep. The long rise time is what damps out any contact-bounce “chatter” when the RPG is changed from its “11” position to . } LPISRFLAG = 0. * It wakes up and executes a LPISR and then exits. ******************************* */ void LoopTime() { while (!LPISRFLAG) // Sleep upon entry and upon exit from HPISR { // Return only if LPISR has been executed. LCDFLAG = 0.c) void UpdateLCD() { if (LCDFLAG) { Display().RD5 = 0. 10-2 Polled RPG. Because the 1-MΩ pull-up resistor on the RB2 input produces such a long response time.c file derived from the RPG. . The INT2 input is not affected by the slow rise time. It also subjects the input to hysteresis. determine the maximum loop time for which RPG clicks (almost always) produce increments or decrements on the LCD. with one increment of the displayed value for each detented click of the knob. inasmuch as the signal on the input pin is subjected to a Schmitt trigger before being passed along to the interrupt circuitry. The Schmitt trigger converts its slowly rising input to a fast snap of a change on its output.c file of Figure 10-7 by removing the high-priority ISR and adding the RPG function of Part (a). Each time DELRPG causes an increment or decrement of RPGNUM in the old RPGcounter function. c) Read an 8-bit value from the pot every 20th time around the main loop. either slowly or at a faster (but “normal”) rate. d) As the RPG is turned.c’s Time function in Figure 5-5 for ideas. The result is an RPG whose performance matches the ideal. Refer to T2.c a) Modify the RPG function of Figure 10-3 to poll the two outputs of the detented RPG of Figure 10-5a. called from the main loop. This hysteresis also mitigates the effect of any contactbounce chatter. now increment or decrement the ASCII-coded value in RPGTENS and RPGONES appropriately. Also replace the RPGcounter function with that of Figure 10-3. PROBLEMS 10-1 RPGcounter modification a) Modify the RPGcounter function of Figure 10-4 and its initialization to use two variables RPGTENS and RPGONES in place of RPGNUM.5 The Detented RPG 149 its “00” position. initialize RE2 high and leave it high. Measure the time between edges of RC2 to determine this loop time. having a slightly higher rising-voltage threshold at which the output snaps than its falling-voltage threshold at which the output snaps back. b) Repeat for the RPGcounter function of Figure 10-6.Section 10. Use this to modify the loop time proportional to the pot value and from (about) 1 ms if the pot is fully CCW and (about) 10 ms if the pot is fully CW. b) Write a PolledRPG. the monitoring of both code size and execution time will be discussed.2 CODE SIZE Alex Singh’s C18 utility: • Compiles and links a source file. the size of the resulting program is not a dominating issue.1 OVERVIEW Coding a microcontroller application in C has benefits and drawbacks. C coding provides little insight into either issue. The faster execution of an algorithm leads directly to more sleep time (with the MCU drawing less than 2 µA) and less awake time (with the MCU drawing more than 1 mA).Chapter 11 MEASUREMENTS 11. From such a comparison. listed in Section 2. 11. • Shows the percentage of available program memory used. The speed of execution of algorithms is another story. • Lists the number of program bytes. 150 . given the weight placed on coin cell current draw and the resulting effect on coin cell life. coding choices can be made intelligently. As mentioned there. as long as it fits in the available program memory within the target microcontroller. Being able to monitor code size and execution time allows the comparison of alternative codings of an algorithm. In this chapter.9. This latter implementation uses the same technique of incrementing or decrementing an ASCII-coded two-digit number as was used in the Pushbutton function of the T2. this gross view of the code generated provides helpful insight. FIGURE 11-1 Two implementations of RPGcounter . * LCDSTRING[6] and LCDSTRING[7] display count. and reinitializations.c template program (Figure 5-5). it is more complicated to write and more difficult for someone else to understand. This example illustrates several points: • While the implementation of Figure 11-1b uses slightly less memory than the implementation of Figure 11-1a. These are significant considerations. The program containing the code of Figure 11-1a generates 22 more bytes of code than the identical program with only the RPGcounter function replaced by the code of Figure 11-1b. compares. Solution Compiling the two source files containing the two versions of the RPGcounter produces program byte counts for each file. • /******************************* * RPGcounter * * This function uses DELRPG to update the signed char variable. RPGNUM. The formation of LCDSTRING[7] has the compiler calling the same subroutine with the same divisor and dividend to form the (previously discarded) remainder.Section 11. the formation of LCDSTRING[6] incurs the call of a divide subroutine. ******************************* */ void RPGcounter() { while (DELRPG > 0) { --DELRPG. The algorithm of Figure 11-1b replaces these divides with increments. decrements. In the implementation of Figure 11-1a. Example 11-1 Compare the amount of code generated by Figure 11-1a with the amount of code generated by the alternative implementation of the same function shown in Figure 11-1b. The amount of code generated does not correlate well with the number of lines in the source file. * DELRPG is returned to zero.2 Code Size 151 In an environment where the C compiler may need to insert complex subroutines to implement a few lines of seemingly simple source code. if (++RPGUNITS > '9') { RPGUNITS = '0'. } // Set flag to display while (DELRPG < 0) { ++DELRPG. if (--RPGNUM < 0) { RPGNUM += 100. } } LCDFLAG = 1. * LCDSTRING[6] and LCDSTRING[7] display count. } LCDFLAG = 1. if (++RPGTENS > '9') { RPGTENS = '0'. LCDSTRING[6] = '0' + (TEMPCHAR / 10). // Set flag to display } TEMPCHAR = RPGNUM. FIGURE 11-1 (continued) . ******************************* */ void RPGcounter() { while (DELRPG > 0) { --DELRPG. } LCDFLAG = 1. LCDSTRING[7] = '0' + (TEMPCHAR % 10). } (a) Implementation of RPGcounter using two divide operations /******************************* * RPGcounter * * This function uses DELRPG to update ASCII-coded RPGTENS:RPGUNITS * DELRPG is returned to zero. // Set flag to display } while (DELRPG < 0) { ++DELRPG.152 Chapter 11 Measurements if (++RPGNUM > 99) { RPGNUM -= 100. } } LCDFLAG = 1. By disabling interrupts before the pulse on RB0 is initiated and reenabling interrupts after the pulse has been completed. if (--RPGTENS < '0') { RPGTENS = '9'. If the RB0 pin is used for this purpose. Solution The two lines are preceded by a Disable() macro to postpone interrupts and a Start() macro to set the RB0 pin. // Update display string FIGURE 11-1 (continued) 11. If the code for which a time interval is to be measured resides in the main code. Example 11-2 Assume that TEMPCHAR contains a number ranging between 0 and 99 and is to be displayed as a two-digit number on the LCD display. Determine the time taken to form LCDSTRING[6] and LCDSTRING[7] in Figure 11-2b. it will occasionally be interrupted if one or more high-priority interrupt sources are being employed. any intervening interrupts will not be lost.3 Code Execution 153 if (--RPGUNITS < '0') { RPGUNITS = '9'. The lines are followed by a Stop() macro and an Enable() macro to produce a pulse on the RB0 pin of 210 µs. } (b) Implementation of RPGcounter incrementing ASCII-coded RPGTENS:RPGUNITS. the user program can be modified to set a pin prior to the execution of the code segment whose duration is to be measured and to clear the pin on its completion. only delayed until the completion of the RB0 pulse. // Set flag to display } LCDSTRING[6] = RPGTENS.3 CODE EXECUTION Using an oscilloscope to measure time intervals. Subtracting the 1-µs interval that is produced if Start() is immediately followed by Stop() yields an execution time of 209 µs for the two lines that form the two LCDSTRING bytes. its use will be simplified by the addition of the macro definitions shown in Figure 11-2a. LCDSTRING[7] = RPGUNITS. .Section 11. Disable().4 VARIABLE CODE EXECUTION If the code segment whose execution time is being measured varies.154 Chapter 11 Measurements /******************************* * Macro definitions ******************************* */ #define Disable() INTCONbits. FIGURE 11-3 Use of oscilloscope’s “persist” mode . as illustrated in Figure 11-3. a casual estimate of the mean pulse width is also easily obtained. LCDSTRING[1] = '0' + (TEMPCHAR % 10). LCDSTRING[0] = '0' + (TEMPCHAR / 10).RB0 = 1 #define Stop() PORTBbits.GIE = 0 #define Start() PORTBbits. both the minimum pulse width and maximum pulse width are easily ascertained. an oscilloscope’s “persist” or “autostore” mode will overwrite the display with each successive trace. FIGURE 11-2 Execution time determination 11.GIE = 1 (a) Definition of Start() and Stop() macros.RB0 = 0 #define Enable() INTCONbits. Stop(). Execution time = 210 − 1 = 209 µs. Enable(). Start(). Taking advantage of the brightness of the range of falling edges. (b) Formation of two ASCII-coded digits. Using the scope’s time cursors. When the program is executed and the pulse displayed in the “persist” mode. but no more than one. /******************************* * HiPriISR * * Measure time CPU digresses from main to execute this minimal HPISR. the display of Figure 11-4c is produced. where the trigger point on the rising edge of the pulse has been moved about 1 ms off to the left of the screen. Example 11-3 Determine the minimum time overhead of a high-priority interrupt. The HPISR of Figure 7-6 has been reduced. After sufficient time to have at least one interrupt occur concurrently with a pulse. vectored to the HPISR. in Figure 11-4b. . // Clear interrupt flag } (b) A minimal high-priority interrupt service routine. ******************************* */ void HiPriISR() { PIR2bits. Start(). the display of Figure 11-4c will result. This will produce a pulse that will be interrupted zero or one time.TMR3IF = 0. FIGURE 11-4 Determining the minimum time overhead of a high-priority interrupt service routine. Then set the delay parameter to something less than one-tenth of this number of microseconds. executed the one flag-clearing instruction (taking 1 µs to do so).Section 11. Delay(100).5 INTERRUPT TIMING MEASUREMENT Measuring how long the CPU digresses from its main function in response to an interrupt request can take advantage of the Delay macro of Section 4. the pulse width will be extended by the exact time of digression for the CPU to deal with the interrupt. restored the selected CPU registers. Solution Add the code of Figure 11-4a to the main function.5 Interrupt Timing Measurement 155 11. // Pause for 1 ms (a) One-millisecond pause in main loop. When an interrupt occurs. Stop().7. to do nothing more than clear the interrupt flag. and returned to where it left off in the main code. The difference between the two falling edges of 15 µs indicates that the CPU digressed for 15 µs as it set aside the program counter and other selected CPU registers. First determine the minimum time between successive interrupts. The oscilloscope’s “persist” mode again helps to identify a reasonable average for TUSEFUL WORK. In this way. the time taken to do useful work can be monitored. Generally. even when that value rarely occurs.6 TIME SPENT DOING USEFUL WORK IN MAIN LOOP By inserting the Start() macro at the beginning of the main loop and the Stop() macro just before the call of the LoopTime function.000 (µS) where 10.7 CLEANING UP SURPRISES When the average current draw is higher than expected. it is valuable to know the average of this time since it leads to the average current draw from the coin cell: TUSEFUL WORK (µS) Average current draw = _________________ × 1 mA 10. It also permits the measurement of the worst-case value. some time will be spent in functions called from main and some time within intervening interrupts.000 µs is the loop time. the use of the Start() and Stop() macros provides an easy way to close in on the source of the problem. A long-duration function at that level leads to the functions it calls. 11. Each time around the main loop. The execution time of questionable functions in the main loop becomes a good place to start. one or .156 Chapter 11 Measurements (c) Scope’s screen dump FIGURE 11-4 (continued) 11. and (from Figure 2-4) 1 mA represents the current draw when the chip is clocked continuously with FOSC = 4 MHz. First.c template of Figure 7-6. • An interrupt service routine that occurs many times per 10-ms loop time also carries out an extensive routine to handle each occurrence. PROBLEMS 11-1 Function size Consider the T3.c template program by rewriting the Pushbutton function of Figure 7-6 using a new signed char variable. it does not.c of Problem 11-1. Then form a T3A. 11-2 Function size Form a T3B. Use the code of Figure 11-1a as a model for how to use PBNUM. The difference between these two numbers is the number of bytes sought.c template with /* inserted before the line void Pushbutton() and a */ after the function’s final }. . when. As once pointed out to the author. PBNUM. a) Compare the number of program bytes generated by T3B. “paper never protests”.7 Cleaning up Surprises 157 more offending functions can be identified.Section 11. for which the Pushbutton code was commented out. Then recompile and note the reduced number of program bytes generated. to represent the number of pushbutton pushes. whereas looking at a long source file is a difficult method of debugging. Some of the issues that can arise are: • A function may calculate a value using long-duration multiplies and divides each time around the main loop while the value is used to update the display only once every 10 loop times. it might accumulate successive changes in a variable and then let a main function handle the accumulated change each loop time before resetting the variable. LCDSTRING[1] = '0' + (TEMPCHAR % 10). Determine the number of program bytes generated by the Pushbutton function.c with the number found for T3A. LCDSTRING[0] = '0' + (TEMPCHAR / 10). It is difficult to discern this from the source file. Instead. including the final three lines of code TEMPCHAR = PBNUM. It is easy to discern it by the measurement of the alternatives. Time is not spent looking for alternatives to code that only looked like it might produce a long execution time. compile the code as is and note the number of program bytes generated. • Alternative implementations of a function may yield quite different execution times. in fact. Testing makes all the difference. Recompile and measure the execution time of the Pushbutton function.158 Chapter 11 Measurements 11-3 Execution time a) In the main function of T3.c. insert the Disable and Start macros before Pushbutton(). . What is the value when the pushbutton is not pressed? What is the value when the number changes from 2 to 3? From 9 to 10? b) Repeat for T3B.c. and the Stop and Enable macros after it. the code was inserted into the source file to have the compiler handle the two interrupt vectors to HiPriISR and LoPriISR.2 MCU INTERRUPT RESPONSE Chapter Seven introduced the use of both high. Stepping the stepper motor with a step period other than some multiple of the loop time represents a common interrupt application. The remainder of the chapter identifies the control and status bits associated with every interrupt source in the PIC18LF4321. the interrupt service routines. HiPriISR and 159 . The first part of this chapter pinpoints this issue. How interrupt service routines are written in C has a profound effect on both execution time and program size.Chapter 12 INTERRUPTS 12. Then. First.and low-priority interrupts. 12.1 OVERVIEW Interrupts provide a way for the CPU to break out of the lockstep sequence of tasks dictated by the function calls in the main loop. Sensing RPG motion only when the RPG generates edges represents another. It is this overhead that can be drastically influenced by how the code is written. For a highpriority interrupt. were written and added to the source file just like any other function.com web site). 7. the two lines of code to reload a timer and clear an interrupt flag compile to three machine code instructions that execute in 3 µs. 8. 3. The code of Figure 12-1a is taken from a file called IntProg1. For testing purposes. Reenables the interrupt level (high or low) that was disabled in Step 2. This knowledge will be used to translate from the total time that the CPU takes to deal with an interrupt to the portion of that time that represents overhead. Restores the CPU registers set aside in Step 4. the CPU: 1.qwikandlow. and run. might corrupt the execution of the interrupted main program.160 Chapter 12 Interrupts LoPriISR. and therefore whether or not it generates interrupts. Timer1 and Timer3 have been set up to be clocked by the CPU’s 1-MHz clock (rather than the Timer1 oscillator) so that interrupts will be synchronized to the CPU clock. further low-priority interrupts are disabled. The trailing edge of this pulse is extended whenever an interrupt strikes during the pulse. 4. Returns to the main program at the point where execution was suspended in Step 1. Within each interrupt service routine of Figure 12-1c. The amount of the extension equals the ISR overhead plus . 2. 12.c (available from the www. all interrupts are disabled. When an interrupt of main program execution occurs.3 COMPILER HANDLING OF INTERRUPTS In this section. As each is compiled. For a low-priority interrupt. 5. Suspends its main program execution. The two ways of expressing the interrupt service routines (Figure 12-1c on the one hand and Figure 12-1d on the other) plus the disabling of one interrupt source or the other via the lines of Figure 12-1b allow four experiments to be run. if changed by the execution of the interrupt service routine. Snippets from several source file examples will be examined. the Initial function includes the two lines shown in Figure 12-1b that control whether or not either timer runs. Executes the interrupt service routine. The intent is to discern how the writing of the code of Step 5 impacts what the compiler does with Steps 4 and 6. Copies any CPU registers that. The reorganization of each interrupt service routine in Figure 12-1d breaks out these same two lines to reload a timer and clear an interrupt flag into two separate “handler” functions. downloaded. 6. It shows a main function that uses the Delay macro to generate a 140-µs pulse on the RC2 output pin every 140 µs + 200 µs = 340 µs. the extra code introduced by the compiler for Steps 4 and 6 will be examined. the 140-µs pulse generated by the main loop of Figure 12-1a is monitored. but any high-priority interrupts that have been enabled are left enabled. Vectors to the interrupt service routine. while (1) { PORTCbits.Section 12. // PIE1bits. PIR1bits. Delay(14).RC2 = 1. PORTCbits. and return. ******************************* */ void HiPriISR() { TMR3H = 0xFF. // Clear interrupt flag } /******************************* * LoPriISR * * Reload TMR1H.com) FIGURE 12-1 Snippets from IntProg1.c in www. } } // Initialize everything // // // // Set pin high Pause for 140 microseconds Set pin low Pause for 200 microseconds (a) Setup to measure the digression from a constant duration pulse by an interrupt. // Enable local interrupt source // Enable local interrupt source (b) Lines from Initial function. PIR2bits.RC2 = 0. and return.qwikandlow. for enabling only one interrupt source at a time. /******************************* * HiPriISR * * Reload TMR3H. PIE2bits.c .TMR3IE = 1.3 Compiler Handling of Interrupts 161 void main() { Initial().TMR1IF = 0. // Clear interrupt flag } (c) One way of writing ISRs (from IntProg1.c and IntProg2. Delay(20).TMR3IF = 0. ******************************* */ void LoPriISR() { TMR1H = 0xFF. clear flag.TMR1IE = 1. clear flag. } /******************************* * Timer3Handler ******************************* */ void Timer3Handler() { TMR3H = 0xFE.qwikandlow. The results of all four experiments are summarized in this table of Figure 12-2. The 10 µs less taken by the HiPriISR to do the same thing occurs because the high-priority ISR automatically and quickly copies three CPU registers into three shadow registers on entry and quickly restores them on exit..c in www. FIGURE 12-1 (continued) the 3 µs to reload the timer and clear the flag.TMR1IF = 0. Thus.com).162 Chapter 12 Interrupts /******************************* * HiPriISR ******************************* */ void HiPriISR() { Timer3Handler(). The ISR overhead of 11 µs (i. } /******************************* * LoPriISR ******************************* */ void LoPriISR() { Timer1Handler(). // Clear interrupt flag } /******************************* * Timer1Handler ******************************* */ void Timer1Handler() { TMR1H = 0xFE. the 140-µs pulse is extended 14 µs by an intervening interrupt. 14 µs − 3 µs) is listed in the top line of Figure 12-2.TMR3IF = 0. when the code of Figure 12-1c is executed with only Timer3 producing high-priority interrupts. The low-priority ISR must also set aside and later restore these same . // Clear interrupt flag } (d) Another way of writing ISRs (from IntProg2. // Reload Timer3 PIR2bits. // Reload Timer1 PIR1bits. The second line shows an ISR overhead of 21 µs.e. Each of three interrupt sources makes use of the same high-priority interrupt service routine. Such an application assumes that no interrupt service routine excessively delays the handling of other interrupt sources.000 steps/s. When this code is executed. evidently the C compiler loses track of what registers the service routine will be using. This delay requirement is referred to as the acceptable worst-case latency of an interrupt source. As shown in the third and fourth lines of Figure 12-2. are broken out to a separate “handler” function as in Figure 12-1d. but there is no automatic. Timer3 is interrupting every millisecond. It is the time beyond which the interrupt source may experience performance degradation.4 USING ONE PRIORITY LEVEL ONLY Given the performance perspective of Figure 12-2. each interrupt causes the CPU to digress from its execution of the main function with an ISR overhead of 19 µs. then at this maximum rate. . it may make sense for many applications to use just one interrupt priority level. Even if two other interrupts line up to be serviced first. their presumably short handlers are not going to insert enough of an irregularity in the timing of the steps to throw the motor out of its fast coasting rhythm. Rather. A snippet of code from an IntProg3. For example. This extra code evidently sets aside and restores every conceivable CPU register and compiler-generated variable that might ever be corrupted by an interrupt service routine. it also adds 88 µs to the interrupt service routine’s execution time. Within HiPriISR. its handler is executed in line (without breaking out to a separate handler function and invoking the performance hit discussed in the last section). If so. When the two source code lines in an interrupt service routine. Upon compiling and running and monitoring the main function’s pulse on RC2. fast mechanism to do so. These four tests provide the insight that a large performance penalty is incurred for both the program code size and execution time by delegating interrupt service routine code to a separate “handler” function. to reload the timer and clear the flag.c file is shown in Figure 12-3. if the stepper motor has a maximum stepping rate of about 1. 12.Section 12. the compiler adds instructions to do the setting aside and restoring for the low-priority interrupt service routine. each interrupt flag is polled to determine whether it is requesting service. the compiler adds 276 bytes of code. The Initial function includes the three lines shown in Figure 12-3b so that two of the three interrupts can be disabled for each of three experiments.4 Using One Priority Level Only 163 ISR overhead HiPriISR of Figure 12-1c LoPriISR of Figure 12-1c HiPriISR of Figure 12-1d LoPriISR of Figure 12-1d 11 21 = (11 + 10) 99 = (11 + 88) 109 = (21 + 88) Compiled bytes in entire file 431 707 = (431 + 276) FIGURE 12-2 Effect of interrupt service routine code writing alternatives on performance three CPU registers. c .qwikandlow. Delay(20).INT2IF) // INT2 interrupt? { INTCON3bits.com).TMR3ON = 1. PORTCbits.TMR3IF) // Timer3 interrupt? { TMR3H = 0xFE.c in www. CPU digresses for 22-3 = 19 us to handle HiPriISR for Timer3. // Enable Timer1 // Enable Timer3 // Enable INT2 interrupt source // // (b) Lines from Initial function.INT2IE = 1. /******************************* * HiPriISR ******************************* */ void HiPriISR() { if (PIR2bits. while (1) { PORTCbits.TMR1ON = 1. PIR2bits. T3CONbits. } } // Initialize everything // // // // Set pin high Pause for 140 microseconds Set pin low Pause for 200 µs (a) Setup to measure the digression from a constant duration pulse by an interrupt.TMR1IF = 0.164 Chapter 12 Interrupts void main() { Initial().INT2IF = 0. INTCON3bits. CPU digresses for 22-3 = 19 us to handle HiPriISR for Timer1. } if (INTCON3bits. Delay(14).RC2 = 0. PIR1bits. (d) Results FIGURE 12-3 Snippets from IntProg3. for disabling all but one interrupt source. Compiles to 423 bytes.RC2 = 1.TMR1IF) // Timer1 interrupt? { TMR1H = 0xFE.TMR3IF = 0. T1CONbits. CPU digresses for 20-1 = 19 us to handle HiPriISR for INT2. } } (c) A third way of writing ISRs (from IntProg3. } if (PIR1bits. the CPU will awaken and continue code execution with the code that follows the Sleep macro. as signaled by the setting of the module’s interrupt flag. and the GIEH bit of INTCON must be cleared. Figure 12-4 lists each possible interrupt source and identifies the register and bit names for the priority control bit. Each interrupt source has a local enable bit that is disabled at reset. the priority control bit must be cleared to have it responded to as a low-priority interrupt source. all local interrupt enable bits other than the one that will awaken the chip must be cleared. the MCU’s idle mode was discussed. the clocking of the CPU is halted. Consequently.7 External Interrupts 165 12.IPEN = 1. On the completion of the event. To make use of this feature of the MCU. INTCONbits. and the local flag bit.5 PIC18LF4321 INTERRUPT SOURCES The following three lines of initialization are required to enable interrupts globally: RCONbits.6 USE OF THE INTERRUPT MECHANISM + IDLE MODE In Section 2. the IDLEN bit of OSCCON must be set. 12. nothing need be done to initialize the many possible interrupt sources that go unused in any given application. An internal peripheral module event can be initiated and the Sleep mode executed.7. Meanwhile. when a Sleep macro is executed.7 EXTERNAL INTERRUPTS The detented RPG discussed in Chapter Ten made use of one of the MCU’s three external interrupt pins. each interrupt source has its own local interrupt control bits: • A priority control bit • A local enable bit • A local flag bit To have any interrupt source be given high-priority interrupt servicing.GIEH = 1.Section 12. // Enable high/low priority interrupt feature // Globally enable low-priority interrupts // Globally enable high/low interrupts In addition. stopping the execution of further instructions. the local enable bit. The bits associated with all three of these pins are described in Figure 12-5. The result is the halving of the current draw by the MCU. as indicated in Figure 2-9. . all internal peripheral modules that had been running continue to be clocked by FOSC. Then. its priority control bit must first be set. 12.GIEL = 1. Alternatively. INTCONbits. Setting the IDLEN bit in the OSCCON register enables this mode. CCP1IF PIR2bits.TMR0IF PIR1bits.HLVDIE PIE2bits.INT1IP INTCON3bits.HLVDIF PIR2bits. INTCONbits.INT0IF INTCON3bits.CCP2IP IPR1bits.TMR3IE PIE1bits.PSPIP IPR2bits.PSPIE PIE2bits.BCLIP IPR1bits.INT2IE INTCONbits.HLVDIP IPR2bits.INT2IP INTCON2bits.INT0IE INTCON3bits.OSCFIP IPR2bits.CMIP IPR2bits.TMR2IE PIE1bits.ADIF PIR1bits.TXIF PIR1bits.INT1IF INTCON3bits.SSPIF PIR2bits.TMR0IE PIE1bits.RCIP IPR1bits.EEIE Local Flag Bit INTCONbits.166 Chapter 12 Interrupts Name INT0 external interrupt INT1 external interrupt INT2 external interrupt RB port change interrupt TMR0 overflow interrupt TMR1 overflow interrupt TMR3 overflow interrupt TMR2 matches PR2 interrupt CCP1 interrupt CCP2 interrupt A/D converter interrupt USART receive interrupt USART transmit interrupt Synchronous serial port int.SSPIP IPR2bits.GIEL = 1.TMR2IP IPR1bits.CMIE PIE2bits. // Enable high/low priority mechanism // Globally enable low-priority interrupts // Globally enable high-priority interrupts (b) Global interrupt initialization FIGURE 12-5 External interrupts .EEIF Local Enable Bit INTCONbits.INT1IE INTCON3bits.BCLIF PIR1bits. INTCONbits.TXIE PIE1bits.RBIP INTCON2bits.GIEH = 1.IPEN = 1.CCP2IF PIR1bits.BCLIE PIE1bits.TXIP IPR1bits. High/low-voltage detect int. Oscillator failure int.OSCFIE PIE2bits.ADIE PIE1bits.RBIF INTCONbits.TMR1IP IPR2bits.INT2IF INTCONbits.SSPIE PIE2bits.ADIP IPR1bits.CMIF PIR2bits.TMR1IF PIR2bits.TMR1IE PIE2bits.OSCFIF PIR2bits.PSPIF PIR2bits.TMR3IF PIR1bits.EEIF * INT0 can only be used as a high-priority interrupt FIGURE 12-4 PIC18LF4321 interrupt sources INT0 input is shared with RB0 pin INT1 input is shared with RB1 pin INT2 input is shared with RB2 pin Initialize TRISB bits with 1s for interrupt or digital inputs 0s for digital outputs or unused pins (a) Initialization of PORTB pins as inputs or outputs RCONbits.CCP1IP IPR2bits. Comparator interrupt Data EEPROM write done int.TMR2IF PIR1bits. 2 Priority Bit * INTCON3bits.CCP1IE PIE2bits.RCIF PIR1bits.TMR0IP IPIR1bits.TMR3IP IPR1bits. I C bus collision interrupt Parallel slave port int.RCIE PIE1bits.RBIE INTCONbits.CCP2IE PIE1bits. test flag subsequently (d) INT1 interrupt initialization INTCON2bits. // Sense rising (1) or falling (0) edge // Local enable for INT0 interrupts // Clear flag initially.INT2IP = 1. the value read for either of these two pins set up as an input will be copied into an internal (i. A twostep process is used to reset the RBIF flag: 1. Alternatively.8 PORTB-CHANGE INTERRUPTS If either RB4 or RB5 is set up as an input.INTEDG1 = 1. It is the subsequent mismatch between an input pin and the internal copy that sets RBIF. there may be an ambiguity concerning which input changed.INT0IE = 1. INTCONbits. setting RBIF. . This flag setting can be used to generate an interrupt to the CPU if the chip is awake at the time of the change. a low-to-high change or a high-to-low change on that input will set the RBIF flag of Figure 12-4.INT0IF = 0. it can be used to awaken the chip and begin execution with the next instruction after the Sleep macro. A narrow 0 → 1 → 0 or 1 → 0 → 1 pulse that is shorter than the response time to a resulting interrupt will have trouble identifying which pin caused the interrupt (if that matters).e. Once the state of the input pin matches the state of the internal flip-flop..INTEDG2 = 1. A write to PORTB for which the bit “written” to the input pin on RB4 or RB5 matches the internal flip-flop will also satisfy this first step.INT2IE = 1.INT1IF = 0. then INTCONbits. INTCON3bits. test flag subsequently (c) INT0 interrupt initialization (high priority only) INTCON2bits. // // // // Sense rising (1) or falling (0) edge High (1) or low (0) priority selection Local enable for INT0 interrupts Clear flag initially.INT1IE = 1. test flag subsequently (e) INT2 interrupt initialization FIGURE 12-5 (continued) 12.INT1IP = 1.INT21IF = 0. INTCON3bits.INTEDG0 = 1. INTCON3bits. even if the input pin changes back to match the internal flip-flop. will clear the flag. INTCON3bits. INTCONbits. If both RB4 and RB5 are set up as inputs. // // // // Sense rising (1) or falling (0) edge High (1) or low (0) priority selection Local enable for INT0 interrupts Clear flag initially. INTCON3bits. Read PORTB so that the internal flip-flop matches the state of the input pin. 2. Once set.Section 12.RBIF = 0. RBIF remains set. INTCON3bits. When PORTB is read.8 PortB-Change Interrupts 167 INTCON2bits. inaccessible) flip-flop. RB6 and RB7 are taken over by the chip’s debug mode. features of which are used by QwikBug. 12-2 Measure HiPriISR of Figure 12-1d Repeat the procedure of Problem 12-1 for the HiPriISR of Figure 12-1d. with QwikBug installed. However. Only in the HiPriISR before it calls Timer3Handler. 12-3 Determining what affects execution time of HiPriISR Modify the code and measurement of Problem 12-2 by introducing a new char variable. compared with the measurement result for Problem 12-2 and explain any difference and what must be happening. Your main loop code should look like that of Figure 12-1a. Note that the multiply instruction employs the CPU registers PRODH and PRODL. NUMBER. Modify the duration of the Delay macros to obtain an interrupt between Start and Stop as often as not. but with the setting of RC2 replaced by the Start Function and the clearing of RC2 replaced by the Stop and Send functions. but not between Start and Stop. RB6 and RB7 can be set up as inputs to serve as two more interrupt-onchange pins. Rather. Only in the main loop. .168 Chapter 12 Interrupts Normally.c program of Chapter Six to determine how long the CPU digresses from its execution of the main loop code to deal with the HiPriISR of Figure 12-1c. Only in Timer3Handler. Consider the measurement result in each case. Your program should never stop. it should loop with timing such that one (but not more than one) interrupt is as likely as not to occur during each pass around the loop. that is multiplied by five: a) b) c) d) Only in the Initial function. PROBLEMS 12-1 Measure HiPriISR of Figure 12-1c Modify the Measure. Stop. and Send functions first used in Chapter Six are developed at the end of this chapter. 32. the time of each edge has the 1-µs resolution of the CPU clock. Because the duration is measured as the number of CPU cycles occurring between the leading and trailing edges of the pulse. The Start. compare. it is the cycle count that provides the definitive measure. the nominal 1-MHz clock. not the microseconds. Incrementing/decrementing the OSCTUNE register can then bring the actual value of FCPU close to 1 MHz.Chapter 13 TIMING MEASUREMENTS REVISITED (CALIBRATE.768-Hz Timer1 oscillator. Alternatively. For measuring the execution time of an algorithm. any time interval measurement can be scaled from timer counts to microseconds using a previously determined calibration factor. Either of the MCU’s two CCP (capture. PWM) modules can be used in conjunction with Timer3 to measure the duration of a pulse input to a CCP pin.1 OVERVIEW Chapter Eleven explored various timing measurements with the help of an oscilloscope. 169 . The duration can be calibrated as it is converted from CPU cycles to microseconds. This chapter will use Timer0 and Timer1 to calibrate FCPU. against the 50 parts per million.c) 13. Then. Because of this. Thus. The write back into the 16-bit counter takes place during the write to TMR0L in the fourth line. TMR0H = TEMPH. the 2 bytes of the counter itself are loaded simultaneously. the content of Timer0 can be updated reliably even as the counter continues to count. adding 0x0000 sets the counter back to what was in it when it was read with the first line of the code sequence listed above. a read of TMR0H does not read the upper byte of the counter itself. NUMH:NUML. or written to. . will result in somewhat less of a change in TMR0H:TMR0L than the number of counts in NUMH:NUML. TMR0L can be read. The use of Timer0 in the next section will actually start and stop the counter. consider the Timer0 use shown in Figure 13-2. With T0CON initialized as shown. buffering for Timer1 and Timer3 was not used in Chapter Seven. Timer0’s operation as a 16-bit counter of FCPU cycles is shown in Figure 13-1. Then it will be used in the next section to help calibrate FOSC. This feature simplifies the reliable reading of Timer0 without first stopping its clocking by clearing the TMR0ON bit. the addition of NUMH:NUML into TMR0H:TMR0L while it continues to run. If the timer is first stopped and then either read or loaded. the buffering does not help. Timer0 is incremented by each rising edge into the Qwik&Low board’s uncommitted RA4/T0CKI pin. Before leaving this section. (For this reason.) Consider the addition of a 16-bit number. The synchronizer delays each input edge until the time in each CPU cycle when the circuit of Figure 13-1 increments the counter. First. // Load TMR0H buffer // Update 16-bit counter Note that the read of the 16-bit counter takes place during the read of TMR0L in the first line. to Timer0. but rather the content of the upper byte of the counter at the instant that TMR0L was last read. it is an option for Timer1 and Timer3. While buffering of the upper byte is mandatory for Timer0. by the CPU reliably. Its use raises several issues that will be addressed in this section.170 Chapter 13 Timing Measurements Revisited (Calibrate.c) 13. the buffering with TMR0H makes it imperative that the bytes be read (or written to) in the order dictated by Figure 13-1.2 TIMER0 OPERATION Timer0 is a 16-bit counter. The upper byte of the counter is buffered with the TMR0H register shown. // Read 16-bit counter and add // Add with carry TEMPH = TMR0H + (NUMH + STATUSbits. The following code might be used: TEMPL = TMR0L + NUML. Even if TMR0L rolls over from 255 to 0 between the read of TMR0L and a subsequent read of TMR0H. Thus. and can actually get in the way. TMR0L = TEMPL. For example. Nevertheless. In like manner. The synchronizer assumes the edges of the input waveform occur at a slower rate than FOSC. when TMR0L is written to.C). the 16-bit value read will be the value that was in the counter at the moment TMR0L was read. TMR0H is loaded. Section 13.2 Timer0 Operation 8-bit counter Write to TMR0L Read from TMR0L TMR0H buffer register TMR0IF TMR0L 8-bit counter FCPU set TMR0ON T0CON 1: Enable counting 0: Disable counting 0 0 0 1 0 0 0 INTCON FIGURE 13-1 Timer0 use for counting FCPU (1 MHz) clock periods 171 . e.172 FOSC RA4/T0CKI Synchronizer (2TOSC delay) 8-bit counter Write to TMR0L Read from TMR0L T0CON TMR0H buffer register TMR0IF TMR0L 8-bit counter set TMR0ON 1: Enable counting 0: Disable counting 0 1 0 1 0 0 0 Chapter 13 INTCON Timing Measurements Revisited (Calibrate.c) FIGURE 13-2 Timer0 use for counting input events (i. edges) . 25 kHz source (see Figure 2-3) FIGURE 13-3 Tuning the internal oscillator Timer0 also includes a prescaler option (not shown in either figure) for dividing the counter input edges by any multiple of 2 from 2 to 256. refer to the data manual on the µs The count will be formed in an unsigned int variable. as indicated in Figure 13-3.microchip. the CPU clock can be calibrated against the 50-ppm-accurate Timer1 oscillator. If it is done again. This time interval is 256 × (1. the internal oscillator is slow. can be converted from counts to microseconds with the calculation TIME = (TIME × 7. TIME. CalSup2. The calibration procedure counts 256 increments of the Timer1 oscillator while at the same time counting Timer0 from zero as it is clocked by the CPU’s (nominal) 1-MHz clock.812.812 may make the value of a TIME measurement sufficiently accurate for a specific purpose without resorting to Equation 13-1. A subsequent time interval measurement formed in the unsigned int variable. This calibration can be done at startup. A state variable. lets each of these .000/32. is inserted at the beginning of the main loop and another. either periodically or in response to temperature change. if CALIB is less than 7. is inserted at the end. The calibration strategy suggested in this section makes use of the revised organization of program code shown in Figure 13-4.3 Internal Oscillator Calibration 173 OSCTUNE 0 − 0 1 1 1 1 • • • Maximum frequency 0 0 0 0 1 0 0 0 0 0 1 1 1 1 1 • • • Power-on default center frequency 1 0 0 0 0 Minimum frequency Unimplemented bit 31. CALIB. Successive increments or decrements of OSCTUNE to minimize the deviation from 7.Section 13. just before the call of LoopTime. this calibration can compensate for any subsequent drift in the internal oscillator frequency.000. 13.3 INTERNAL OSCILLATOR CALIBRATION To make accurate timing measurements. For information on this (or any) option. It can be speeded up by incrementing the OSCTUNE register.812)/CALIB (13-1) Alternatively.768) = 7. CalSup1. A calibration supervisor function. CAL.com web site.812. CalSup2 waits for TMR1IF to be set. or subsequently a main loop task. When CalSup1 is next called (with CAL = 1). Instead of the chip returning to sleep immediately. clears its overflow flag. TMR1H is reloaded with 0xFF and its overflow flag is cleared. CAL = 0 and neither function does anything more than just return. at which time. Timer0 is started (“Go”). It sees CAL = 2 and takes charge of the calibration process. wants to initiate a calibration. When Initial. from one loop to the next. and TMR1H is reloaded with 0xFF so that the next Timer1 overflow will occur 10 ms from the beginning of the loop. it stops and resets Timer0 to zero. CalSup2 is called. analogous to . Figure 13-5 shows how the subsequent calibration sequence plays out.174 Chapter 13 Timing Measurements Revisited (Calibrate. It stops Timer1 and reloads it with 0xFFFE. After the main loop tasks have been completed for this pass around the loop. Timer1 is started again. Then CAL is set to 2 so that the CalSup2 function will be there waiting for the rollover of Timer1 after exactly 256 clock edges from the Timer1 oscillator. Timer1 is 2 + 256 counts on its way to the 328 counts that define the 10-ms loop time. Timer0 is stopped. and enables its counting of the slow 32. So Timer1 is stopped.c) Power on Initial sets CAL = 1 to initiate calibration CalSup1 Main loop tasks CalSup2 LoopTime FIGURE 13-4 Reorganizing main loop for calibrating Fosc two functions know where they are in the calibration process. Normally. it sets CAL = 1 (“Ready”). When Timer1 has progressed two more counts and rolls over.768-Hz Timer1 clock again (having not missed a clock edge). Meanwhile. 0xBA is added to TMR1L. Section 13.3 CalSup2 sends display string to PC CalSup2 completes measurement CalSup1 (Calibration supervisor) starts measurement Internal Oscillator Calibration Main loop task calls for calibration by setting CAL = 1 0 1 Sleep Sleep 2 3 Sleep 0 Sleep Sleep • • • CAL (state variable) CPU activity • • • CalSup1 Main loop tasks CalSup2 TMR1IF set 328 10 ms 2+256 10 ms 70 328 10 ms Timer1 counts Time FIGURE 13-5 Calibration sequence 175 . CALIB = 7812 if Fosc/4 = 1 MHz exactly. starting with * the nominal value and incrementing OSCTUNE with each subsequent press.176 Chapter 13 Timing Measurements Revisited (Calibrate.c file of Figure 13-6 illustrates the entire process. RA6=Fosc/4. CALIBH = TMR0H.c in Figure 7-6. * Calibrate Fosc each time that the pushbutton is pressed. With OSCTUNE initialized to 0b00011111. * ******* Program hierarchy ***** * * main * Initial * InitTX * CalSup1 * CalSup2 * BlinkAlive * PBcalibrate * LoopTime * ******************************* */ #include <p18f4321. RA7=I/O // Enable power-up delay // Define PIC18LF4321 registers and bits FIGURE 13-6 Calibrate. the first press will produce the power-on default center frequency. CalSup2 converts CALIB to its four-digit ASCII representation and sends it to the PC for display. On the next pass around the main loop. * Display CALIB on PC. /******* Calibrate.c . Finally.h> /******************************* * Configuration selections ******************************* */ #pragma config OSC = INTIO1 #pragma config PWRT = ON // Use internal osc.5 seconds. The Calibrate. CAL is set to 3 and the TMR1IF flag is reset. CALIB. On returning from the CalSup2 function. Timer0 is read and used to form an unsigned int variable.c) what is done by the LoPriISR of T3. A PBcalibrate function is included that increments Figure 13-3’s OSCTUNE each time the pushbutton is pushed. * Use Timer1 to set loop time to 10 ms. * Blink LED on RD4 for 10 ms every 2. with CAL1BL = TMR0L. as shown in Figure 13-5. the CPU calls the LoopTime function and returns to sleep for the remainder of the 10-ms loop time. // Read in correct sequence // into unsigned int variables // Form CALIB = CALIBH:CALIBL CALIB = (CALIBH << 8) + CALIBL.c *********** * * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz. 3 Internal Oscillator Calibration 177 #pragma #pragma #pragma #pragma #pragma #pragma #pragma #pragma #pragma config config config config config config config config config LVP = OFF WDT = OFF WDTPS = 4 MCLRE = ON PBADEN = DIG CCP2MX = RB3 BOR = SOFT BORV = 3 LPT1OSC = OFF // // // // // // // // // Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period. // char NEWPB. while(--DELAY){ Nop().Section 13. // signed char i. Nop(). CalSup2(void). Scale-of-400 counter for blinking "Alive" LED Index into strings Sixteen-bit counter used by Delay macro Int version of TMR0L Int version of TMR0H Calibration constant Calibration state variable Old pushbutton state New pushbutton state String to represent 0 . // char PCSTRING[] = "xxxx". CalSup1(void). // unsigned int DELAY. LoopTime(void). } #define TXascii(in) TXREG = in.9999 value /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x. while(!TXSTAbits. PBcalibrate(void). // /******************************* * Function prototypes ******************************* */ void void void void void void void Initial(void). // unsigned char CAL. // unsigned int TIMEH. // char OLDPB.TRMT) /////// Main program ////////////////////////////////////////////////////////// /******************************* * main ******************************* */ FIGURE 13-6 (continued) . nominal Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. BlinkAlive(void). // unsigned int CALIB. // unsigned int TIMEL. InitTX(void). nominal Deselect low-power Timer1 oscillator /******************************* * Global variables ******************************* */ unsigned char ALIVECNT.0V. letting watchdog timer wake up chip } } /******************************* * Initial * * This function performs all initializations of variables and registers. // Blink "Alive" LED PBcalibrate(). RCONbits.RA2.SBOREN = 0. INTCONbits.TMR1IF = 0. ******************************* */ void Initial() { OSCCON = 0b01100010. CAL =0. // Toggle for looptime BlinkAlive().RA1. OLDPB = 0. PORTB = 0. // Calibrate each time Pushbutton is pressed Delay(600). TMR1H = 0xFF. // Initialize everything InitTX(). } // // // // // // // // Use Fosc = 4 MHz (Fcpu = 1 MHz) RA0. OSCTUNE = 0b00011111. Initialize pushbutton flags Calibration state variable .c) void main() { Initial().RC2 ^= 1.RA3 pins analog. ALIVECNT = 247. PORTE = 0. TRISC = 0b10000000. ADCON1 = 0b00001011. TRISB = 0b01000100. NEWPB = 0. Delay(50000).TMR1IE = 1. TRISD = 0b10000000. // Sleep. T1CON = 0b01001111. TMR1L = 0x00. LoopTime(). PIR1bits. TRISE = 0b00000010.do nothing yet CALIB = default value after first PB push Enable local interrupt source Initial value Timer1 runs from 32768 Hz oscillator Clear Timer1 flag Enable wake-up from sleep FIGURE 13-6 (continued) . // Pause CalSup2(). TRISA = 0b00001111.178 Chapter 13 Timing Measurements Revisited (Calibrate. PIE1bits. PORTA = 0. // Initialize UART's TX output while (1) { CalSup1(). PORTC = 0. // First part of calibration supervisor PORTCbits.GIEL = 1. PORTD = 0b00100000. Section 13. TXSTA = 0b00100000. It assumes * Fosc = 4 MHz.3 Internal Oscillator Calibration 179 /******************************* * InitTX * * This function initializes the UART for its TX output function. SPBRG = 12.RD4 = 0. } } // Turn off LED // Increment counter and return if not 250 // Reset ALIVECNT // Turn on LED for one looptime /******************************* * PBcalibrate * * Calibrate each time pushbutton is pressed with an increase calibration value ******************************* */ void PBcalibrate() { PORTEbits. // Power up the pushbutton Nop(). if (++ALIVECNT == 250) { ALIVECNT = 0. // Set flag if pushbutton is pressed PORTEbits.RE0 = 0. PORTDbits. // Power down the pushbutton if (!OLDPB && NEWPB) // Look for last time = 0. use Figure 6-3c to * change BRGH and SPBRG appropriately. BAUDCON = 0b00111000. For a different oscillator frequency. // Initiate a calibration sequence FIGURE 13-6 (continued) .RD4 = 1.RE0 = 1. * With a looptime of about 10 ms. // Delay one microsecond before checking it NEWPB = !PORTDbits.RD7. ******************************* */ void BlinkAlive() { PORTDbits. now = 1 { CAL = 1. } // // // // Enable UART Enable TX Set baud rate Invert TX output /******************************* * BlinkAlive * * This function briefly blinks the LED every four seconds. ******************************* */ void InitTX() { RCSTA = 0b10010000. count 250 looptimes. TMR0ON = 0. // Stop Timer0 T1CONbits. T1CON = 0b01001110. } } /******************************* * CalSup2 * * Second part of calibration supervisor. // Clear flag T1CONbits.TMR1IF = 0.TMR1IF = 0. // Timer0 stopped TMR0H = 0.TMR1IF = 0. // Read Timer0 in correct sequence FIGURE 13-6 (continued) . // Stop Timer1 TMR1H = 0xFF. // Clear flag (if not already cleared) CAL = 2. // Start Timer1 again while (!PIR1bits. // Cut out remaining counts of Timer1 T1CONbits.TMR0ON = 1. } // Increment calibration value // Save present pushbutton state /******************************* * CalSup1 * * First part of calibration supervisor. // Upper byte of Timer1 will be 0xFF PIR1bits. // Timer0 = 0 TMR0L = 0. // Next overflow in 256 counts of Timer1 PIR1bits. // Wait for Timer1 to roll over and set flag T0CONbits. // Wait for exact rollover TMR1L = 0xFE. } OLDPB = NEWPB.180 Chapter 13 Timing Measurements Revisited (Calibrate. * ******************************* */ void CalSup2() { if (CAL == 2) // Collect measurement { while (!PIR1bits. * ******************************* */ void CalSup1() { if (CAL == 1) { T0CON = 0b00001000. PIR1bits. // Start Timer0 TMR1H = 0xFF.TMR1IF).c) ++OSCTUNE. // Clear interrupt flag TIMEL = TMR0L.TMR1IF). // and wait for it to set again T0CONbits.TMR1ON = 1.TMR1ON = 1. // Resume Timer1 counter TMR1H = 0xFF. // Pause Timer1 counter TMR1L += 0xBB.TMR1ON = 0. Nop(). } for (i = 0. // Form calibration factor CAL = 3. i <= 3. ++i) { TXascii(PCSTRING[i]). the CCP1M0 edge-select bit is cleared. When this flag is set again (while the chip remains awake. // Upper byte of Timer1 will be 0xFE PIR1bits. and the CCP1IF flag is cleared. } TXascii(0x0D). TXascii(0x0A). For example.Section 13. // Cut out all but 328 counts of Timer1 T1CONbits. CAL = 0. T1CONbits. . PWM) modules that can be set up in a variety of ways to enhance the functionality of the chip’s timers. // Clear interrupt flag } // Display result // Form digits and display on PC 10) + 0x30. // Pause Timer1 counter TMR1L += 0xB9. i >= 0. then CCP1CON is initialized to 0b00000101. to be awakened by Timer1 rollover. ******************************* */ void LoopTime() { Sleep(). // Resume Timer1 counter TMR1H = 0xFE. --i) { PCSTRING[i] = (CALIB % CALIB = CALIB / 10. and the CCP1IF flag is cleared. Either the CCP1 input or the CCP2 input can be used to measure the duration of an input pulse. When the flag is set by the reception of a rising edge. compare. CALIB = (TIMEH << 8) +TIMEL.TMR1ON = 0. CCPR1 is copied to an unsigned int LEADINGEDGE variable. Consider the circuit of Figure 13-7. as shown.4 External Time Measurement 181 TIMEH = TMR0H. if the CCP1 input is used.TMR1IF = 0.TMR1ON = 1. // Done with calibration sequence } else if (CAL == 3) { for (i = 3. // Carriage return // Line feed FIGURE 13-6 (continued) 13.4 EXTERNAL TIME MEASUREMENT The PIC18LF4321 has two CCP (capture. } } /******************************* * LoopTime * * This function puts the chip to sleep. Chapter 13 CCPR2 Timing Measurements Revisited (Calibrate.182 TRISCbits TRISC2 = for CCP1 input or TRISBbits TRISB3 = 1 for CCP2 input T3CON = 0b01001001 to clock Timer3 from FCPU (1 MHz) CCP1CON = 0b00000100 for falling edge or 0b00000101 for rising edge on CCP1 pin or CCP2CON = 0b00000100 for falling edge or 0b00000101 for rising edge on CCP2 pin CCPR1 16 bits CCP1IF set Edge select CCP1M0 CCP1CON 0 0 0 0 0 1 0 1 TMR3 16 bits FCPU (1 MHz) CCP2CON 0 0 0 0 0 1 0 0 CCP2M0 1: Rising edge 0: Falling edge Edge select PIR2 16 bits set CCP2IF CCP2/RB3 CCP1/RC2 1: Rising edge 0: Falling edge PIR1 . .c) FIGURE 13-7 Capture mode operation for CCP1 or CCP2 inputs . C). the CPU can actually be undertaking other tasks while the measurement is under way. However.999 CPU cycles. the difference will be correct even if Timer3 rolls over between the leading edge capture and the trailing edge capture. PROBLEMS 13-1 Adding into Timer0 A user. might make the mistake of adding NUMH:NUML to TMR0H: TMR0L with TMR0L += NUML.Section 13. Because the flag bits can be set up to interrupt the CPU. • Stop – This function stops the counting of Timer0 and forms the number of CPU cycles occurring between Start and Stop in the unsigned int variable. The three functions are listed in Figure 13-8. CYCLES.5 START. • Start – This function initializes Timer0 for counting CPU cycles.5 Start.c program of Figure 6-9. What would be the result? . it is important to read the captured time before the same edge occurs again and overwrites the previously captured time. TMR0H += (NUMH + STATUSbits. unaware of the buffering of TMR0H shown in Figure 13-1. 13. STOP. the CPU cannot be allowed to sleep during the measurement because that will stop the 1-MHz clocking of Timer3. and Send Functions 183 to continue clocking TMR3). Stop. • Send – This function converts CYCLES to its decimal representation as a number ranging from 0 to 9. expressed as four ASCII-coded digits and sends the resulting number to QwikBug’s Console display on the PC. This capture mode determination of an input pulse width produces a timing resolution of 1 µs for each edge. AND SEND FUNCTIONS An opportunity afforded by the serial test port and its connection to the PC is its availability for displaying the number of CPU clock cycles required to execute a function or code segment. For example. Then TIME = TRAILINGEDGE − LEADINGEDGE. Stop and Send functions. CCPR1 is copied to an unsigned int TRAILINGEDGE variable. clears Timer0. These functions are being explained here based on the present understanding of Time0’s use in the configuration of Figure 13-1. The tools needed are the Start. Note that with all three variables being declared to be unsigned integers. the hex subtraction 0002 − FFFF produces a difference of 0003 (plus a borrow that is lost to the 16-bit unsigned result). already used by the Measure. However. and then starts the clocking of Timer0 with the 1-MHz CPU clock. // Clear Timer0 TMR0L = 0. ******************************* */ void Start() { T0CON = 0b00001000. // Send four-digit number TXascii(HUNDREDS). } (c) Send function. // Send carriage return TXascii('\n'). /******************************* * Stop * * This function stops counting Timer0. CYCLES -= 3. TXascii(ONES). // Start counting } (a) Start function. T0CONbits. // Convert TXascii('\r'). TXascii(TENS). /******************************* * Send * * This function converts CYCLES to four ASCII-coded digits and sends * the result to the PC for display.184 Chapter 13 Timing Measurements Revisited (Calibrate. // Form CYCLES from TMR0H:TMR0L CYCLES += (TMR0H * 256). and Send functions . ******************************* */ void Send() { BIGNUM = CYCLES. // Remove 3 counts so back-to-back Start-Stop } // functions produce CYCLES = 0 (b) Stop function. // Stop counting CYCLES = TMR0L. // Set up Timer0 to count CPU clock cycles TMR0H = 0. Stop.TMR0ON = 1. and reads the result into CYCLES. // Send line feed TXascii(THOUSANDS). // Load ASCII4's input parameter ASCII4().c) /******************************* * Start * * This function clears Timer0 and then starts it counting.TMR0ON = 0. ******************************* */ void Stop() { T0CONbits. FIGURE 13-8 Start. using the format ±D CCCC where ±D represents the signed frequency-setting number in OSCTUNE (i. What is the result in each case. −1. . not the CYCLES −= 3. Use the pushbutton to determine a new value of CALIB. Noting that the setting of a port pin immediately followed by the clearing of the pin produces a 1-µs pulse. To verify the loss of the first two counts after TMR0ON is set. blank CCCC until the pushbutton is next pressed.. clears TMR0ON. unlike the clock synchronizer associated with Timer1. Display on the LCD both of these values.e.812.5 Start. it has been left out of the simplified schematic of Figure 13-1. sets TMR0ON.lst file of some code that employs the Start and Stop functions of Figure 13-8 shows that a two-cycle subroutine return instruction follows the setting of the TMR0ON bit at the end of the Start function.c program. +1.0000 MHz? c) Form a new CalibrateX.Section 13. the value corresponding exactly to FCPU = 1. clears TMR0L. 0. so the setting of TMR0ON immediately followed by the clearing of TMR0ON ought to produce a count of one in the previously cleared Timer0 counter. shown in the Stop function. A two-cycle subroutine call instruction is executed before the TMR0ON bit is cleared at the beginning of the Stop function.5. then two Nop macros. a) What is the frequency increment corresponding to a single increment of the OSCTUNE register? b) What value of OSCTUNE will produce the integer value of CALIB that is closest to 7. T0CKI. The two-cycle difference occurs because of a clock synchronizer circuit. it cannot be bypassed via the setting or clearing of a bit in a control register.c program that uses the RPG to increment or decrement the five frequency controlling bits of OSCTUNE. Whenever the RPG is turned. Stop. and how do you (now) explain it? 13-3 Oscillator calibration Run the Calibrate. This circuit is shown in Figure 13-2 because of its important role in dealing with an unsynchronized clock input. the back-to-back calls of the Start and Stop functions of Figure 13-8 ought to produce a count of 2 + 1 + 2 = 5 and require a correction of CYCLES −= 5. and finally three Nop macros between the setting and clearing of the TMR0ON bit.) and CCCC represents the value of CALIB. and Send Functions 185 13-2 Clock-edge synchronization A look at the . However. Consequently. etc. Repeat this by inserting one Nop macro. Because it is a distraction. and then displays TMR0L. write a little test program that clears TRM0H. sends the nine ASCII-coded characters in LCDSTRING to the LCD. and Send functions Repeat Problem 13-4 by modifying the Display function with the Start. e) Create a CalibrateY.c.c) d) Use CalibrateX.186 Chapter 13 Timing Measurements Revisited (Calibrate. never sleeps. Send the resulting number to QwikBug for display in its Console window. and then sets RD5. See whether any attendant heating within the chip affects the calibration. in contrast to CalibrateX. 13-4 External Time Measurement The Display function that is used throughout this book clears RD5. and Send functions to make the same measurement by counting cycles from the instruction that clears RD5 at the beginning of Display to the instruction that sets RD5 at the end. Stop. Connect the TP10 test point (RD5) to the RC2/CCP1 pin on the H4 proto area header. Then display the result on the PC.c program that. without changing the tuning. The intent is to then repeat Part (d) with the chip drawing an average current of about a milliampere. 13-5 Start.c to tune the oscillator as close to 7. Then. . Then write a little test program that uses the CCP1 circuit of Figure 13-7 to capture the number of CPU clock cycles between the falling edge and the rising edge. That is.812 as possible. Stop. modify the LoopTime function so that it just waits for Timer1 to roll over before reloading the value in Timer1. record CALIB immediately and 1 and 2 min later. EEPROM’s nonvolatility means that its data will be retained even when power is removed from the chip and then subsequently restored. home appliances. . hereafter referred to as EEPROM. a write to a byte of EEPROM typically takes 4 ms. with the write operation being self-timed by the EEPROM module. • Consumer: digital TV. .1 OVERVIEW The PIC18LF4321 contains 256 bytes of data EEPROM. the same as a RAM location.c) 14. • Communication: cell phone personalization. This is nonvolatile memory that can be written to a byte at a time. . 187 .Chapter 14 EEPROM (EETEST. . the same as RAM. . . Reads from the EEPROM take just one CPU cycle. games. unlike RAM. This chapter describes EEPROM use. digital radio. 14. Also. seat control. In contrast to RAM. answering machines. .2 EEPROM USE Having nonvolatile memory available is an invaluable resource across the full spectrum of technical activity: • Automotive: security system. monitors. for which a write operation takes just one cycle. . . Figure 14-2b lists a line to be added to the beginning of the main loop.3 EEPROM REGISTERS AND FUNCTIONS The 256 bytes of EEPROM on the PIC18LF4321 are accessed indirectly. to reduce the chance of a runaway CPU overwriting important information. leading to a jump to anywhere in the program memory and executing unintended code. Figure 14-2a lists a line to be added to the Initial function. alarms. Given this. the chip can be asleep during most of the write operation. The EEread function of Figure 14-2c begins by testing the WR bit in the EECON1 register to determine whether a write operation has already been initiated during this loop time. it waits for that write operation to be completed before initiating the read operation. Because each write lasts about 4 ms and because most of this time will usually be spent while the CPU has completed its other useful tasks and returned to sleep for the last of the 10-ms loop time. When an oscilloscope has the ability to retain and restore a complicated setup state. Reading a byte is carried out by writing the address to EEADR. and instead typically use 1 Kbit–1 Mbit EEPROM parts having a serial interface. It disables any further write operations until a subsequent write sequence reenables it. . For an application using the EEPROM memory. it is better to organize the program code within the main loop so that all EEPROM reads occur before any EEPROM writes take place. this line is executed well after the write of a byte has been completed. . Of course. . By clearing the upper 4 bits of EECON1. and then reading the result from EEDATA. Another is channel selection information built into a TV remote. access cards. . One example is the exposure calibration adjustment built into a digital camera. Protecting this EEPROM-write instruction sequence will be addressed in Section 14. including an EEPROM-write instruction sequence. Many applications require much more that the 256 bytes of EEPROM available in the PIC18LF4321. the CPU will go directly from executing code properly to being reset.c) • Industrial: instruments. On the other hand. if the brown-out reset module is not enabled. . this represents a use of the PIC18LF4321’s built-in EEPROM. setting the RD bit in the EECON1 register. For example.188 Chapter 14 EEPROM (EEtest. . When the Qwik&Low board powers up and retrieves the most recently determined clock calibration byte from EEPROM and loads it in the OSCTUNE register. then as the chip is powering down. . 14. writing is a safeguarded process. as the chip is powering down with the brown-out reset module enabled. Many other applications are served well by a small number of bytes.5. wireless optical mice. the CPU can find its program counter bits being corrupted. hard drives. • Computer: motherboards. this line sets the destination of subsequent reads and writes to be the EEPROM memory module. In contrast. this indicates the presence of a small EEPROM. this points to a small EEPROM. to minimize coin cell current. by way of the registers listed in Figure 14-1. If so. When a lawn sprinkler controller remembers its settings through a power glitch or a power outage. motor control. interrupts are suspended (if they were enabled) during the write operation. The WR bit is automatically cleared when done. it is better to organize program code so that only one EEPROM write occurs during each pass around the main loop. The module’s 34-µA current draw will continue for about 10 µs. EECON2 = 0xAA. WR WREN WRERR EECON2 Used in the write sequence EEADR (8 bits) Data EEPROM (256 bytes) EEDATA (8 bits) FIGURE 14-1 EEPROM registers The EEwrite function of Figure 14-2d likewise begins with a test to see if a write is taking place. The EEwrite function then enables the brown-out reset module. Similar to the case of the EEread function. If so.2 to initiate a self-timed 4-millisecond write cycle. At the end of the function. Because the three-line sequence: EECON2 = 0x55. it waits for the completion of the write before proceeding. The RD operation takes one CPU cycle. The RD bit is automatically cleared. Used by the 3-line sequence of Section 14.Section 14. 1: Enable writes 0: Disable writes 1: A write operation is still going on (if WR = 1) or was prematurely terminated by a reset 0: A write operation was completed successfully. // Write first key // Write second key // Set WR bit to initiate write must be executed consecutively with no gaps in between. .3 EEPROM Registers and Functions 189 EECON1 0 0 0 0 RD Setting RD initiates an EEPROM read. EECON1bits. both GIE and SBOREN are restored to their former state. The brown-out reset module will ensure that a powering-down CPU that may have inadvertently been led into code that called the EEwrite function will proceed no further.WR = 1. RD = 1. /**************************** * EEwrite * * This function writes the data contained * address identified by EEADR. // INTCONbits.WREN = 0.SBOREN = SBORENCOPY.SBOREN // RCONbits. // EECON2 = 0x55.WR). // } in EEDATA into the EEPROM 4 milliseconds. // EECON2 = 0xAA. // SBORENCOPY = RCONbits. to disable WREN after any EEwrite during the previous loop.SBOREN = 1.WR). EECON1bits.GIEH = GIEHCOPY.GIEH = 0. Complete any ongoing write Copy SBOREN for subsequent restore Enable brown-out reset Copy GIEH for subsequent restore Disable all interrupts Enable write operation Write first key Write second key Set WR bit to initiate write Restore global interrupt state Restore brown-out reset state (d) EEwrite function. // Wait on the completion of any ongoing write EECON1bits.c) EECON1 = 0.WREN = 1. // Initialize module state (a) Addition to the Initial subroutine.WR = 1. **************************** */ void EEread() { while (EECON1bits.190 Chapter 14 EEPROM (EEtest. // EECON1bits. FIGURE 14-2 EEPROM functions . // INTCONbits. * The write is self-timed and takes about **************************** */ void EEwrite() { while (EECON1bits. // EECON1bits.GIEH. // Disable further EEPROM writes (b) Instruction to add to the beginning of the main loop. // GIEHCOPY = INTCONbits. // RCONbits. /**************************** * EEread * * This function reads from the EEPROM address identified by EEADR * into EEDATA. } (c) EEread function. Section 14. decrement EECNT and return.4 Protecting the Write Sequence 191 14. EECNT will have been decremented to zero so that calls of EEArrayWrite during subsequent passes around the main loop do nothing until the RAM array. It precedes these two writes with a write to EEPROM address 0x10. 14. The logic analyzer capture of these three writes is shown in Figure 14-4b and expanded for the second write in Figure 14-4c. The EEArrayWrite function can be called every time around the main loop. By enabling the brown-out reset feature of the chip for FIGURE 14-3 EEArrayWrite functions EECNT RAM RAMPTR EEADDRESS EEPROM • • • • • • (a) Registers . Its action is to copy 1 byte. To help identify when each write takes place. RC2 is toggled and a 1-ms delay is inserted. the two pointers and EECNT have been reloaded for a new multiple-byte write sequence. It acts only if EECNT is nonzero. The example code of Figure 14-4a implements the example listed in the header of Figure 14-3e to execute two writes to EEPROM addresses 0x20 and 0x21. Before the function is called. When all bytes have been copied. the EEArrayWrite function of Figure 14-3 will serve. Then EEADDRESS is loaded with the first EEPROM destination address. and EECNT is loaded with the number of bytes to be copied. the bytes are first written into consecutive RAM addresses and RAMPTR is loaded with the first of these addresses. If the writes are destined for consecutive EEPROM addresses.5 PROTECTING THE WRITE SEQUENCE The discussion associated with the EEwrite function of Figure 14-2 has already addressed the recurring problem of applications for which power is turned off as a matter of regular practice. This delay keeps the chip awake and is reflected in the 1 ms of FOSC/4 clocking after each write.4 MULTIPLE WRITE SEQUENCES Quite often an update of data stored in EEPROM involves a sequence of writes. Figure 14-4d displays the resulting content of EEPROM as read by the PICkit 2 programmer. 192 Chapter 14 EEPROM (EEtest. * Example usage: * char TEMPARRAY[] = {'a'. void EEArrayWrite(void). // Number of bytes to copy (b) Global variable additions. Then it increments RAMPTR and EEADDRESS and * decrements EECNT. void EEwrite(void). **************************** */ void EEArrayWrite() { if(EECNT && !EECON1bits. * and EEPROM has 'b' and 'c' in address 0x20 and 0x21 respectively. // Copy of SBOREN bit for EEPROM writes char* RAMPTR. * Variable declaration: * char* RAMPTR. } } (e) Function. // Pointer to RAM array to be copied to EEPROM char TEMPARRAY[] = {'a'. unsigned char EECNT.'d'}. * RAMPTR = TEMPARRAY + 1. // Characters to copy unsigned char EEADDRESS.c) char GIEHCOPY.'b'. * After 2 calls of EEArrayWrite. FIGURE 14-3 (continued) . EECNT = 2. /**************************** * EEArrayWrite * * Each time this function is called with EECNT != 0. * EECNT = 2. it writes one byte * from the RAM char[] pointed by RAMPTR. RAMPTR. // Initialize module state // Experiment with EEPROM // Set up for writes 2 and 3 (d) Additions for Initial function.'c'. EEADR = EEADDRESS++. EECNT = 0.'d'}. EEADDRESS = 0x20. // Copy of GIEH bit for EEPROM writes char SBORENCOPY. EECNT--.WR) { EEDATA = *(RAMPTR++). unsigned char EEADDRESS. void EEread(void). * EEADDRESS = 0x20. EEwrite(). EECON1 = 0. into the EEPROM location whose * address is in EEADDRESS. // Starting address in EEPROM unsigned char EECNT.'c'.'b'. (c) Function prototype additions. RAMPTR = TEMPARRAY + 1. EEADDRESS and EECNT should not be modified * by other code until EECNT is 0. FIGURE 14-4 Multiple EEPROM writes .c ************** * * Test Alex's example. // Copy of SBOREN bit for EEPROM writes char* RAMPTR. // Characters to copy unsigned char EEADDRESS. // Sixteen-bit counter for obtaining a delay /******************************* * Function prototypes ******************************* */ void Initial(void). * ******* Program hierarchy ***** * * main * Initial * ******************************* */ #include <p18f4321.Section 14.'b'. nominal Deselect low-power Timer1 oscillator // Define PIC18LF4321 registers and bits /******************************* * Global variables ******************************* */ char GIEHCOPY.'c'.1V. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially 16 millisecond WDT timeout period. nominal Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. // Starting address in EEPROM unsigned char EECNT. // Number of bytes to copy unsigned int DELAY. // Copy of GIEH bit for EEPROM writes char SBORENCOPY. void EEread(void).'d'}. * Show EEwrites by awake times on scope (using Delay(100)).4 Protecting the Write Sequence 193 /******* EEtest. // Pointer to RAM array to be copied to EEPROM char TEMPARRAY[] = {'a'. RA6=Fosc/4. // Sleep through writes to EEPROM Nop(). // Set I/O for PORTD TRISE = 0b00000010.RA1. // Set I/O for PORTC TRISD = 0b10000000. /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x. Nop(). // Deal with EEPROM writes Sleep(). // RA0. while(--DELAY){ Nop(). // Set initial state for all outputs low FIGURE 14-4 (continued) . ******************************* */ void Initial() { OSCCON = 0b01100010. } } // Writes 2 and 3 // Check this /******************************* * Initial * * This function performs all initializations of variables and registers. // Set up SPI for output to LCD SSPCON1 = 0b00110000. ADCON1 = 0b00001011.194 Chapter 14 EEPROM (EEtest. } /////// Main program /////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). // Set I/O for PORTB TRISC = 0b10000000.WREN = 0. EEDATA = 0xAA. void EEArrayWrite(void). // Initialize everything EEADR = 0x10. // Disable further EEPROM writes EEArrayWrite(). // Set I/O for PORTE PORTA = 0. others digital TRISA = 0b00001111. EEwrite(). // Set I/O for PORTA TRISB = 0b01000100.c) void EEwrite(void). // Use Fosc = 4 MHz (Fcpu = 1 MHz) SSPSTAT = 0b00000000. // Do the first write // Write 1 while (1) { EECON1bits.RA2.RA3 pins analog. Then it increments RAMPTR and EEADDRESS and * decrements EECNT. * RAMPTR = TEMPARRAY + 1.'b'.'c'.SBOREN = 0. EECNT = 0. **************************** */ void EEArrayWrite() { if(EECNT && !EECON1bits. * and EEPROM has 'b' and 'c' in address 0x20 and 0x21 respectively. EECNT--. * EEADDRESS = 0x20. * After 2 calls of EEArrayWrite. * Variable declaration: * char* RAMPTR. RCONbits. **************************** */ FIGURE 14-4 (continued) . EEwrite(). EECNT = 2.4 Protecting the Write Sequence 195 PORTB = 0. it writes one byte * from the RAM char[] pointed by RAMPTR.WR) // Skip to next loop time for second write { EEDATA = *(RAMPTR++). EEADDRESS = 0x20. unsigned char EECNT. * Example usage: * char TEMPARRAY[] = {'a'. } // Initialize module state // Experiment with EEPROM // Set up for writes 2 and 3 /**************************** * EEArrayWrite * * Each time this function is called with EECNT != 0. * EECNT = 2.'d'}. RAMPTR. RAMPTR = TEMPARRAY + 1. PORTE = 0. Delay(50000). } } /**************************** * EEread * * This function reads from the EEPROM address identified by EEADR * into EEDATA. into the EEPROM location whose * address is in EEADDRESS. EEADR = EEADDRESS++. EEADDRESS and EECNT should not be modified * by other code until EECNT is 0. WDTCONbits.SWDTEN = 1. PORTC = 0.Section 14. PORTD = 0b00100000. unsigned char EEADDRESS. // except RD5 that drives LCD interrupt // Pause for half a second // Now disable brown-out reset // Enable watchdog timer EECON1 = 0. // Write second key EECON1bits.WR).SBOREN. // Wait on the completion of any write SBORENCOPY = RCONbits. // Disable all interrupts EECON1bits. * The write is self-timed and takes about 4 milliseconds. // Restore brown-out reset state PORTCbits. // Write first key EECON2 = 0xAA.WREN = 1. // Copy GIEH for subsequent restore INTCONbits.GIEH = GIEHCOPY.RD = 1.WR). **************************** */ void EEwrite() { while (EECON1bits.c // Toggle pin to flag where write occurs // Add a delay to show sleep after 1 ms (b) Three writes + 1 ms markers FIGURE 14-4 (continued) .GIEH = 0.GIEH. // Set WR bit to initiate write INTCONbits. EECON1bits. // Enable write operation EECON2 = 0x55.RC2 ^= 1. } (a) EEtest.SBOREN = 1.SBOREN = SBORENCOPY.196 Chapter 14 EEPROM (EEtest. } // Wait on the completion of any write // Read from EEADR into EEDATA /**************************** * EEwrite * * This function writes the data contained in EEDATA into the EEPROM * address identified by EEADR.WR = 1. // Enable brown-out reset GIEHCOPY = INTCONbits. // Copy SBOREN for subsequent restore RCONbits.c) void EEread() { while (EECON1bits. // Restore global interrupt state RCONbits. Delay(100). when the CPU executed the brown-out reset enable instruction. This produces the same threat as that of the last section without any help from the solution offered there. the INBUG bit is set.192 addresses making up program memory will lead into the undesirable sequence. However. A perturbation of the program counter that produces an inadvertent write sequence can only be to the program memory address produced by the EECON2 = 0x55. None other of the 8. The out-of-range value of VDD may have produced a transmutation of a bit in the program counter that was following a path to the call and execution of the EEwrite function. a powering-down of the chip that is already in progress and has reached the point where VDD is below 2 V will reset the chip. the CPU’s execution of further instructions was stopped dead in its tracks. Even at that. consider how QwikBug writes downloaded user code into the flash program memory using the WriteInitiateSequence function of Figure 14-5. Another type of concern arises when an application is subjected to a perturbation (e. the address pointer at that moment is pointing . When the chip is in the Background Debug Mode used by Microchip’s programming/debugging tools such as the PICkit 2 and also used by QwikBug.g. the RF interference resulting from a lightning strike) that reaches all the way into the chip and toggles a bit of the program counter. As an example of a different approach.Section 14.. The first line of the function tests a bit in an undocumented DEBUG register. // Write first key line.5 Protecting the Write Sequence 197 (c) Second write and its 1 ms marker (d) PICkit2 verification of the three writes FIGURE 14-4 (continued) the duration of the write sequence. In this way. .198 Chapter 14 EEPROM (EEtest. When the counter reaches 100. RELEASE = 0. } } // Write first key // Write second key // Set WR bit to initiate write FIGURE 14-5 QwikBug’s WriteInitiateSequence function.000 writes. Each write to an EEPROM byte is translated by the EEPROM module into an erase operation followed by the actual write operation. EECON1bits.000. not into the area that holds QwikBug. If the press is used to set a PRESS flag while the release is used to set a RELEASE flag.INBUG) { EECON2 = 0x55. } 14. PRESS = 0. This can be extended to 1. into the user area of program memory.WR = 1.c) WriteInitiateSequence() { if (DEBUGbits. the QwikBug code is protected against corruption by the inadvertent execution of its own code by a user program.000 erase per write cycles for any addresses that have not been written to in the last 100.000 (because each write is accompanied by a write to the counter). EECON2 = 0xAA. then a test of PRESS can be used to load up the registers used by the EEwrite function. Another refresh scheme for an application that uses only n bytes of EEPROM is to use one of those bytes as a counter and increment it each time any of the other bytes is written to. A similar tack can be taken when an EEPROM write is initiated by an external event. the press of a pushbutton.000 writes to the module by refreshing them. Each of the 256 addresses of EEPROM memory in the PIC18LF4321 is specified to be able to sustain a minimum of 100.000 erase per write cycles before an error may occur.000/2 = 50. provides the information needed to copy the content of each of the 256 addresses back to itself after every 100.6 EEPROM LIFE The finite life of EEPROM bits is a factor of little consequence for most applications. for example. and knowing how long it has been since the last refresh cycle. and the following sequence used to initiate the write: if (PRESS && RELEASE) { EEwrite(). Knowing the rate at which EEPROM writes are being carried out by a heavy duty EEPROM application. the next n bytes are used. If not. This section has been a detailed look at handling the finite EEPROM life issue that never even arises for most applications. b) Create a new InitOSCTUNE function.Section 14. This function first looks at the char value located at 0xFF.. address 255) can serve as a block pointer to indicate which of the five blocks is the active block. If CALIB = 7. the 50 bytes are copied to the next block. the EEPROM is invaluable to the application.g. that user program will be armed to produce calibrated microsecond measurements in addition to cycle count measurements. this scheme extends the life of the EEPROM module to (100. Test to see if this upper byte stored in EEPROM address 0xFF falls within the range 0x1C to 0x21.. send the word “Recalibrate” to the Qwik&Low Console. This should hold the upper byte of CALIB if the CalibrateY. the EEPROM memory can be divided into 256/50 blocks: 0–49 50–99 100–149 150–199 200–249 with six addresses left over. If so.000 erase per write cycles. the counter in the new block zeroed and the block pointer incremented. PROBLEMS 14-1 SendMicroSec function a) Modify the code developed for the CalibrateX.000/2) × 10 × 5 = 2. but its erase per write endurance is not an issue.g. Within each block. One of these last six (e. . copy the EEPROM value from 0xFD into OSCTUNE. If the MCU in the camera were a PIC18LF4321. When the counter reaches 100.c program has been run. In this case. one address (e. the EEPROM within the microcontroller within a camera may be written to a few times during its exposure calibration at the completion of its assembly and then never written to again. if only 50 bytes are used. then this upper byte will be 0x1E.c program of Problem 13-3 so that it stores the content of OSCTUNE into address 0xFD of EEPROM and the content of CALIB into 0xFE and 0xFF after each calibration carried out in response to a pushbutton press.500. In this case.812 = 0x1E84.5 EEPROM Life 199 For example.000. its more relevant spec is its minimum data retention of 40 years. 0 or 50 or 100 or 150 or 200) can serve as the counter of writes to the block. If this InitOSCTUNE function is called toward the end of the Initial function of a user program. For example. Use this information to comment on the results found in Part (d). Use Equation 13-1 from Section 13. .200 Chapter 14 EEPROM (EEtest. and immediately followed by the clearing of RB0 and then the call of the Stop function and the SendMicroSec function. The difference between these two measurements is the result of exactly 2.000 cycles of execution. use its extraordinarily accurate time interval and frequency measurement capability to check both the pulse width of RB0 and also the accuracy of FOSC/4. on test point TP6. How close is the resulting number of microseconds for the pulse width to the number calculated from the PC values? e) If a “universal counter” is available to you.3 to convert CYCLES to BIGNUM. Compare the pulse width on RB0 with the result that is displayed on the PC. the CPU clock frequency.000 cycle pulse with Delay(200) that is immediately preceded by the call of the Start function and then the setting of RB0.c) c) Create a SendMicroSec function analogous to the Send function of Figure 13-8c. Now comment out just the Delay macro and do this again. d) Use the Delay macro to generate a 2. with the MCU controlling the timing of each bit. The 1-wire part has a true open-drain output that can pull the I/O line low by overriding the pull-up resistor. the MOSFET 201 . These parts fit well in the low-current environment of the Qwik&Low board. and each multiple-byte message transfer. Then the broader issue of dealing with other 1-wire devices is discussed.Chapter 15 1-WIRE INTERFACE (SSN. one MCU pin is used to power the part.2 INTERFACE CIRCUITRY The interface circuit of both a 1-wire part and the MCU is shown in Figure 15-1. has a family of parts that employ a 1-wire interface. The chapter begins with the 1-wire protocol and its implementation by Alex Singh in the SSN.c template file to read back the unique 8-byte serial number from a DS2401 Silicon Serial Number part. each byte. Another pin is used for bidirectional communication between the MCU and the part. as exemplified by the Silicon Serial Number part of Figure 3-2. 15. As shown there. now a part of Maxim Integrated Circuits.c) 15.1 OVERVIEW Dallas Semiconductor. If its internal line labeled “Output” in Figure 15-1 is low. Thus. The 1-wire protocol supports this by including at least a 180-µs “high” interval on the I/O line before ones and zeros are transferred. If “Output” is high.202 Chapter 15 1-Wire Interface (SSN. • Drives TRISD2 high whenever it is expecting input data so that the 1-wire chip can control the I/O line.c) MCU RD3 (power-switching) 5 kΩ Input I/0 line 1-wire chip Parasitic power for chip Input RD2 = 0 Output Output high = open drain out or input Output low = 0 V out TRISD2 TRISD2 high = open drain output or input TRISD2 low = 0 V out FIGURE 15-1 1-wire interface circuit will pull the I/O line low. the 1-wire chip: • Drives its “Output” low to force a “0” on the I/O line. • Drives its “Output” high whenever it is expecting input data so that the MCU can control the I/O line. Thus. This interval is sufficient to charge the internal capacitor that keeps the internal logic supplied during a message transfer. It is this latter MOSFET that must never be turned on. an output driver with one MOSFET to pull the I/O line down to ground and another MOSFET to pull the I/O line up to VDD. • Drives TRISD2 high to generate an “open-drain” output of “1”. that is. the MCU must simulate having an open-drain output with what is actually a totem-pole output. • Drives its “Output” high to generate an (open-drain) output of “1”. the MOSFET is turned off and the I/O line will be pulled high by the pull-up resistor unless some other device (the MCU in this circuit) pulls the line low. • Draws “parasitic” power from the I/O line. For its part. This is achieved by treating the TRISD2 pin as the open-drain output. the MCU: • Drives TRISD2 low (with RD2 low) to force a “0” on the I/O line. . Consequently. FIGURE 15-2 Writing ones and zeros . Start of bit Start of next bit Controlled by pull-up resistor Trecover Controlled by MCU I/O line Tlow Tslot Trecover 60 µs ≤ Tlow ≤ Tslot < 120 µs 1 µs ≤ Trecover < ∞ (b) Writing a zero. Figure 15-2a illustrates the timing to send a one by pulling the line low with PORTDbits. Start of bit Start of next bit Controlled by pull-up resistor Controlled by MCU I/O line Tlow Tslot 1 µs ≤ Tlow ≤ 15 µs 60 µs ≤ Tslot < 120 µs 1 µs ≤ Trecover < ∞ (a) Writing a one.Section 15.TRISD2 = 0.3 Writing Ones and Zeros 203 15. TRISDbits. input and output are treated somewhat differently.RD2 = 0.3 WRITING ONES AND ZEROS The MCU controls the timing for each bit that it sends or receives. TRISD2 = 1.4 MESSAGE PROTOCOL The protocol for a complete message between the MCU and the DS2401 Silicon Serial Number part is illustrated in Figure 15-3. The MCU can look for the line to be low 60 µs after it was released at the end of the reset pulse. For clarity in his SSN. When the I/O line is released by the MCU. pulling the I/O line low for the half-millisecond Reset pulse shown in Figure 15-3 will force their interface circuitry to the reset state. // Send ONE and the code to send the zero shown in Figure 15-2b becomes OpenDrainLow. the DS2401 will begin operation in its reset state. This Presence pulse may last for up to 240 µs. The code to send a one becomes OpenDrainLow. More generally. and OpenDrainHigh. for multiple 1-wire devices sharing a single 1-wire I/O bus. and then waiting out the Tslot time with Delay(6). sent LSb (least-significant-bit) first. The DS2401 responds to the Read ROM command. coded as 0x33. If it begins with the I/O line powered down for longer than half a millisecond. It is sent out by the MCU with BYTETOSEND = 0x33. OpenDrainHigh: Delay(6).c source file. // Send ZERO 15. .c) and releasing it immediately with TRISDbits. All 1-wire devices expect the Presence pulse time slot to be followed by the reception from the MCU of a 1-byte command. the DS2401 and any other 1-wire devices sharing the I/O line will pull the line low to signal their presence on the bus. SendByte().204 Chapter 15 1-Wire Interface (SSN. but the MCU can continue with the next step of the protocol after a high recovery time of at least 180 µs. Delay(6). Alex Singh represents the first two of these steps with macros: OpenDrainLow. as required. OpenDrainHigh. 0x33 (least-significant bit first) Read back 64-bit Silicon Serial Number (least-significant bit first) FIGURE 15-3 SSN protocol 205 .Section 15.4 Tph Tpl I/O line Line idle Read ROM 64-bit SSN Message Protocol Trec Line idle Reset pulse (> 480 µs) Look for DS2401 to pull line low for presence pulse 15 µs ≤ Tph < 60 µs 60 µs ≤ Tpl < 240 µs 180 µs < Trec < ∞ Send 8-bit Read ROM command. c code of Figure 15-4.0V. * ******* Program hierarchy ***** * * main * Initial * InitTX * DS2401 * PresenceTest * SendByte * ReadByte * SaveByte * SendSSNSTRING * ******************************* */ #include <p18f4321. received a bit at a time (LSb first) as discussed in the next section. // unsigned char BYTETOSEND. Each of the 8 bits is sent as discussed in the last section. j. // unsigned int DELAY. * Developed by Alex Singh.c) in the DS2401 function of the SSN. /******* SSN. RA7=I/O Enable power-up delay Disable low-voltage programming Disable watchdog timer initially Enable master clear pin PORTB<4:0> = digital Connect CCP2 internally to RB3 pin Brown-out reset controlled by software Brown-out voltage set for 2. the DS2401 expects to be queried for its 64-bit SSN. // Use internal osc. In response. nominal Deselect low-power Timer1 oscillator Loop counters Sixteen-bit counter for obtaining a delay Used by SendByte Used to store byte read from DS2401 FIGURE 15-4 SSN.c ***************** * * Read the DS2401 serial number and then sleep with RD3 high and RD2 = input * Use Fosc = 4 MHz for Fcpu = Fosc/4 = 1 MHz ******************************* */ unsigned char i. RA6=Fosc/4.206 Chapter 15 1-Wire Interface (SSN.c . // unsigned char SSNBYTE. /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x. void SaveByte(void). // Nop(). while(--DELAY){ Nop().TRMT) #define OpenDrainHigh TRISDbits. ******************************* */ FIGURE 15-4 (continued) . char PresenceTest(void). } #define TXascii(in) TXREG = in.Section 15. /******************************* * Function prototypes ******************************* */ void Initial(void).TRISD2 = 0 /////// Main program /////////////////////////////////////////////////////////// /******************************* * main ******************************* */ void main() { Initial(). } Initialize everything Initialize UART Read and display SSN on PC Done /******************************* * Initial * * This function performs all initializations of variables and registers. Nop(). TRISDbits. while(!TXSTAbits. // InitTX(). // Sleep().4 Message Protocol 207 char SSNSTRING[20] = "xxxxxxxxxxxxxxxx\n\r\0". void SendByte(void).RD2 = 0. void SendSSNSTRING(void).TRISD2 = 1 #define OpenDrainLow PORTDbits. void InitTX(void). // DS2401(). void DS2401(void). void ReadByte(void). // To hold DS2401's serial number /******************************* * Constant array in program memory ******************************* */ const char rom FormHex[] = "0123456789ABCDEF". RD3 = 1. RCONbits. disable brown-out reset /******************************* * InitTX * * This function initializes the UART for its TX output function. if(!PresenceTest()) { PORTDbits. PORTC = 0. // Enable TX SPBRG = 12.208 Chapter 15 1-Wire Interface (SSN. // Enable UART TXSTA = 0b00100000.RD4 = 1. PORTD = 0b00100000. SSPCON1 = 0b00110000. ADCON1 = 0b00001011.RA2. turn on red LED and halt. PORTB = 0. TRISA = 0b00001111. TRISE = 0b00000010. // Set baud rate BAUDCON = 0b00111000. * It assumes Fosc = 4 MHz. // Presence Test // Turn on LED FIGURE 15-4 (continued) . Delay(50000). // Invert TX output } /******************************* * DS2401 * * This function displays on the PC the serial number given * by the DS2401.5 second for contact bounce // After this delay.SBOREN = 0. 0. TRISC = 0b10000000. TRISD = 0b10000100. PORTE = 0. PORTA = 0. ******************************* */ void InitTX() { RCSTA = 0b10010000. } // Use Fosc = 4 MHz (Fcpu = 1 MHz) // Set up SPI for output to LCD // // // // // // // RA0. SSPSTAT = 0b00000000. // Master Reset with 500 us negative pulse OpenDrainHigh. TRISB = 0b01000100. If it is not present. ******************************* */ void DS2401() { PORTDbits.c) void Initial() { OSCCON = 0b01100010. // Apply power to SSN part OpenDrainLow. Delay(50).RA1.RA3 pins analog. // Leave I/O pin as an input PORTDbits.RD3 = 1. // Send "Read ROM" command to get back SendByte(). SaveByte(). j > 0. ******************************* */ void SendByte() { for (i = 0. } OpenDrainHigh. // and be done } else { BYTETOSEND = 0x33. OpenDrainHigh. j-=2) // Read and save 8 bytes { ReadByte(). } SendSSNSTRING(). i++) // Send 8 bits of command { if (BYTETOSEND & 1) // Test bit 0 { OpenDrainLow. Nop(). Tslot = 85 us for ONE or for ZERO.4 Message Protocol 209 Sleep(). } /******************************* * SendByte * * This function sends BYTETOSEND to DS2401. ******************************* */ char PresenceTest() { Delay(10).Section 15. // Wait for line to be released return 1. } return 0. // Leave SSN part empowered } /******************************* * PresenceTest * * This function returns a 1 if DS2401 is present and a 0 otherwise.RD2). // serial number for (j = 16. i <= 7. } FIGURE 15-4 (continued) . // After 100 us if (!PORTDbits.RD2) // check for Presence { while (!PORTDbits. // Send ONE Delay(6). // Sample 13 us after 'clocking' if (PORTDbits. Delay(6).RD2) { SSNBYTE += 0b10000000. // Save upper nibble SSNSTRING[j . ******************************* */ void SaveByte() { SSNSTRING[j . } } // Send ZERO // Move on to next bit /******************************* * ReadByte * * This function reads in the 64-bit serial number a byte at a time. ******************************* */ void ReadByte() { SSNBYTE = 0. // Initialize SSNBYTE for (i = 0.c) else { OpenDrainLow. // Copy bit into SSNBYTE } Delay(3). } } /******************************* * SaveByte * * This function converts the binary value in SSNBYTE into two * ASCII-coded digits in SSNSTRING. Delay(1). i <= 7. OpenDrainHigh.1] = FormHex[SSNBYTE & 0x0F].210 Chapter 15 1-Wire Interface (SSN. * Tslot = 70 us for ONE or for ZERO. i++) // Read 8 bits from DS2401 { SSNBYTE >>= 1.2] = FormHex[SSNBYTE >> 4]. // Save lower nibble } FIGURE 15-4 (continued) . OpenDrainHigh. } BYTETOSEND >>= 1. * DS2401 holds line low for zero for 35 us. // Move on to next bit OpenDrainLow. 5 READING ONES AND ZEROS Figure 15-5 illustrates the reading of ones and zeros from the DS2401.6 GENERALIZING FROM THE SSN.2 µA to this shutdown current.1 µA from the coin cell. // Send all bytes until null terminator } } FIGURE 15-4 (continued) 15.c Template 211 /******************************* * SendSSNSTRING * * This function sends SSNSTRING to the PC. read the SSN. input) state while RD3 is powered down before the MCU is put to sleep. The DS2401 function listed in Figure 15-4 calls its ReadByte function eight times to acquire the 64-bit SSN.c file does nothing more than to initialize the chip. . and then go to sleep. ++i) { TXascii(SSNSTRING[i]). The DS2401 responds to the falling edge and leaves the line released for a “1” or pulls the line low for a “0”. The MCU clocks each bit time by pulling the I/O line low and then immediately releasing it. it adds just 0.Section 15.e. the entire string is sent to the PC for display. It waits for something over 60 µs (the Tslot time of Figure 15-5) before initiating the falling edge to clock the next bit response. SSNSTRING[i]. ******************************* */ void SendSSNSTRING() { for (i=0. 15.c TEMPLATE • The intent of the code of Figure 15-4 is to illustrate the general principles of 1-wire messaging including: • Reset pulse generation • Presence pulse detection • Sending a 1-byte command • Sending or receiving bytes to or from a 1-wire device The SSN. shifting the bits into SSNBYTE. Each ReadByte is followed by a SaveByte that breaks SSNBYTE into two ASCII-coded hexadecimal characters and inserts these into the long SSNSTRING string. After SSNSTRING has been loaded with the 16 hex characters. The MCU samples the line after about 15 µs. Even if the DS2401 chip is left empowered.6 Generalizing from the SSN. Each call of ReadByte reads the I/O line eight times. The board at that point draws just 0.. Then the I/O pin is left in the Open-DrainHigh (i. 212 Chapter 15 1-Wire Interface (SSN.c) Start of bit Start of next bit Controlled by pull-up resistor Controlled by MCU Controlled by DS2401 I/O line Tlow Tread Tslot 1 µs ≤ Tlow < 15 µs Tread = 15 µs 60 µs ≤ Tslot < 120 µs (a) Reading a one Start of bit Start of next bit Controlled by pull-up resistor Controlled by MCU Controlled by DS2401 I/O line Tlow Tread Trelease Trecover < 15 µs = 15 µs ≤ 45 µs < 120 µs Tslot 1 µs ≤ Tlow Tread 0 µs < Trelease 60 µs ≤ Tslot 1 µs ≤ Trecover < ∞ (b) Reading a zero FIGURE 15-5 Reading ones and zeros . The selected device will then respond to all subsequent commands while the unselected devices will stay idle until they receive another Reset pulse. Following the Reset pulse/Presence pulse sequence.7 Multiple 1-Wire Devices on a Single Bus 213 More generally. several DS1825 digital thermometer chips may be used to monitor potential hot spots of a PC board. As an example of the application of multiple devices. it is important to disable interrupts before each bit transfer is initiated. 15. In response to the first read. temperature sensors. one of their Thermochron parts can be included in a shipment of perishable food to log temperature samples. an I/O message string can be paused indefinitely. but also the location of a hot spot can be identified. Nothing is lost if an interrupt service routine intervenes after the MCU releases the I/O line and has. all devices send the state of the LSb of their ROM address. This Search ROM command will be discussed shortly. The two 1-wire commands that are used to identify and select any one device are Search ROM (0xF0) Match ROM (0x55) The ROM that is being referred to here is the unique 64-bit serial number included in every 1-wire device. The Search ROM command is used iteratively to determine the ROM content of each device on the 1-wire bus. 1-wire device interactions can be employed during the on-going operation of a larger program. not only is temperature measured. if an interrupt occurs while the MCU is holding the line low and the resulting pause causes a 1-wire device to be held low for more than 120 µs. analog-to-digital converters. Thus. However. each of these can be stored in the MCU’s EEPROM. The Search ROM command is followed by two 1-bit reads and a 1-bit write. battery usage (current × time) monitors. to verify whether the shipment was handled as intended. For example. Each chip. During the second read. While the I/O line is high. a specific device is selected by sending the Match ROM command followed by the 64-bit ROM contents in the 64 time slots (LSb first) that follow the eight time slots of the Match ROM command. all devices send the complement of the LSb of their ROM address.7 MULTIPLE 1-WIRE DEVICES ON A SINGLE BUS The Dallas/Maxim repertoire of 1-wire integrated circuits includes real-time clocks. The interpretation of the response to these two reads is listed in Figure 15-6a. In this section. and nonvolatile memory with security key access. not just the DS2401 Silicon Serial Number part discussed earlier. and used thereafter to select a device. the serial I/O messaging protocol may be reset. Dallas/Maxim’s significantly pricier iButton parts are housed in a rugged coincell-like package and can employ extended self-powered capabilities afforded by an internal lithium battery. Once found. completed the reading or the writing of a bit. the emphasis will be on identifying and selecting a specific 1-wire device from among several sharing a single bus. in addition. to take advantage of the versatility of 1-wire devices. During such interactions.Section 15. has four of its pins hard-wired as a 4-bit address. The next . housed in a tiny 8-pin surfacemount package. the first bit mismatch found will be the only bit mismatch needed to obtain the second part’s ROM address. the result will be to select the part with the highest ROM address. Figure 15-6c illustrates the Search ROM process of successive read-read-write bits to sort out the ROM address of one of the devices.214 Chapter 15 1-Wire Interface (SSN. Bit number 0 1 1 0 2 1 3 1 4 0 ••• ••• ROM address of selected part Read-read-write sequence Select both devices Mismatch detected between parts Select one device Keep selecting the selected part to obtain its complete ROM address 1 0 1 0 1 0 0 0 1 1 0 1 0 1 0 ••• (c) Example. a zero is written. Instead of writing a one back for this bit. Write 1 0 Interpretation Only devices with a 1 in this ROM address position remain enabled Only devices with a 0 in this ROM address position remain enabled (b) Meaning of the write during the next Time slot. FIGURE 15-6 Search ROM procedure time slot (Figure 15-6b) is used as a write.c) First read 1 0 0 Second read 0 1 0 Interpretation All devices have a 1 in this ROM address position All devices have a 0 in this ROM address position Devices differ in this ROM address position (a) Interpretation of a pair of reads. deselecting the chip whose . If only two 1-wire parts are connected to the 1-wire bus. to select all devices that match the bit written to them. obtaining the ROM address of one of a pair of 1-wire parts. If a “1” is written during the third of the three time slots each time a bit mismatch is detected (by a read-read of 0-0). Section C. until all ROM data are identified. the master goes in the opposite direction and continues.g. RA5 .8 DS2415 1-Wire Time Chip 215 1 1 0 0 1 0 0 1 1 1 0 1 1 0 1 0 1 1 0 1 9 ••• ••• ••• ••• ••• ••• 1 0 1 1 0 0 Bit position 0 1 2 3 4 5 6 1 0 1 7 1 8 FIGURE 15-7 Tree of ROM addresses for five 1-wire parts ROM address has already been found in order to continue to determine the ROM address for the second part. the master has learned another ROM’s contents. Alternatively. then subsequently the path having a zero in this second mismatch position must be followed. For three 1-wire parts connected to the 1-wire bus.. two otherwise unused pins of the MCU (e. and so on.Section 15. retaining power even when the power switch is turned off.3 Search ROM Command: “The general principle of this search process is to deselect one device after another at every conflicting bit position. After both paths at the highest conflicting bit position are followed to the end. and so on.8 DS2415 1-WIRE TIME CHIP The Dallas/Maxim DS2415 1-wire time chip can be added to the Qwik&Low board using the surface-mount pattern in the prototyping area of the board. Dallas/Maxim addresses this determination systematically in an application note that can be found by Googling “Book of iButton Standards” and then finding on PDF page 58. If another conflict is found. again zero is written. Were the circuit of Figure 15-8 to use the same I/O bus as the SSN part. the master goes the same way as before but deciding oppositely at a lower conflicting position. At this point. as illustrated in Figure 15-7. At the end of each ROM Search process. the Search ROM procedure would have to be executed and the ROM address of each part stored in EEPROM memory. The next pass is the same as the previous pass up to the point of the last decision. If the part having a one in this second mismatch position is taken. The additional circuitry is shown in Figure 15-8 with the time chip drawing power directly from the Qwik&Low coin cell. the determination of each ROM address amounts to tracing out each branch of a tree having 64 bits in it.” 15. For more than three 1-wire parts connected to the 1-wire bus. the path to select one of the first two chips will include a second mismatch. The DS2415 time chip has the following features: • It draws a maximum of 0. • By being continuously powered. With just one 1-wire device on the bus of Figure 15-8.c) Power switch VDD DS2415 Time chip 4 VBAT 3V + coin cell 5 kΩ 1-wire 2 MCU RA5 (power switching) RA4 6 32768 Hz crystal 5 X2 X1 VDD GND 3 1 0. its counter can be employed as a real-time clock. the DS2415 responds to just the two commands shown in Figure 15-9: Write Clock Read Clock (0x99) (0x66) . unfortunately when the power switch is opened. accumulating 136 years of seconds before rolling over. Although it would seem that the pull-up resistor could be powered directly from the coin cell. the message protocol of Figure 15-9 begins with the Reset pulse/Presence pulse sequence.25 µA with its oscillator incrementing an internal settable and readable 32-bit counter every second. This is followed by the Skip ROM (0xCC) command so that all subsequent I/O interactions will be responded to by that chip. Once selected by the Skip ROM command.1 µF GND FIGURE 15-8 DS2415 1-wire time chip connections and RA4 selected from Figure 3-7) can be used. the pull-up resistor voltage will exceed the MCU’s VDD voltage of 0 V and will lead to a constant current drain of 3 V/5 kΩ = 600 µA.216 Chapter 15 1-Wire Interface (SSN. The read sequence of Figure 15-9b is responded to as follows: • When the Read Clock command has been received. the write sequence of Figure 15-9a produces the following actions: • The reception of the control byte immediately starts (0x0C) or stops (0x00) the DS2415 oscillator.6.8 DS2415 1-Wire Time Chip 217 Line idle Reset pulse Presence Skip pulse ROM Write Control clock byte LSB Counter MSB : Start oscillator : Stop oscillator Reset pulse Line idle (a) Write sequence Line idle Reset pulse Presence Skip pulse ROM Read Control clock byte LSB Counter MSB : Oscillator is running : Oscillator is stopped Line idle (b) Read sequence FIGURE 15-9 DS2415 write and read message sequences.Section 15. or received. not the counter itself. repeatedly read. Add repeated reads of the DS2401 every second to the T3. . the 32-bit counter is copied into the buffer. to control the oscillator and set the counter. (Each byte is sent. • The final reset pulse transfers the buffer to the counter. a) Execute your resulting code. interrupts can occur during a 1-wire transfer without corrupting the transfer if interrupts are disabled during each bit transfer and enabled momentarily between successive bit transfers. PROBLEMS 15-1 Interrupts and 1-wire devices As pointed out in Section 15. • The next 5 bytes received are the control byte followed by the 4-byte counter content. • The 4 bytes destined for the counter are received least-significant-byte first and are loaded into a buffer. Does the serial number. least significant bit first) Thus. ever get corrupted? Explain.c template file that uses both Timer1 and Timer3 for interrupts. DeltaDays. ever get corrupted? Explain. that displays. // and quickly reenable lines appropriately placed. add one or two Nop macros between an enable and a following disable.TMR3IE = 1. Compare what you get relative to what the SSN. ever get corrupted? If so.TMR3IE = 0. Thereafter.01 day and a range up to 9. repeatedly read. to ensure the momentary enabling of the Timer3 interrupts.7 to keep the DS2401 chip enabled for the first 55 bits of its serial number. again send each of the remaining 8 bits read via the Search ROM 3-bit-time procedure back to the PC for display. // Disable Timer3 interrupts and PIE2bits. the difference TIMEEND − TIMESTART . TIME.c program produces.99 days.6. send the complement of the found bit both to the PC and the DS2401. as suggested in Section 15. that will take the number read back into the unsigned long variable. c) Modify the SendByte and ReadByte functions in the code for Part (b) with PIE2bits. as an ASCII-coded one or zero. Days. Now does the serial number. Explain what you find including any need for N intervening Nop macros. Send a space character (0x20) after every group of eight characters sent to the PC. Does the serial number.999. TIME = (60×60×24×51) + (60×60×24×. Explain the result. For the 56th bit.16) = 4406400 + 13824 = 4420224 seconds then the LCD display should show 0051. and convert it to an LCD display of days.16 b) Write a second function.c) b) Add Delay (50) to your HighPriorityISR so that you are introducing a 500-µs pause every 4 ms. in the same format. repeatedly read. send it back to the PC for display. 15-2 Search ROM command Use the Search ROM command of Section 15. 15-3 DS2415 time chip Assume that the DS2415 was cleared to zero and started counting many days ago. with a resolution of 0. As each bit is determined. a) Write a function.218 Chapter 15 1-Wire Interface (SSN. This chapter will begin with a discussion of how a multiplexed LCD display works. A 14-segment coding represents each of the 8 characters. Then. It has 36 pins to control 32 × 4 = 128 segments.c code will be examined and his use of data structures to sort out the complexities of the chip will be explained.1 OVERVIEW The PIC18LF6390 is the second microcontroller on the Qwik&Low board. dedicated to the very specific role of operating the eight-alphanumeric-character LCD display.c) 16. and the waveforms that its LCD controller must generate. To turn on a segment. a lowfrequency (37 Hz) complex waveform is imposed between the frontplane segment and 219 .Chapter 16 STARBURST DISPLAY (LCD. as shown in Figure 16-2a. Each of the 16 segments associated with a character position is controlled by a conductive segment on the front of the display and an identically shaped conductive segment on the back of the display. with liquid-crystal material sandwiched in between. Alex Singh’s LCD. 16.2 STARBURST DISPLAY CONFIGURATION The eight-alphanumeric-character starburst display is shown in Figure 16-1. Also associated with each character are an apostrophe segment and a decimal point segment. c) FIGURE 16-1 Starburst display (Varitronix) the backplane segment. B. For example. the ¼ multiplexing used by the Qwik&Low LCD is supported by complex waveforms for which each period is made up of stairstep values of 0 V. The liquid-crystal medium must draw a distinction between an RMS “on” voltage of 1. This is a drawback of using a display with only 36 pins and an LCD controller chip designed to drive it while drawing a miniscule current of just a few microamperes. C and P for the character in POSITION 1. and a single backplane driver are brought out to 24 pins. on the back of the display. regardless of the viewing angle. The result is a display with a strong sensitivity to viewing angle. the SEG0 pin is connected to segments A.220 Chapter 16 Starburst Display (LCD. The job of controlling LCD segments is simplified for a nonmultiplexed display such as a three-digit. C. Its RMS value must be above a threshold specific to the liquidcrystal medium. to turn off a segment. The Qwik&Low board’s LCD is designed to be viewed from the 6:00 o’clock position that results when the board sits flat on the workstation in front of a user. the RMS value between the frontplane segment and the backplane segment must be below a specified threshold. to just one of the four segments associated with each frontplane SEGi pin. the liquid-crystal medium must only distinguish between 0 V and 3 V. and 3 V. The result is a display with a sharp distinction between on and off segments. An “off” segment has the same waveform applied to its frontplane (for an RMS value of 0 V across the liquid-crystal medium for that segment). Each backplane COMj pin is connected. SEG4 is connected to segments A. and P (the decimal point) for the character in POSITION 0 (the left-most character position of the display). The characters fade as the viewing angle approaches the straight on position or is moved to either side. 1 V. Returning to Figure 16-2b. A lowfrequency squarewave between VDD and GND is applied to the entire backplane. for VDD = 3 V.00 V.73 V and an RMS “off ” voltage of 1. it is a controlling factor for 8 (characters) × 4 (segment pins per character) = 32 segments . Thus. each frontplane SEGi pin is connected to four segments. Correspondingly. 2 decimal points. B. Its 7 × 3 = 21 digit segments. Thus. seven-segment numeric display. 2 V. as will be discussed shortly. An “on” segment has the inverted squarewave applied to its front plane (for an RMS value of VDD volts). In contrast. It connects power and SPI inputs from the MCU .Section 16.3 LCD Controller Circuit 221 SEG2 SEG0 SEG6 SEG4 X COM0 F COM1 G COM2 E COM3 H A X H A I J K B F I J B ••• G K L M N C E L M N C D P D P SEG1 SEG3 SEG5 SEG7 Position 1 Position 0 (left-most character) (a) Segment coding SEG0 SEG2 SEG1 SEG3 SEG4 SEG6 SEG5 SEG7 COM0 COM1 COM2 COM3 A B C P X F E D H G L M I J K N A B C P X F E D H G L M I J K N ••• Position 0 Position 1 (b) Connections for frontplane SEG drivers and backplane COM drivers FIGURE 16-2 Starburst display configuration 16. push-to-break switch. The circuit employs a four-pole-double-throw (4PDT) push-to-make. Omitted in this figure are the LCD PICkit 2 connections for programming the chip as well as seven 0. in Figure 16-3.1 µF bypass capacitors. in simplified form.3 LCD CONTROLLER CIRCUIT The LCD controller circuit is shown. If this were not done. alternatively. The latter condition is used to clarify the current draw by Qwik&Low circuitry independent of the LCD current draw.222 Chapter 16 Starburst Display (LCD. 153–1113 $2. The three pins that control the use of the Serial Peripheral Interface (SPI) for updating the display from the MCU are also disconnected from the MCU when the LCD controller is powered down.92 20 19 18 17 VDD (3 V) COM0 COM1 COM0 COM1 COM2 COM3 GND VDD Microchip MCU PIC18LF4321 475 kΩ LCDbias2 (2 V) LCDbias1 (1 V) 475 kΩ GND TP11 FOSC/4 FOSC/4 TP10 INT0 COM2 COM3 SEG0 SEG1 SEG2 58 55 54 53 52 51 • • • 35 1 36 2 33 3 SEG0 SEG1 SEG2 SEG3 SEG4 SEG5 RD5 INT0 TP9 SCK SCK SCK TP8 SDI SDO SDI TP7 6390 RC7 RC7 SEG31 SEG3 SEG4 SEG5 59 16 SEG31 FIGURE 16-3 LCD controller circuit (simplified) to the LCD controller or. measured in milliamperes. It is also used to measure the small increase in current draw when the LCD current is added into that drawn for a Qwik&Low application. it breaks these connections to power down the LCD. through .35) 63 62 61 60 Varitronix VIM-878-DP-FC-S-LV Digi-Key No. any MCU operation that left any of these outputs high would produce a leakage current.c) Qwik&Low power GND VDD 4PDT switch Switched Power 475 kΩ Microchip LCD controller PIC18LF6390 ($3. The ±3 V difference across the liquid-crystal medium for the first two-eighths of the frame produces a large change in the resulting RMS voltage to 1. b. Referring to Figure 16-2b. as calculated in parts d. However. this voltage is seen by the "A". and f of Figure 16-5 form the RMS value of the waveform by first squaring each section (part d) and finding the mean value of the squared waveform (part e). the LCD controller offers two other test points. and COM3 stairstepped waveforms are shown in Figure 16-4. Figure 16-6a. each waveform rises to 2 V during the first half of the quarter frame and drops to 1 V during the second half. Parts d. It can be used to monitor conditions or measure time intervals introduced if modifications are made to the LCD. It supports four distinct serial input modes for accepting new display data.73 V. a long-term exposure to DC will turn the medium dark and no longer useful as a display. 16. COM1. and f. In addition to the three test points for monitoring Serial Peripheral Interface transfers. In addition to the 64-pin PIC18LF6390 part. Note how each waveform selects a quarter frame by first dropping to 0 V and then rising to 3 V during the second half of the selected quarter frame. . e. e. Figure 16-5b shows the waveform that the LCD controller uses to drive the backplane COM0 pin. labeled on the back of the Qwik&Low board as TP7 (6390 RC7). there is an otherwise identical 80-pin PIC18LF8390 that can control up to 4 × 48 = 192 LCD segments (half again as many as the 64-pin part). the COM0. and "I" segments of the eight starburst characters. An LCD can tolerate brief moments of DC without apparent ill effect. TP11 (FOSC/4) is used to monitor how long it takes the LCD controller to respond to new SPI data and to format the characters received for display into the chip’s LCD registers before going back to sleep. "X". It can control nonmultiplexed LCDs as well as 1/2-. With the refresh rate initialized to 37 Hz. and c show the waveforms seen when the same “A” or “X” or “H” or “I” segment of one of the eight starburst characters is turned on. "H". This is important to the longevity of the medium. With its LCD control registers initialized for 1/4-multiplexed operation. and 1/4-multiplexed LCDs. 1. each frame is repeated every 1/37 s. the normal state of the LCD controller’s CPU.4 Multiplexed LCD Voltage Waveforms 223 the overvoltage protection diodes on the LCD controller inputs to the grounded VDD pin on the LCD controller.Section 16. Figure 16-5c shows the voltage waveform responded to by the liquid-crystal medium. During the remaining three-quarter frames.c file employed by the LCD controller. COM2.4 MULTIPLEXED LCD VOLTAGE WAVEFORMS The PIC18LF6390 is designed for versatility in its role as an LCD controller. Now consider Figure 16-5a that shows the waveform that the LCD controller will use to drive one of the SEGj pins for which all four segments are turned off. provides a user-defined flag. Another pin. 1/3-. The RMS value of the waveform (part f) is the square root of this mean value.00 V in this case. Note that neither voltage waveform across the liquid-crystal medium (Figures 16-5c and 16-6c) has a DC component. To do this. each ASCII-coded character sent to it must be converted to its 14-segment representation. For example. the lower 4 bits) of . the segments for POSITION 0 (the left-most character) must be stored in the lower nibble (i..e.224 Chapter 16 Starburst Display (LCD.5 LCDDATAi REGISTER USE The PIC18LF6390 refreshes the display automatically while its CPU sleeps.c) One frame 3V Backplane 2V COM0 driver selects first quarter frame 1 V 0V One frame 3V Backplane 2V COM1 driver selects second quarter frame 1 V 0V One frame 3V Backplane 2V COM2 driver selects third quarter frame 1 V 0V One frame 3V Backplane 2V COM3 driver selects fourth quarter frame 1 V 0V FIGURE 16-4 Backplane waveforms 16. The result must be broken into four 4-bit parts and stored in half of four 8-bit registers. 00 V FIGURE 16-5 All four segments selected by SEGi are off LCDDATA0 and LCDDATA6 and LCDDATA12 and LCDDATA18 The allocation of the segments for all eight characters is shown in Figure 16-7.Section 16. these 14 bits must be ordered for loading into the LCDDATAi registers of Figure 16-7.6 ASCII CODE TO LCDDATAi REPRESENTATION Each ASCII-coded character must not only be represented by its 14-segment code of Figure 16-2a. In addition. the 8-bit ASCII code is used as an . = = = 1 V2 (1 1 V2 1 V2 + 1 V2 1 1 V2 1 V2 + 1 V2 1 1 V2 + 1 + 1 + 1 + 1 + 1)/8 = 1 V2 1 V2 = 1. 16. To facilitate this loading.6 ASCII Code to LCDDATAi Representation 225 One frame 3V (a) Frontplane segment driver. each table entry consists of the 4 nibbles JGFB IHXA NMDP KLEC packed into the 2 bytes of an unsigned int constant stored in program memory. = = = 9 V2 (9 9 V2 1 V2 + 1 V2 1 1 V2 1 V2 + 1 V2 1 1 V2 + 9 + 1 + 1 + 1 + 1)/8 = 3 V2 3 V2 = 1.73 V FIGURE 16-6 RMS voltage across a selected turned-on segment offset into the table of 256 2-byte entries shown in Figure 16-8.c file of Figure 16-13 will unpack the nibbles for each character to be displayed and load them into the appropriate LCDDATAi registers.c) One frame 3V (a) Frontplane segment driver. As shown by the comment at the beginning of this table. .226 Chapter 16 Starburst Display (LCD. The LCD. 6 LCDDATA6.5 LCDDATA21.6 LCDDATA12.5 LCDDATA8.6 LCDDATA15.5 LCDDATA14.4 LCDDATA7.4 LCDDATA2.4 LCDDATA18.7 LCDDATA7.5 LCDDATA13.7 LCDDATA3.2 LCDDATA15.7 LCDDATA13.6 LCDDATA3.4 LCDDATA0.6 LCDDATA19.7 LCDDATA15.0 LCDDATA6.3 LCDDATA13.2 LCDDATA21.7 FIGURE 16-7 Allocation of starburst segment bits to PIC18LF6390 registers Segment P D M N P D M N P D M N P D M N P D M N P D M N P D M N P D M N .6 LCDDATA14.0 LCDDATA14.5 LCDDATA12.0 LCDDATA2.0 LCDDATA18.4 LCDDATA9.1 LCDDATA9.4 LCDDATA13.7 A X H I A X H I A X H I A X H I A X H I A X H I A X H I A X H I LCDDATA6.3 LCDDATA6.6 LCDDATA1.2 LCDDATA7.4 LCDDATA20.5 LCDDATA6.6 LCDDATA13.7 C E L K C E L K C E L K C E L K C E L K C E L K C E L K C E L K LCDDATA18.2 LCDDATA12.0 LCDDATA8.5 LCDDATA9.1 LCDDATA0.4 LCDDATA19.2 LCDDATA13.6 ASCII Code to LCDDATAi Representation 227 COM0 Bit address COM1 Bit address COM2 Bit address COM3 Bit address POSITION LCD Pin Segment Segment Segment Segment 35 SEG0 0 1 SEG1 36 SEG2 2 SEG3 33 SEG4 1 3 SEG5 34 SEG6 4 SEG7 31 SEG8 2 5 SEG9 32 SEG10 6 SEG11 29 SEG12 3 7 SEG13 30 SEG14 8 SEG15 27 SEG16 4 9 SEG17 28 SEG18 10 SEG19 25 SEG20 5 11 SEG21 26 SEG22 12 SEG23 23 SEG24 6 13 SEG25 24 SEG26 14 SEG27 21 SEG28 7 15 SEG29 22 SEG30 16 SEG31 LCDDATA0.2 LCDDATA19.0 LCDDATA13.1 LCDDATA12.3 LCDDATA2.Section 16.0 LCDDATA3.4 LCDDATA14.1 LCDDATA19.7 LCDDATA1.2 LCDDATA1.4 LCDDATA15.2 LCDDATA6.1 LCDDATA3.7 LCDDATA2.6 LCDDATA8.4 LCDDATA8.2 LCDDATA8.6 LCDDATA2.1 LCDDATA7.0 LCDDATA7.7 LCDDATA9.0 LCDDATA21.5 LCDDATA19.2 LCDDATA2.5 LCDDATA7.7 LCDDATA20.2 LCDDATA0.7 B F G J B F G J B F G J B F G J B F G J B F G J B F G J B F G J LCDDATA12.3 LCDDATA8.6 LCDDATA9.5 LCDDATA18.0 LCDDATA9.3 LCDDATA15.4 LCDDATA6.1 LCDDATA6.2 LCDDATA3.1 LCDDATA13.6 LCDDATA18.3 LCDDATA18.7 LCDDATA14.3 LCDDATA1.1 LCDDATA2.6 LCDDATA0.3 LCDDATA9.1 LCDDATA15.4 LCDDATA21.7 LCDDATA19.2 LCDDATA14.3 LCDDATA3.4 LCDDATA1.0 LCDDATA19.5 LCDDATA3.0 LCDDATA15.1 LCDDATA8.1 LCDDATA14.6 LCDDATA20.0 LCDDATA12.5 LCDDATA0.3 LCDDATA14.5 LCDDATA1.5 LCDDATA15.7 LCDDATA21.4 LCDDATA3.0 LCDDATA1.1 LCDDATA18.6 LCDDATA7.3 LCDDATA19.5 LCDDATA2.2 LCDDATA20.6 LCDDATA21.5 LCDDATA20.7 LCDDATA8.1 LCDDATA21.2 LCDDATA9.1 LCDDATA1.3 LCDDATA12.3 LCDDATA0.3 LCDDATA20.1 LCDDATA20.0 LCDDATA0.2 LCDDATA18.0 LCDDATA20.3 LCDDATA7.3 LCDDATA21.4 LCDDATA12. 0x0002. 0x0200./ 0x1129.&. 1 0xffff. // ASCII column 0xffff. 0xffff.K L.Y.E.A. 0xffff. 0x3087.C D. 0x0040. // ASCII column 0x0000. 0xffff. 0x4848.J. 0x3023. 0x8000. 0x8124. 0xffff. 0x3483. 0xb137. // P.c) // Table-entry coding of segments: const rom unsigned int ASCII[] = { // ASCII column 0 0x0100. their // performance verification program 0xffff.# // $. J G F B I H X A N M D P K L E C // Chris Bruhn's and Peter Ralston's // modification for PV. 0xcedc. 0xe082. 0xffff. 0xb137.7 8. 0x4008. FIGURE 16-8 ASCII Table . <. 0xa006.K L. 0xffff. 0x612b.R. 0xffff. 0x0200. . 0x0940. 3 0x512a. 0x8440.*. 0x8080. . 0x2000. 0x3087. . 0xffff. 7 0x718a.^. 0x2022. 0x0084. 0x6102.M. 0xffff. 0x0020. 0x8140. 0x212b.G H. 6 0x1969. 2 0xffff.= >. 0x8004. 0x0960.C D. 0x1000. 0x6102. // blank. 0x7009. 0x0404. 0x7129. 0x8484.N. 0x0001.U. 0x4028. 0x3023.F.2. 0x712b.+ // . 0xa006. 0x0080.I.S // T.O 0x6129.6.5. 0xffff. 0x31a3. .I.Q. 0x8080. 0xffff. 0x1961. 0xe082. // // // // 0. 0x0008. 0xffff. 0x0400.W // X.!. // ASCII column 0xb127.A. // ASCII column 0x710a. 0x8484. 0xc48c. // .M.J. // ASCII column 0xffff. 0xffff. 0x1023. 0x0010. 0x2122. 0x31a3. // ASCII column 0x710a. 0xffff.0. 0xffff. 0x3123. 0x1001. 0xb403.Q. 0x3483.9. 0xffff. 0x0940. // P. 0x710b. 0x710b. // // // // @.O 0x6129.".V. 0x1023. 0x0960. 0xffff. 0x6122. 0x7108.3 4. // ASCII column 0xffff. 0x0004.228 Chapter 16 Starburst Display (LCD.-. 0x0800.Y.1. // // // // @. 0xffff. 0xffff.' // (.N.Z. 0x6122.V.Z. 5 0x718a.F.). 0xffff. 0x1961.U.R. 0x0000. }. 0x2022.? 0x2122. 0xffff. 0x4000.B. 0x3123.B. 0xffff.G H. // . 0x8440. 0xffff.S // T. 0xffff. 0x0000.%. 0x212b. 0x8124.W // X. 0x700b. // CB and PR again 0x0480. 4 0x1969. 0x0404. 0xb403.E.c. 0x6129. 0x700b. 0xffff. Section 16. a user sends fewer than 9 bytes. If. // Get character and put into string } DisplayV(). However as used in the LCD. However. it is loaded into the variable string. stacking the program counter and vectoring to an interrupt service routine). When the CPU is awakened by the INT0 input edge. // Clear wake up flag TMR0L = 0. // Reset breakout timer INTCONbits. which is left disabled. to break out of the loop that awaits the reception of bytes that actually were void main() { Initial().7 AWAKENING VERSUS INTERRUPT VECTORING The LCD controller expects to be awakened by a falling edge applied to its INT0 input.TMR0IF) { break. Timer0 is used as a breakout timer. When all 9 bytes have been received. the CPU simply executes the instruction that follows the Sleep macro. As each byte is received.SSPIF) && (!INTCONbits. This external interrupt in the PIC18LF6390 is identical in operation to the INT0 input in the PIC18LF4321. the DisplayV function translates each ASCII-coded byte and loads the resulting nibbles into the appropriate LCDDATAi registers.TMR0IF)) .e. RECEIVED++) // Receive 9 chars { PIR1bits. it expects to receive 9 bytes over the Serial Peripheral Interface. on the other hand.TMR0IF = 0.SSPIF = 0.c is broken out to Figure 16-9. // Clear breakout timer flag for (RECEIVED = 0. GIE. RECEIVED < 9. VSTRING. CHAR = SSPBUF.8 Reception of SPI Bytes into VSTRING 229 16. // Clear SPI flag // Wait limited amount of time for character while ((!PIR1bits.INT0IF = 0. The effect of the falling edge occurring on the INT0 pin when the chip is asleep and GIE = 0 is to awaken the chip. // Clear buffer initially INTCONbits. instead of the normal interrupt response (i. 16. } VSTRING[RECEIVED] = SSPBUF. the interrupt mechanism is initialized all the way up to the global interrupt enable bit.c code of Figure 16-13. // Initialize everything while (1) { Sleep(). Nop(). } } FIGURE 16-9 Main loop .. if (INTCONbits.8 RECEPTION OF SPI BYTES INTO VSTRING The main loop of LCD. .nHH Lower nibble of LCDDATA12 = LCDDATA.nLL Lower nibble of LCDDATA18 = LCDDATA. LCDDATA is the name of a data structure in RAM.nHL Lower nibble of LCDDATA6 = LCDDATA.nLH (i. displays what it has received. If this next byte represents a decimal point. From Figure 16-7.. Rather than wait indefinitely with the (FOSC = 8 MHz) clock drawing its relatively heavy current. . The lowest address for POSITION 2 and POSITION 3 is the address of LCDDATA1. the WriteCharacter function first copies the character into LCDDATA. DisplayV normally displays each received byte in each successive position of the display.c) not sent. given the source of the nibbles from Figure 16-10: Lower nibble of LCDDATA0 = LCDDATA. the CPU stops waiting. and returns to sleep. it also looks ahead to the next byte in VSTRING. the RAM nibbles will be written to the lower nibble or upper nibble of the selected register. KLEC) (i. JGFB) (i.10 DATA STRUCTURES To access the 4 nibbles of a selected ASCII table entry. where the nibbles for the ASCII table entry must be sent to display that character in a certain character position. Instead. The assigning of these members is shown in Figure 16-10c. When WriteCharacter handles the byte in CHAR.c simply takes up an entire character position to display an apostrophe. etc. six parts of which have been assigned the members shown in Figure 16-10b.5..9 DECIMAL POINT The reception of (the ASCII representation of) a decimal point into VSTRING must be treated differently from the reception of any other character. 16. it can be seen that the lowest address for POSITION 0 and POSITION 1 is the address of LCDDATA0.e. For example. However.e. Alex Singh has created another data structure with members identifying the nibble locations in the registers of Figure 16-7. Then.ALL as shown in Figure 16-10a. An apostrophe could also be handled as an exceptional character and packed in with the character it follows. DisplayV sets DPFLAG and increments past the decimal point.e. it also sets the bit for that character’s decimal point. DisplayV not only reads a byte from VSTRING into CHAR. NMDP) The data structure is set up so that a pointer can be used to identify the lowest of the four addresses. IHXA) (i. In similar fashion. as discussed earlier in Section 5.e. LCD.230 Chapter 16 Starburst Display (LCD. the 4 nibbles associated with the character to be displayed in the left-most character position (POSITION 0 of Figure 16-7) must be written as follows. 16. depending on whether POSITION is even or odd.. FIGURE 16-10 ASCII table entry members Figure 16-11 lists the actual addresses of the LCDDATAi registers. forms the pointer: ptr = (oneLCDSEG *) (&LCDDATA0 + POSITION / 2).g. LCDDATA union { struct { unsigned int ALL. }. The data structures of Figure 16-12 assign members that will be written to. } LCDDATA. unsigned nLH:4. // To identify entire structure // To identify 4 nibbles for each table entry // To identify the decimal point bit // structure to handle table entries as nibbles (c) Data structure definition to assign members to parts of ASCII table entry.nHL LCDDATA. unsigned P:1. struct { unsigned nLL:4. // Load table entry to be written (a) Reading from table into data structure JGFB LCDDATA P (decimal point bit) LCDDATA nHH IHXA NMDP KLEC . LCDDATA ALL (b) Desired members within the data structure.Section 16. WriteCharacter. unsigned nHL:4. the character location destined to display the character. As the DisplayV function reads an ASCII code from VSTRING into CHAR. it also forms POSITION. the address of LCDDATA1 for Character Number 2).nLL . in turn. once the pointer has been set to point to the first address (e. LCDDATA. }. . struct { unsigned:4.. unsigned nHH:4.10 Data Structures 231 LCDDATA ALL = ASCII [CHAR]. .nLH LCDDATA. }. . 232 Chapter 16 Starburst Display (LCD. char _1byte. _5bytes a. unsigned nBL:4. } _5bytes. LCDDATA18 LCDDATA19 LCDDATA20 LCDDATA21 (a) This structure will be used below to add an offset of five bytes to an address in the oneLCDSEG data structure typedef struct { unsigned nAL:4. unsigned nAH:4.c) Hex address F60 F61 F62 F63 F64 F65 F66 F67 F68 F69 F6A F6B F6C F6D F6E F6F F70 F71 F72 F73 F74 F75 F76 F77 F78 F79 F7A Register name LCDDATA0 LCDDATA1 LCDDATA2 LCDDATA3 +5 LCDDATA6 LCDDATA7 LCDDATA8 LCDDATA9 +10 +5 LCDDATA12 LCDDATA13 LCDDATA14 LCDDATA15 FIGURE 16-11 Actual addresses of LCDDATAi registers typedef struct { long _4bytes. // LCDDATA(x) // LCDDATA(x+6) FIGURE 16-12 Naming LCDDATAi nibbles . unsigned nCH:4.Section 16. * * Because of the quirky translation of the starburst segments ABCDEFGHIJKLMNPX * into their positions in the LCDDATAi registers. Starburst display draws 6 uA. * Thus the letter "K" made up of segments EFGJN is translated into the table * entry db 0xe0. _5bytes b. unsigned nDH:4. // LCDDATA(x+12) // LCDDATA(x+18) (b) oneLCDSEG is a structure that assigns members to LCDDATA. unsigned nCL:4. FIGURE 16-12 (continued) that it uses to write each nibble from the LCDDATA data structure to the nibble of a register with a line exemplified by: ptr→nAL = LCDDATA.0x82 because * 1 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 * * Use Fosc = 8 MHz. _5bytes c. unsigned nDL:4. } oneLCDSEG. _5bytes d.c ***************** * * Display a string received having a length of 9 characters (including * an optional decimal point). /******* LCD.c . the tables showing the coding * for numbers and letters are coded with two-byte table entries in the * following order: * J G F B I H X A N M D P K L E C * where P is the decimal point and X is the apostrophe.nHL. The entire file is listed in Figure 16-13.10 Data Structures 233 unsigned nBH:4. * Developed by Alex Singh. * ******* Program hierarchy ***** * * main * Initial * DisplayV * WriteCharacter * ******************************* */ FIGURE 16-13 LCD. unsigned nDL:4.h> /******************************* * Assembler directives ******************************* */ #pragma #pragma #pragma #pragma #pragma #pragma #pragma config config config config config config config OSC = INTIO7 WDT = OFF PWRT = ON MCLRE = ON XINST = OFF BOREN = ON BORV = 3 // // // // // // // Internal osc. } oneLCDSEG. typedef struct { unsigned nAL:4.234 Chapter 16 Starburst Display (LCD. nominal /******************************* * Structure definitions ******************************* */ // Structures to map LCDDATA (as nibbles) typedef struct { long _4bytes. RA7=I/O WDT disabled (control through SWDTEN bit) PWRT enabled MCLR pin enabled. _5bytes d. RA6=CLKO. unsigned nCH:4. unsigned nDH:4. RG5 input pin disabled Instruction set extension disabled Brown-out controlled by software Brown-out voltage set for 2. unsigned nBH:4. _5bytes c.c) #include <p18f6390. /******************************* * Global variables ******************************* */ union { struct // LCDDATA(x) // LCDDATA(x+6) // LCDDATA(x+12) // LCDDATA(x+18) FIGURE 16-13 (continued) . } _5bytes. char _1byte.0V. unsigned nBL:4. unsigned nAH:4. unsigned nCL:4. _5bytes a. _5bytes b. }. }. } LCDDATA. /******************************* * Constant strings ******************************* */ // Table-entry coding of segments: const rom unsigned int ASCII[] = { // ASCII column 0x0100. 0x1000. oneLCDSEG *ptr. // CB and PR again FIGURE 16-13 (continued) . char *CLEARptr. unsigned char POSITION. // Chris Bruhn's and Peter Ralston's // modification for PV. }. 0xffff. 0xffff. 0x0040. unsigned char CHAR. unsigned int j. 0x0200.Section 16. 0xffff. unsigned nLH:4. 0xffff. 0x0400. unsigned int DELAY. 0xffff. 0x0010. 0x0004. 0x0002. 0xffff. 0xffff. 0x2000. 0xcedc. 0x0080. 1 0xffff. 0x8000. their // performance verification program 0xffff. struct { unsigned:4. unsigned P:1.c. 0xffff. unsigned char i. 0x4000.10 Data Structures 235 { unsigned int ALL. unsigned int RECEIVED. J G F B I H X A N M D P K L E C 0x0020. 0xffff. // ASCII column 0xffff. 0xffff. 0 0x0001. // To identify entire structure // To identify 4 nibbles for each table entry // To identify the decimal point bit // Structure to handle table entries as // nibbles // // // // // // // // // // Flag to handle a received decimal point ASCII character from string LCD character position (0 to 7) Used as index for loops and VSTRING Sixteen-bit counter for obtaining a delay Used for delay in Initial Used to keep track of characters received Pointer that maps to our LCD nibbles Pointer used to clear all LCDDATA Variable string to display char DPFLAG. struct { unsigned nLL:4. unsigned nHH:4. 0xffff. unsigned nHL:4. 0x0800. 0xffff. 0x0008. unsigned char VSTRING[10]. ". 0x212b. 0xffff. 0xffff. 0x0960. 0xa006. void WriteCharacter(void). }. 0x3023. 0xffff. 0x3087. 0xa006. 7 0x718a.2.I. . 0x0000. 0x31a3.A.G H. 0x6102. // ASCII column 0x710a. 0x0940.= >.E. // // // // @./ 0x1129. 5 0x718a. 0x1961. 0xffff.S T.M.9. 0x2022. 0xffff. 0x710b.V.5.F. 0x0200. <.!. 0x3123.Q.C D.O 0x6129. 0x712b. 0x4028.c) // ASCII column 0x0000. 0xb403. 0x4008. 0x700b. 6 0x1969.F.%.6. 0x0960. 0x4848.S T. // ASCII column 0xffff. 0x31a3. . // // // // P. 0x7009.3 4. 0x7108. 0x0084. 0x8140. 0x3087. 2 0xffff.E. 0x8080.+ .0. 0x1023.' (. 0xe082. 0xffff.I. 0xffff.Y.N. 0x8484. 0xb137. 0x8484. 0xffff.B.-. 0x6129. 0x6122. 0x0404.# $.7 8. 0xffff. 0x3023. 0x8004. // ASCII column 0xb127. 0xe082.K L. 0x212b.W X.M. .236 Chapter 16 Starburst Display (LCD. void DisplayV(void). 0x1961. 0xb403.Z .Q. 3 0x512a. 0x0940.G H. 0x8124. 0x1023.).U.J. 0x8440. // // // // @.Y. 0x0404. 0x0480. 0x6122. .&.C D.? 0x2122. 0x700b. 0x612b.J. 0x2122.B. 0x7129. 0x3483.A. // // // // 0. 0xc48c. /******************************* * Variable strings ******************************* */ /******************************* * Function prototypes ******************************* */ void Initial(void). 0x6102. 0xffff. 0x8124. 0x1001.R. // // // // blank. 0xb137.O 0x6129.N.*. 0x3483. // ASCII column 0xffff.^. FIGURE 16-13 (continued) .U. 0xffff. // // // // P. 0x8080. 0x2022. 4 0x1969.Z .K L.V. 0xffff. 0xffff.1. 0x8440. 0x0000. // ASCII column 0x710a. 0x710b. 0x3123.W X.R. // Clear breakout timer flag for (RECEIVED = 0. } /******************************* * main() ******************************* */ void main() { Initial().TMR0IF)) . while(--DELAY){ Nop(). LCDSE3 = 0b11111111. // Clear SPI flag // Wait limited amount of time for character while ((!PIR1bits. // Initialize everything while (1) { Sleep(). RECEIVED < 9. // Select 8 MHz internal oscillator // Enable all LCD segments // 1/4 mux. LCDSE2 = 0b11111111. Nop(). INTRC clock FIGURE 16-13 (continued) .SSPIF) && (!INTCONbits. LCDSE0 = 0b11111111. // Get character and put into string } DisplayV().INT0IF = 0. // Clear buffer initially INTCONbits. RECEIVED++) // Receive 9 chars { PIR1bits. CHAR = SSPBUF.10 Data Structures 237 /******************************* * Macros ******************************* */ #define Delay(x) DELAY = x. } VSTRING[RECEIVED] = SSPBUF. LCDSE1 = 0b11111111. } } /******************************* * Initial() * * This subroutine performs all initializations of variables and registers.SSPIF = 0.TMR0IF = 0. Nop(). ******************************* */ void Initial() { OSCCON = 0b01110010.Section 16. // Reset breakout timer INTCONbits. if (INTCONbits.TMR0IF) { break. LCDCON = 0b10001011. // Clear wake up flag TMR0L = 0. } LCDDATA21 = 0b00010000.INT0IE = 1. i++) // { *CLEARptr++ = 0x00. i < RECEIVED. i++. // // Don't enable interrupt. // TRISB = 0b00000001. // TRISA = 0. // and increment pointer past decimal point } WriteCharacter().INT0IF = 0. // ADCON1 = 0b00111111.') // Deal with decimal point { // Check next character for decimal point DPFLAG = 1. // Display current character } } FIGURE 16-13 (continued) . set flag i++. // INTCON2bits. PORTA = 0. TRISC = 0b00011000. POSITION++) { CHAR = VSTRING[i].SBOREN = 0. SSPCON1 = 0b00110101. // SSPSTAT = 0b00000000. // CLEARptr = (char *) &LCDDATA0.238 Chapter 16 Starburst Display (LCD. Delay(30000). i < 28. only DPFLAG = 0. SCK. // Save byte if (VSTRING[i + 1] == '.INTEDG0 = 0. // INTCONbits. // } 37 Hz frame frequency // Point to first segment Turn off all segments Turn on rightmost decimal point initially Make all ADC/IO pins digital Make all pins outputs but RB0. PORTB = 0. // INTCONbits. POSITION = 0. // If it is. SDI Initialize SPI as slave Use Timer0 to timeout on incomplete input Wake up with falling edge on INT0 Clear flag Enable INT0 source wakeup Initial delay is 300/2 milliseconds Now disable brownout reset /******************************* * DisplayV() * * This subroutine displays the string stored in VSTRING ******************************* */ void DisplayV() { // Iterate through all received for (i = 0. PORTC = 0. for (i = 0. // RCONbits. T0CON = 0b11000011.c) LCDPS = 0b00110110. 100-mil-spaced header to bridge between the programmer’s 6-pin female output and the Qwik&Low board’s unpopulated H5 “LCD PICkit 2” header.nLL. ptr->nDL = LCDDATA. .10 Data Structures 239 /******************************* * WriteCharacter() * * This subroutine writes the selected character to the display ******************************* */ void WriteCharacter() { LCDDATA.c code with the same c18.c code to set RC7 before the call of WriteCharacter in DisplayV and to clear RC7 on the return from WriteCharacter. ptr->nDH = LCDDATA.exe utility used to compile the code for the PIC18LF4321.nHL. ptr->nCH = LCDDATA. Note the message produced by this utility indicating its recognition (and acceptance) of this code for the PIC18LF6390 LCD controller chip. ptr->nCL = LCDDATA. // write to lower nibbles ptr->nBL = LCDDATA.ALL = ASCII[CHAR].nHL. // Load table entry to be written // Ppoint to corresponding LCDDATAs ptr = (oneLCDSEG *) (&LCDDATA0 + POSITION / 2). // and clear flag } if (!(POSITION % 2)) // If even position { ptr->nAL = LCDDATA. // write to upper nibbles ptr->nBH = LCDDATA.nLH.P = 1. } } FIGURE 16-13 (continued) PROBLEMS 16-1 Algorithm testing This problem requires the availability of a PICkit 2 programmer plus a 6-pin. // Write decimal point DPFLAG = 0.nHH. • Modify the LCD. Compile your modified LCD.nLH.Section 16.nLL. if (DPFLAG) // if FLAG is set { LCDDATA.nHH. } else // If odd position { ptr->nAH = LCDDATA. 240 Chapter 16 Starburst Display (LCD. you already know the effect of the position of the character.. What is this duration? b) Does the duration of WriteCharacter vary with the character code? To test this. or course. not off). and TP11. on.c) • Use the PICkit 2 programming utility (rather than QwikProgram used to program QwikBug into the PIC18LF4321) to program the LCD controller chip. • Monitor test point TP7 with a scope while running MCU code that writes to the LCD display. have the MCU send “AAAAAAAAA” to the display. Now have the MCU send “AOPZ. this switch shorts the LCD controller’s VDD pin to ground. be probed from the front of the board at the pad located below the TP8 label. This test point is labeled on the back of the board below TP8.e. When you do this. TP9. a) Does the duration of WriteCharacter vary with the position of the character on the display? To test this. It can. TP10. Otherwise. as can be seen in Figure 16-3.aopz” to the display. is down or in (i. make sure that SW2. What do you find? . the big 4PDT switch in the center of the board. and thereby take up less CPU awake time. I2C message strings always require the time to send one more (address) byte than a similarly functioning SPI chip would require. The Qwik&Low board is committed to the SPI function because: • Two of the three SPI pins are already committed to communication with the LCD controller. 241 . They must also be individually disabled for SPI transfers that use the same pins.1 OVERVIEW The Serial Peripheral Interface (SPI) facility used by the MCU to send a display string to the LCD controller can also be employed for communication with other peripheral chips to enhance the features of the MCU. These resistors present a large current draw during I2C transfers. • SPI transfers are inherently faster than I2C transfers. This chapter will begin with the clocking options used to match the SPI to another chip’s SPI.Chapter 17 SPI FOR FEATURE ENHANCEMENT 17. The SPI circuitry is part of the PIC18LF4321’s Master Synchronous Serial Port (MSSP) module that supports either SPI or I2C bus transfers. It will end with the use of two peripheral chips. The SPI clock is more than twice as fast as that specified for I2C. • I2C bus use requires a relatively low 2.2-KΩ pull-up resistor for each of its two I2C pins. the AD5601 digital-to-analog (DAC) considered later in this chapter is the SPI counterpart of the AD5602. 17. This is a defining characteristic of the SPI interface. MCU Chip select (general-purpose output) CS Select a specific device SPI Control circuitry SSPIF flag PIR1 SSPBUF Internal shift register SCK (RC3) Serial clock (eight clock pulses are emitted in response to a write to SSPBUF) SDO (RC5) Serial data out (most-significant bit first) (a) Function of pins CS Clear flag SSPIF Write to SSPBUF SCK SDO b7 b6 b5 b4 b3 b2 b1 b0 Flag set upon completion of transfer 8 µs (b) Waveforms FIGURE 17-1 SPI use for serial output . a DAC with an I2C interface and an otherwise identical feature set. Note that the byte that is written to the SSPBUF register is transferred out of the MCU most-significant bit first.242 Chapter 17 SPI for Feature Enhancement • Many peripheral functions available with an I2C interface are also available with an SPI interface. Peripheral chips with an SPI interface are designed to use transferred data in this most-significant-bit-first order. For example.2 SPI OUTPUT FUNCTIONALITY The SPI functioning for transfers to the LCD controller was illustrated in Figure 5-1 and is repeated in Figure 17-1. 2 SPI Output Functionality 243 7 6 5 4 3 2 1 0 0 x x x TRISC x x 0 SCK = output SDO = output SDI/RC4 7 6 5 4 3 2 1 0 SSPCON1 0 0 1 0 0 0 0 SPI clock rate = FOSC/4 CKP . RC4. Changing . if the Figure 17-3b or d choice were made.Section 17. serve a vital role for SPI output transfers.used by SPI inputs. then the initialization of bit 4 of TRISC to zero (as it is initialized in all of the earlier template files) allows the SDI pin to be used as a general-purpose output pin. either Figure 17-b or d will work. CKP selects whether the clock output. On the other hand. see Figure 17-5 7 6 5 4 3 2 1 0 PIR1 SSPIF SSPBUF 1: Transfer completed (must be cleared before transfer) 0: SPI ready to transfer 1: for use by SPI for serial input transfers 0: for use as a general-purpose output SSPSTAT A write to SSPBUF initiates a transfer FIGURE 17-2 SPI registers The registers associated with the SPI module are shown in Figure 17-2.see Figure 17-3 SMP . that device would see a changing. the better choice is the one that does not change CKP from its previous value. then either Figure 17-3a or c will serve. If the device requires each incoming bit to be stable at the time of the rising edge of its SCK input. idles high or low. ambiguous bit on SDO at the time of each rising edge of SCK. These two control bits are initialized before initiating an SPI transfer to a device. either Figure 17-3a or c will work. If the SPI is only being used for output transfers (as it is for the Qwik&Low board without addon parts). The SPI clock rate is controlled by the lower 4 bits of SSPCON1. For a device that requires stable data with the falling edge of the clock. Between the two choices for a device.see Figure 17-3 SSPEN = 1 to enable SPI module Unused in SPI mode 7 6 5 4 3 2 1 0 0 0 0 0 0 0 Unused in SPI mode CKE . For a device that requires stable data with the rising edge of the clock. CKP and CKE. SCK. Two control bits. The 0000 choice shown sets this rate to its maximum value of 1 MHz when FOSC = 4 MHz so that an 8-bit transfer will take just 8 µs. If CKP is changed to zero for an SPI transfer to another device. as indicated by Figure 17-3a. This potential problem never arises if CKP is never changed. For example. that change in CKP will drop the idle SCK line from high to low. That change may clock the other device and produce an inadvertent 9-bit transfer to the device. ignoring the wiggling SCK and SDO lines except when enabled. In the case of the MCU transfers to the LCD controller. this extra input to a device must serve the device in the manner specified in that device’s data sheet. when CKP is changed back to one for the next SPI transfer to the LCD controller.244 Chapter 17 SPI for Feature Enhancement SCK SDO b7 b6 b5 b4 b3 b2 b1 b0 (a) CKP = 1. then this extra edge will be ignored. CKE = 1 SCK SDO b7 b6 b5 b4 b3 b2 b1 b0 (d) CKP = 0. If the LCD controller’s CPU has not yet been awakened by the interrupt input from the MCU (see Figure 5-1a). CKE = 1 SCK SDO b7 b6 b5 b4 b3 b2 b1 b0 (c) CKP = 0. CKE = 0 (selection for transfers to LCD controller) SCK SDO b7 b6 b5 b4 b3 b2 b1 b0 (b) CKP = 1. CKE = 0 FIGURE 17-3 CKP and CKE options for output transfers CKP introduces two extra edges. the LCD controller is sensitive to rising clock edges. an extra rising edge will occur on the SCK input to the LCD controller. On the other hand. . one of which will clock falling-edge-sensitive devices and one of which will clock rising-edge-sensitive devices. Likewise. SPI output transfers to a device generally involve an extra control line in addition to the SCK to SCK connection and the SDO to SDI connection (see Figure 5-1). the extra control line is the MCU’s RD5 pin used to awaken the LCD controller’s CPU with a falling-edge INT0 interrupt. However it is used. less careful dealing with this sequence by first dropping RD5 to wake up the LCD controller’s CPU and then changing CKP will clock a garbage bit into the LCD controller and thereby garble what is received. Some other devices use the extra input as a chip enable. 3 SPI Input Functionality 245 17. after clearing the SSPIF flag in the PIR1 register. with a general-purpose output pin used as specified by the peripheral chip’s data sheet.Section 17.3 SPI INPUT FUNCTIONALITY Reading serial input from an SPI peripheral chip makes use of the three pins of Figure 17-4a. At the same time. The output from this pin may serve as a chip enable. For another chip. MCU Chip select CS Select a specific device SPI Control Circuitry SSPIF flag PIR1 SSPBUF Internal shift register SCK (RC3) Serial clock (eight clock pulses are emitted in responce to a write to SSPBUF) SDI (RC4) Serial data in (most-significant bit first) (SDO) (a) Function of pins CS Clear flag SSPIF Write to SSPBUF SCK Input sampling of SDI pin SDI b7 b6 b5 b4 b3 b2 b1 b0 Flag set upon completion of transfer (b) Example waveforms FIGURE 17-4 SPI use for serial input . taking a tristate SDO output from the peripheral chip out of its high-impedance state so it can drive the MCU’s SDI input. the output from this pin may load a register with the content to be shifted back to the MCU. In any case. whatever the external device presents to the SDI pin is shifted into SSPBUF. a write to the SSPBUF register initiates the shifting of whatever was written to SSPBUF out of the SDO pin. 5 V. as shown in Figure 17-2. 10-bit. SMP = 1 or CKE = 0. SMP = 0 CKE = 0. input transfers are also controlled by an SMP sampling bit. k = 10 for the AD5611. 17. as discussed in the last section. SMP = 1 (b) SDI sampling times for CKP = 0 (for which SCK idles low) FIGURE 17-5 CKP. SMP = 0 CKE = 1. the “chip select” pin to the peripheral chip may load its SPI output register so that the most-significant bit is then sitting on its SDO output and. the use of the CKP = 1. If the peripheral chip is sensitive to rising SCK clock edges. CKE. One of these units can be N 2 . Figure 17-5a shows the three timing alternatives in the case for which CKP = 1. N. The units operate over a supply voltage range of 2. and SMP options for input transfers As in the case of SPI output transfers. to an output voltage VOUT = __ × VDD k where k = 8 for the AD5601. SMP = 1 or CKE = 0. the SCK line will not experience any extra. an SPI input transfer can use any of several timing alternatives. If the input transfer makes use of the same CKP = 1 value used for output transfers to the LCD controller.246 Chapter 17 SPI for Feature Enhancement SCK CKE = 1. SMP = 0 timing choice will have the MCU’s SPI sampling its SDI input before the first shift takes place. For example. In addition to the role of the CKP and CKE control bits. thereby. or 12-bit conversions of an input value. as shown in Figure 17-4b. SMP = 0 CKE = 1.4 AD5601 DAC OUTPUT Analog Devices has a family of three tiny 6-pin nanoDAC digital-to-analog converters for 8-bit.7 V–5. SMP = 1 (a) SDI sampling times for CKP = 1 (for which SCK idles high) SCK CKE = 1. just as desired. SMP = 0 CKE = 0. The alternative sampling time choices are obtained by loading SSPSTAT appropriately. and k = 12 for the AD5621. on the MCU’s SDI input. spurious clock edges that might otherwise throw the input data off by 1-bit time. VDD 2 . The chip’s SPI interface expects to see stable data on its SDI input at the time of the falling edges on its SCK input. it can be connected to the MCU with 30-gauge wirewrap wire soldered between the AD5601 pins and the pins of the H4 terminal strip. The DAC then expects a low→high→low pulse on its SYNC input.RA5 = 0.5 × ____ k For the 12-bit DAC. that is. this is accomplished by PORTAbits. A relative accuracy specification of ±0. with the effect shown in Figure 17-8.RA5 = 1. the output impedance will be • 1 kΩ to ground • 100 kΩ to ground • Three-state (i. CKE is set to one (from its value of zero dictated by the LCD controller’s requirement) as shown in Figure 17-9.e. The resistor stringmultiplexer combination ensures a monotonic output. an output that always increases as the digital input increases.and 10-bit DACs means that the output deviates from a straight line between 0 V and VDD by no more than ±0. even including a typical settling time of 6 µs.5 LSb for the 8.. A block diagram of the DAC is shown in Figure 17-7. essentially open circuit) depending on 2 bits of the int value sent to the chip. the unit typically draws 60 µA.5 Ω. Using the circuit of Figure 17-6. PORTAbits. producing an output with the very low output impedance of 0.65 mm surface-mount pattern located on the back of the board. With the circuit of Figure 17-6. This DAC family exhibits close to ideal specs. This timing dictates the choice of Figure 17-3b. 2 bytes must be sent to the chip over the SPI to load its input register. To control the DAC. one of these units typically draws 40 µA. the specification is relaxed slightly to ±1 LSb. but when sent a standby command.4 AD5601 DAC Output 247 VDD AD5601 MCU RA5 SCK SDO GND 1 2 3 SYNC VOUT SCK SDI GND VDD 6 5 4 VOUT FIGURE 17-6 AD5601 DAC circuit connections soldered to the Qwik&Low board using the 0. the current draw drops to 0. When sent a power-up command to produce an output voltage. At power-on reset. Therefore. before the transfer is initiated.1 µA.Section 17. In standby mode. the DAC will act on the input register contents. It will shift the SDI input into its DAC input register in response to each of these falling edges. writes the upper byte to SSPBUF. as specified in Figure 17-8. The chip uses this pulse to reset. the MCU clears the SSPIF bit. then DACREGL = DACREG & 0x00FF. waits for SSPIF = 1. If DACREG is the 16-bit int variable to be sent to the DAC. It expects this pulse to be followed by 16 falling edges on its SCK input.248 Chapter 17 SPI for Feature Enhancement VDD Multiplexer Operational amplifier follower circuit Resistor string • • • • • • + − VOUT FIGURE 17-7 Block diagram of AD5601 DAC With FOSC = 4 MHz. After setting the CKE bit. or synchronize. clears it again. and pulsing the SYNC input. In response to the 16th falling edge. DACREGH = DACREG >> 8. its SPI interface. and finally clears the CKE bit to leave this bit in its default state for the LCD controller. writes the lower byte to SSPBUF. The sequence of events to update the DAC is shown in Figure 17-9. this sequence will produce a 1-µs pulse. easily meeting the SYNC pulse-width specification of 20-ns minimum. waits for SSPIF = 1. //Form lower byte //Form upper byte forms the two 8-bit unsigned char variables to be written to SSPBUF. . Section 17. The intent was to have an interface that could swap the contents of two 8-bit registers between two devices using the 3-wire interface shown in Figure 17-10. driven by a corresponding slave-select output from the master. each slave has a single (SS) input while the ___ ___ master has one (SS) for each slave.5 MOSI/MISO Terminology 249 b7 b6 b5 b4 b3 b2 b1 b0 x x x x x x 0 0 1 1 0 1 0 1 N Power up. The original intent of the (SS) input was to force a slave’s MISO output to the high-impedance state and to___ a slave from respondkeep ing to activity on the MOSI and SCLK lines unless its (SS) line was driven low by the master for the duration of the transfer. generate output Standby with output of 1 kΩ to ground Standby with output of 100 kΩ to ground Standby with open-cicuit output (a) AD5601 input register (for 8-bit DAC) b9 b8 b7 b6 b5 b4 b3 b2 b1 b0 x N Power up. This MOSI term (and the corresponding MISO term) avoids the naming confusion associated with a line that connects an SDO pin on one chip to an SDI pin on another chip. the SYNC input of the . generate output Standby with output of 1 kΩ to ground Standby with output of 100 kΩ to ground Standby with open-cicuit output (b) AD5611 input register (for 10-bit DAC) b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 b1 b0 x N Power up. slave-in (MOSI) is applied to the line that transmits data from the master (i.e. Present usage employs a more generally defined pin to signal the slave of an impending transfer (e.g. The term master-out.e. the chip that uses its clock pin as a clock input).5 MOSI/MISO TERMINOLOGY The Serial Peripheral Interface was developed many years ago by Motorola. generate output Standby with output of 1 kΩ to ground Standby with output of 100 kΩ to ground Standby with open-cicuit output (c) AD5621 input register (for 12-bit DAC) x x x x 0 0 1 1 0 1 0 1 0 0 1 1 0 1 0 1 FIGURE 17-8 DAC input register 17. ___ A fourth... active-low slave-select (SS) input is also defined for the slave. the chip that drives the clock line) to the slave (i.. For multiple ___ slaves (the configuration being considered in this chapter). 250 CKE SYNC SSPIF Write to SSPBUF SCK 0 First byte sent 0 b7 b6 b5 b4 b3 b2 b1 b0 0 0 0 Second byte sent 0 0 0 SDO Chapter 17 FIGURE 17-9 SPI protocol for 8-bit DAC SPI for Feature Enhancement . and SMP of Figures 17-3 and 17-5 so that data is read by both master and slave half a clock period before data is changed. Each of these modes specifies a combination of CKP.6 ADT7301 SPI TEMPERATURE SENSOR Analog Devices makes an SPI-connected temperature sensor.6 ADT7301 SPI Temperature Sensor 251 SPI master SS SPI slave (SCK) (SDI) SCLK (SCK) (SDO) MISO (SDO) MOSI (most-significant bit first) (SDI) FIGURE 17-10 MOSI/MISO terminology last section or the INT0 input of the LCD controller) in addition to the original role of framing the transfer. CKE. Because the chip powers up into an active mode. Features of the chip. their ADT7301.Section 17. A schematic for connecting this temperature sensor to the MCU is shown in Figure 17-12a. Two parameters are used to define the four modes. either of which can be added to the surface-mount patterns in the lower-right corner of the Qwik&Low board. and SMP that produce each mode. It is available in a 6-pin SOT-23 package or an 8-pin SOIC package. it is important to read the data sheet to determine how the device expects this input to be used. as shown in Figure 17-11: • • • • CPOL = 0 means the clock line idles low (same as CKP = 0) CPOL = 1 means the clock line idles high (same as CKP = 1) CPHA = 0 means sample on the leading clock edge CPHA = 1 means sample on the trailing clock edge The table of Figure 17-11 also lists the values of CKP. drawing almost 200 µA of current. the chip must be initialized by sending it a shutdown command. 17. While the chip’s current as it carries out . The Motorola standard defines four SPI modes. For any device. derived from a translation of Figures 17-3 and 17-5. include a resolution of well less than a tenth of a degree Fahrenheit. listed in Figure 17-12b. CKE. after which current drawn by the chip drops to less than a microampere. 252 Chapter 17 SPI for Feature Enhancement SCLK for CPOL = 0 SCLK for CPOL = 1 MISO & MOSI for CPHA = 0 MISO & MOSI for CPHA = 1 b7 b7 b6 b6 b5 b5 b4 b4 b3 b3 b2 b2 b1 b1 b0 b0 MODE CPOL CPHA 0 1 2 3 0 0 1 1 0 1 0 1 Clock idles low low high high Clock edge upon which data is read rising edge falling edge falling edge rising edge Clock edge upon which data is changed falling edge rising edge rising edge falling edge CKP 0 0 1 1 CKE 1 0 1 0 SMP 0 0 0 0 FIGURE 17-11 SPI mode numbers and correlation to CKP. SMP VDD VDD MCU RB4 SPI (RC3) SCK (RC4) SDI (RC5) SDO GND SCLK MISO MOSI CS VDD ADT7301 SCK SDO SDI FIGURE 17-12 ADT7301 temperature sensor (a) Schematic . CKE. 2 µΑ Figure 17-13a shows the two commands that the chip understands.33 µA + _____ × 190 µA = 2.03125°C 1°C 32°C Output 11 1111 1111 1111 00 0000 0000 0000 00 0000 0000 0001 00 0000 0010 0000 00 0100 0000 0000 (c) Conversion examples FIGURE 17-12 (continued) a conversion is high.2 µA.000 Alternatively. a conversion once per second with the chip otherwise shut down produces an average current draw on the coin cell supply of only 208 _________ × 1. For a temperature above 0°C. The examples of Figure 17-12c illustrate that if the 2-byte result is formed in a signed int variable. typical 208 µs 6-lead SOT-23 or 8-lead SOIC Temperature -0.Section 17.6 ADT7301 SPI Temperature Sensor 253 Supply voltage Accuracy Resolution Operating temperature range Supply current Converting Not converting Shutdown mode Conversion time Package (b) Features +2.5°C from 0°C to 70°C 0. The simultaneous operation of reading out an already converted result and putting the chip in shutdown mode is illustrated in Figure 17-13b. //Temperature in units of 0.000. the average current drawn by the temperature sensor is 0. 10 ms later. typical 0.5V ±0.1 degree . the temperature will be expressed in units of 0. typical 190 µA. Although it is the state of the third bit received that draws the distinction between the shutdown command and the wakeup and convert command. the chip might be sent the serial command to power up and begin a conversion once per second. RAWTEMP.03125°C 0°C +0. the chip requires the reception of all 16 clock edges before the CS pin is raised or it will ignore the command.33 µA 1. If.05625°F -40°C to +150°C 1600 µA. //Temperature in units of degrees 10 1.03125°C.600 = 0. the MCU shuts down the sensor and at the same time retrieves the converted result.000 or TENTHS = (10 ∗ RAWTEMP) >> 5. the Centigrade temperature is expressed as CENTIGRADE = RAWTEMP >> 5.03125°C = 0.7V to 5. 254 CS SSPIF SCLK 0 Wakeup and convert command = 0x00 followed by 0x00 Shutdown command = 0x20 followed by 0x00 (a) Two commands 0 0 0 0 0 0 0 0 0 0 0 0 0 0 MOSI CS SSPIF SCLK 0 0 0 b13 b12 b11 b10 b9 b8 0 1 0 0 0 0 0 0 b7 0 b6 0 b5 0 b4 0 b3 0 b2 0 b1 0 b0 Chapter 17 MOSI MISO (b) Read temperature and shut down SPI for Feature Enhancement FIGURE 17-13 SPI use with ADT7301 with Mode 3 operation (CKP=1. CKE=0. SMP=0) . 5°F If the temperature is below 100. One loop time later it retrieves the converted result while simultaneously shutting the chip down. Assume that the temperature will never exceed 99. add an ADT7301 to the SOIC surface-mount pattern on the front of the Qwik&Low board. Using two DMMs. blank the hundreds digit.9°C.c program that powers up the pot and keeps it powered up. write a little Init7301 function that sends the shutdown command described in Figure 17-13a assuming the circuit connections of Figure 17-12 (and with no change in the SPI initialization of SSPSTAT and SSPCON1 already carried out for the LCD). (Without running InitDAC. and for the same reason. . c) Write a TenthCent function that. any code that uses the board will suffer an extra current draw of about 40 µA.4 to add the part and to wire the connections.Section 17.3°C right justified on the LCD. Make a plot of this voltage difference versus the pot voltage over the full range of the pot output. Then the function displays the temperature with a format exemplified by 27.4 for an output impedance of 1 kΩ and a current draw of less than 1 µA. once a second.) c) Write a DAC.6 ADT7301 SPI Temperature Sensor 255 PROBLEMS 17-1 DAC Output a) Write a little InitDAC function that sends a standby command to the AD5601 digital-to-analog converter described in Section 17. b) If you are willing to add a call of this InitDAC from the Initial function for all of the code that subsequently uses this augmented board. 17-2 Temperature sensor a) As was done for the last problem. b) Subject to the same caution as was raised in Part (b) of the last problem. being careful to avoid the use of any pins used by a part (such as the DAC for the last problem) on the back of the board. follow the directions at the beginning of Section 17. measure the DC voltage of the DAC output relative to the pot output and also measure the pot voltage as you turn the pot from full CCW to full CW. Assume the chip is connected to the MCU with the circuit of Figure 17-6. d) Write a TenthFahr function analogous to the function of Part (c) that will display the Fahrenheit temperature with a format exemplified by 104. initiates a conversion. Then read the 8-bit output of the pot and write it to the DAC every tenth of a second.0°F. over a standard RS-232 connection. A custom protocol was developed to facilitate communications between the two components. This allows the user to download a C program to the PIC without any additional hardware or software. This simple protocol defines many standard debugging commands.1 Architecture There are two components to QwikBug: the QwikBug kernel. and the QwikBug software interface.1. step.1 INTRODUCTION QwikBug is a small utility used to aid developers in the testing and debugging of C programs compiled for use on the Qwik&Low board. A1. which is a program that resides in the PIC’s program memory.Appendix A1 QWIKBUG PROGRAM DEBUGGER By Ryan Hutchinson A1. and add breakpoint. 256 . The QwikBug kernel and software interface communicate using the computer’s serial port. QwikBug was developed for the PIC18F4321 series of 8-bit PIC microcontrollers and makes full use of the PIC’s built-in background debug mode (BDM). which provides the graphical user interface from a standard Windows-based PC. such as run. The protocol also defines commands that allow the QwikBug kernel to dynamically program the PIC’s flash memory using the serial port. Because of this. If the registers shared by QwikBug are written to. making it unavailable to the user except by moving a jumper on header H1. thereby assigning RX to an add-on user connection.096 words) of program memory available. It utilizes a total of 56 bytes of RAM to perform its operations. it makes exclusive use of bank 1 for all of its operations. The QwikBug kernel makes use of the PIC’s low-power features by placing itself into sleep mode when idle. Once QwikBug returns from BDM. The transmit buffer. QwikBug also uses a clock frequency and serial baud rate that could be different from the user’s.536 bytes (768 words) of the PIC’s memory. As with program memory. pre-defined values so that communications with the software interface is always possible. the PGC pin will trigger the microcontroller to enter BDM. As long as the user’s programs do not write to registers in the range specified above. The goal behind the QwikBug program was to make it as non-intrusive as possible and to use the minimum amount of resources so that a user program could operate as if it were the only program running on the microcontroller. QwikBug uses both the transmit and receive functionality of the UART to communicate behind the scenes with the QwikBug software interface. Since the PIC18LF4321 has a total of 8. can be shared between the two.192 bytes (4.Section A1. however. To accomplish the seamless transition from BDM to user code.656 bytes (3. QwikBug also requires some RAM registers to operate. QwikBug shadows many of the PIC special function registers (SFRs). it requires the use of various PIC resources to function. Since the QwikBug kernel is no different from any other program that is written for a PIC microcontroller. unexpected results may occur. . this leaves 6. The RAM used by the QwikBug kernel begins at address 0x1C8 and extends through address 0x1FF. the software interface will “wake up” the chip when transmitting commands by first sending a “wake-up” byte that is ignored by the kernel and is only used to awaken the chip and return it to BDM. This means that many of the timerand peripheral-related SFRs are saved to temporary locations before being modified by QwikBug. In this fashion. The QwikBug kernel occupies 1. This is accomplished by tying the RX input pin that is used by the PIC’s UART to the PGC input pin.328 words) of program memory for the user’s programs. The kernel is located high in the PIC’s program memory starting at address 0x1A00 and extends to the very end of its memory at address 0x1FFF. the registers are restored and operations can continue as if the user program was never interrupted. whenever data is received by the PIC on the UART. The third resource that is shared by QwikBug and by user programs is the UART. Since all RAM used by QwikBug is above 0x0FF. QwikBug requires exclusive utilization of the UART’s receive buffer. these 56 bytes are located high in the PIC’s address range to prevent collisions with user program variables. This same pin is used by Microchip’s ICD2 programmer/debugger to communicate to the PIC. The incoming user data is separated from communications-related data by the software interface and presented to the user via the QwikBug console. QwikBug can operate as intended. When BDM is first entered.1 Introduction 257 QwikBug uses the PGC (Program Clock) input pin on the microcontroller to initiate BDM (Background Debug Mode). however. QwikBug shadows the SFRs related to the clock speed and serial baud rate and uses its own. 1. from COM1 through COM7 The following prerequisites are required to install the QwikBug kernel: • • • • Qwik&Low board Microchip PICkit 2 programmer QwikProgram 2 software installed (found online at www. A1.2 INSTALLATION A1.qwikandlow. QwikBug was designed to work with the Qwik&Low board and this guide will only cover installation for Qwik&Low boards.VECTOR files from the webpage at www. Place both the HEX file and the HEX. free debugging interface • Run.258 Appendix A1 QwikBug Program Debugger A1. However. The following features are all part of the QwikBug package: • Simple.1 Prerequisites The following prerequisites are required to run the QwikBug software interface: • PC running Windows XP or Windows Vista • Standard PC serial port via any COMi address.2.2 Features The QwikBug software interface was designed to be lightweight and easy-to-use while still providing powerful debugging features. and single-step through C source code • Load and erase programs from a C18-compiled hex file using the PIC’s UART • Monitor watch variables in multiple display formats.2 Installing QwikBug Kernel with QwikProgram 2 • Download the latest QwikBug kernel HEX file and HEX. variable types.2. . VECTOR file in the same directory. and array sizes • Modify watch variable values while program execution is suspended • Soft reset of program to initial program vector • Add a single breakpoint to stop execution at a specific C source line • Quickly search through C source code by navigating to subroutines • Display user data received on the PC’s serial port using the built-in console tab A1. pause.qwikandlow.com) Standard PC USB port Note that QwikBug could potentially be installed on a PIC18F4321 chip that was not part of the Qwik&Low board.com. • Select File -> Open hex file. Locate the previously downloaded HEX file and click Open. A 6-pin male-to-male header strip is required to connect the female end of the PICkit 2 to the female header on the Qwik&Low board. Ensure that the arrow on the board lines up with the arrow on the PICkit 2.2 Installation 259 • Attach the PICkit 2 programmer to the computer’s USB port.Section A1. A1. The following window should appear: • Verify that the PIC18F4321 was detected as labeled in the QwikProgram 2 status bar before proceeding. The window should now look as shown: • Click the Write button once the HEX file has been loaded.3 Installing QwikBug Software Interface • Download the QwikBug software interface install file from the website at www. • Verify that power is turned off to the Qwik&Low board and run QwikProgram 2 on the computer. qwikandlow. This will write the QwikBug kernel to the proper vector location on the PIC. This header also has the label “MCU PICkit 2” and is specifically for the PIC18LF4321 on the Qwik&Low board. If the verification of the write did not succeed. from the QwikProgram 2 menu.com. . If the PIC was not detected. . try disconnecting and reconnecting the PICkit 2 from the USB port and running Detect from QwikProgram 2’s Device menu. • Now the QwikBug kernel has been installed and the QwikBug software interface can be used to communicate with the kernel residing on the PIC.2. reseat the PICkit 2 connection and try again. . • Attach the other end of the PICkit 2 to H5 on the Qwik&Low board. 260 Appendix A1 QwikBug Program Debugger • Launch the setup program. If QwikBug has already been installed on the computer then it will prompt to uninstall the old version before proceeding. Otherwise, click Next after selecting the desired options. • Select the COM port that will be used to communicate with the QwikBug kernel from the drop-down list. Click Next to continue installation. • Select the installation folder for QwikBug. The default installation folder is recommended. Click Install to begin the installation of the software. • After installation has successfully completed, click Close. The QwikBug software interface has now been installed. • After installation, it is possible to tweak particular QwikBug settings. To do so, open the settings.xml file located in the QwikBug installation directory chosen above using a standard text editor such as Notepad. To change the setting values, modify the value attribute for the desired XML element. Caution; modification Section A1.2 Installation 261 of the name or type attributes or other aspects of the file could corrupt the XML file and cause QwikBug to malfunction. The table below outlines the settings that can be tweaked: Setting Name COMPort Default Value (chosen during setup) Description The COM port that QwikBug uses to communicate with the kernel. This value was created during setup and can be changed if needed. The serial port baud rate used to communicate with the kernel. This setting should generally not be changed unless the QwikBug kernel is modified to also use the same baud rate. The amount of time in milliseconds to wait before a timeout error occurs when issuing a command to the QwikBug kernel. BaudRate 19,200 baud SerialTimeout 300 ms 262 Appendix A1 QwikBug Program Debugger A1.3 GRAPHICAL USER INTERFACE The following figure outlines the various components of the QwikBug user interface. Those components that will be referred to later are called out to provide a reference. Abnormal stop source indicator Menu bar Toolbar Source box Watch grid State label Tab button to console box Status label Progress bar Interaction with the QwikBug user interface is identical to that of most commonly used Windows programs. Several of the popup windows that are part of the QwikBug program are set as topmost windows and will always remain on top of other windows while they are open. This is to help the user to quickly relocate the popup windows when needed. A1.4 LOADING A PROGRAM A1.4.1 Opening a List File QwikBug gathers all of the information it needs about the user program from the LST and COD files that are generated by the Microchip C18 compiler. It also requires the HEX file that is generated by the compiler to download the program to the PIC. It is recommended that the user downloads and uses the C18 compilation utility that is freely available on the website at. The C18 utility utilizes the C18 compiler and passes in compiler arguments needed to compile C programs for the PIC18LF4321. It also provides the user with program memory utilization and factors in the program memory occupied by QwikBug when doing so. To open a list file, select Open File from the File menu or click the Open File toolbar button. A dialog box will appear prompting the user for the desired LST file. Locate the compiled LST file from the dialog and click Open. Note that the associated Section A1.4 263 HEX and COD files must be in the same directory as the LST file and have the same beginning file name or QwikBug will produce an error. Once the list file has been processed, the source code for the C program will appear in the source box. The progress bar will show the progress of the file as it is being opened. Note that the state label shows “Disconnected”, indicating that the user program has not yet been loaded into the PIC. Ensure that the Qwik&Low board is powered on and that the serial cable is properly connected from the PC to the Qwik&Low board’s female DB-9 serial port connector. To load the program into the PIC, select Load from the Program menu or click the Load toolbar button. The progress bar should begin to increase as the program is downloaded over the serial port. If there was an error downloading, the following message box will appear: This error message indicates that the software interface was unable to communicate with the QwikBug kernel. If this error occurs, check the power to the PIC and the serial port connections. Also verify that the QwikBug kernel has been properly installed as described in the previous section. 264 Appendix A1 QwikBug Program Debugger Upon successful load of the program, the state label will change to “Paused” and the status label should read “Program paused [Reset executed]”. Note that the Reset , Run , and Step toolbar buttons are all now enabled. Refer to the associated sections to learn about the use of all of QwikBug’s debugging features. A1.4.2 Erasing the Program Memory QwikBug allows the user to erase the program memory of the PIC (up to the QwikBug kernel’s vector location). To execute an erase, select Erase from the Program menu or click the Erase toolbar button. Erase is only allowed when the state is either disconnected or paused. If the erase is successful, the state will change to disconnected and the status label will read “Program memory erased”. A1.4.3 Monitoring of List File QwikBug will constantly monitor the list file once it has been opened. If the list file changes for any reason (e.g., the source file is changed and recompiled), QwikBug will disconnect, clear out the source box, and the status label will change to read “List file has been changed, please reopen file”. This is done to ensure that the user is kept upto-date when the source file has been recompiled and that an old copy of the program is not accidentally used with QwikBug. To reopen a list file at any time after the file has initially been opened, select Reopen File from the File menu or click the Reopen File toolbar button. A1.5 PROGRAM CONTROL A1.5.1 Running While the PIC is in the running state, it is executing code without any intervention by QwikBug. To place the PIC in run mode after a program has been loaded into protoolbar button. gram memory, select Run from the Debug menu or click the Run The PIC cannot be placed into run mode unless it is currently paused. The state label will change to “Running” while in run mode and will be highlighted green. Once in run mode, watch variable values will not be updated until the PIC reaches a paused state. If the PIC reaches a breakpoint while running it will also enter the paused state. The PIC can also be reset while in the running state. A1.5.2 Pausing No user program code is executed by the PIC while in the paused state. To place the PIC in pause mode after a program has been loaded into program memory, select toolbar button. The PIC can be Pause from the Debug menu or click the Pause Section A1.5 Program Control 265 paused while it is in run or step mode. Paused is also the default state of the PIC after coming out of reset or performing a program download. The state label will change to “Paused” while in paused mode and will be highlighted yellow. The values of the watch variables will be updated as soon as the PIC is placed in the paused state. While in pause mode, breakpoints can be added or removed and watch variables can be added. It is also possible to reload the program into the PIC while in pause mode or to erase the program memory. From pause mode, the user can place the PIC in run mode or step mode. While the PIC is in the paused state, a yellow highlight will appear in the source box to let the user know what code is about to be executed. It is important to remember that the line that is highlighted has not yet been executed or has been partially executed, as is the case for C source lines that contain multiple instructions should the PIC be paused while in the middle of executing the line. The figure below shows an example of a highlighted C source line just before execution: A1.5.3 Stepping While the PIC is stepping, code is being executed one instruction at a time. The PIC will continue to step until its program counter reaches a value that is outside the range of the C source code line. There are generally multiple instructions that are executed for each line of C source code. To place the PIC in step mode after a program has been loaded into program memory, select Step from the Debug menu or click the Step toolbar button. The PIC can be stepped while it is in pause mode only. The state label will change to “Stepping” while in step mode and will be highlighted orange. If a C source line contains loops that cause the line to continually execute, it could take significant time before the PIC steps out of one C source code line. Because of this, QwikBug allows the user to discontinue step mode by selecting Pause from the 2 Adding a Breakpoint To add a breakpoint in QwikBug. Additionally. the breakpoint is actually put at the last instruction contained in the C source code line. When a breakpoint is set in QwikBug. A1.266 Appendix A1 QwikBug Program Debugger Debug menu or clicking the Pause toolbar button. This is because the PIC executes the line of code that the breakpoint is placed on and then increments the program counter before entering BDM.5. A reset can be executed while the PIC is in either run or paused mode.1 Breakpoint Execution Order Breakpoint execution order is different for QwikBug than for many other debugging programs that the user may be used to. Once paused. To issue a soft reset to the PIC. QwikBug will return the PIC to the paused state at the initialization vector after a reset. This will cause the program counter to reset to the default initialization vector of 0x0000. Breakpoints cause an executing PIC program to halt when the program counter reaches a specified value. the PIC will execute the very last instruction contained in the line and then pause.6. It cannot be executed while the PIC is stepping. the program must first be loaded onto the PIC and the PIC must be in a paused state. A1. When a breakpoint is placed on a C source line is QwikBug.6 BREAKPOINTS QwikBug provides the user with a single breakpoint that can be placed on any line of C source code that contains PIC instructions. simply right-click on a line of source code in the source box and select Add Breakpoint as shown below: . A1. all PIC special function registers (SFRs) and RAM values will be reset to their initial states.6. select Reset from the Program menu or click the Reset toolbar button. This will cause the PIC to suspend single-step execution and the state will change back to paused. A1.4 Resetting QwikBug provides a soft reset feature. the previous breakpoint will be automatically cleared and the newly selected breakpoint line will be highlighted red. Once a watch variable has been added to the watch grid in QwikBug. . long) as well as the number of elements if the variable is an array. QwikBug allows the user to watch PIC SFRs and modify their values just like a normal. and ASCII. If another breakpoint already exists when the Add Breakpoint selection is clicked.g. In addition.g..3 Clearing a Breakpoint To clear the current breakpoint either select Clear Breakpoint from the Debug menu or select Clear Breakpoint from the menu that appears when a C source line is rightclicked. QwikBug uses the compiler-generated COD file to locate address information for the variable symbol names.Section A1. A1. short long. including decimal. int. the red highlight will also disappear from the breakpoint line in the source box. the Add Breakpoint option will be grayed-out and disabled from the right-click menu. Breakpoints can only be cleared when the PIC is in the paused state.. the user can view the actual value of the register prior to entering BDM. When a breakpoint is cleared.7 Watch Variables 267 A line that has a breakpoint associated with it will be highlighted red as shown below: Note that only one breakpoint is available with QwikBug. user-defined C variable. If a line that is not associated with any instructions is selected. The variables are defined in the C source file. char. comment lines) cannot have breakpoints added to them. Also note that source lines that do not have any PIC instructions associated with them (e.7 WATCH VARIABLES Watch variables are pointers into the values stored in the PIC’s RAM and Special Function Registers. QwikBug allows the user to manually choose the variable type for a specified watch variable (e. hexadecimal. binary.6. The user also has the ability to modify the value of the watch variable and display the variable in multiple formats. A1. Note that QwikBug does not support watching local function variables. The figure below shows an example of a highlighted variable in the source box as well as the Add Watch selection: Once Add Watch is selected.7. The Type. it must be a global C variable. and Display columns in the QwikBug watch grid will need to be manually updated for the new watch variable since they will all be set to the default values. If the variable is found in QwikBug’s symbol table the Add Watch option will be selectable.1 Adding Watch Variables to the Watch Grid Watch variables can be added while the PIC is in any state. Only one copy of the variable can exist at a time in the watch grid. however. Refer to the section on variable and display types below for more information on these columns. The figure below shows the watch grid after the example variable has been added for watching: Now that the variable exists in the watch grid the value will be updated whenever the PIC enters the paused state. The values.268 Appendix A1 QwikBug Program Debugger A1. and will be initialized with an array size of one element. The variable will be added with the default variable type and display type. QwikBug will automatically highlight the entire word that was clicked on in the source box. . meaning that the variable is not an array. the variable will be added to the watch grid. and QwikBug will ignore requests to add the same watch variable multiple times. If a user-defined variable is intended to be watched in QwikBug. right-click on the variable anywhere it is used in the C source box. Array. To add a watch variable after opening a list file. will only be updated while the PIC is in its paused state. To clear all of the watch variables that are shown in the watch grid. select the Clear All option after right-clicking on the watch grid. Multiple rows can be selected at a time by clicking the leftmost column and dragging the mouse to select the desired rows. simply right-click anywhere on the variable’s row in the watch grid and select Remove Watch as shown in the figure below: If multiple rows were selected.Section A1. A1. all of the selected watch variables will be removed from the watch grid.3 Add Watch Variable Popup The add watch variable popup is a way to alphabetically view all possible variables that can be watched and can be used as an alternate method of adding and removing watch variables from the watch grid.2 Removing Watch Variables from the Watch Grid To remove a watch variable. It is also possible to use the keyboard’s Del key to quickly delete selected rows from the watch grid.7 Watch Variables 269 A1.7. The add watch variable popup window can be opened by selecting Add Watch from the Debug menu and is always the topmost window.7. The figure below shows a typical example of the add watch variable popup in QwikBug: . The following popup will appear: . if the variable is currently being watched. If the variable consists of only one element. The variables that are currently being watched are highlighted in the appropriate list box. the highlight will be removed from the list box and the variable will be removed from the watch grid. To add or remove a watch variable simply click on the variable name in either list box. If the variable is not being watched.270 Appendix A1 QwikBug Program Debugger The add watch variable popup is divided into two list boxes: user-defined variables and PIC special function registers. Structures and other multi-type variables are not supported by QwikBug. as shown in the example above. The variable type for PIC SFRs cannot be modified and will be highlighted gray because all SFRs are single-byte registers and thus have an inherent type of char.4 Watch Variable Types and Display Types The Type column in the watch grid represents the declared type of the C variable in the source program. the Array column will display No. The table below lists all of the possible variable types and their associated size: Type char int short long long Size (of each element) 1 byte 2 bytes 3 bytes 4 bytes Note that the variable type applies to each element of an array. The PIC special function registers list box contains all of the defined SFRs that can be read from or written to on the PIC18LF4321. implying that the watch variable is not an array.7. The Array column in the watch grid displays the number of elements contained in the associated watch variable. To change the number of elements in a watch variable. click on the cell button in the column. Conversely. it will become highlighted and will be added to the watch grid. The user-defined variables list box contains all globallydefined C variables that are user defined in the source program. A1. Section A1. For variables types larger than a char this means that all of the upper bytes are ignored when displaying the value as ASCII. only the least significant byte is used to determine the ASCII character. To modify the value. select the total length of the array and click OK to update the watch variable.5 Writing to Watch Variables QwikBug allows the user to modify the values of variables that are being watched. The Display column determines how the watch variable’s value in the Value column should be displayed to the user. the displayed value will be commaseparated with each element following the display formatting shown above. Then. A1.7. The table below lists all of the possible display type options as well as an example display of each for a single-element char: Display Unsigned Signed Hex Binary ASCII Example 165 −91 0xA5 10100101 G For variables that have been defined as arrays. check the Array box on the popup. as shown below: . For ASCII display types.7 Watch Variables 271 To make the variable an array of elements. double-click on the cell in the Value column for the associated watch variable in the watch grid. Watch variable values can only be modified when the PIC is in the paused state. This action will open a popup that can be used to modify the variable’s value(s). Note that the Array column will be disabled and grayed-out for SFRs because they can only be single-byte registers. select Export Watch Variables from the File menu. For ASCII display types only one row will be shown and the value is treated as a contiguous string.6 Import/Export of Watch Variables QwikBug contains a feature that allows the user to import and export watch variable configurations to the hard drive to expedite watch variable creation at different points in time. Once all element values have been modified to the desired new values. To discard any modifications simply click the Cancel button on the popup window and the variable will not be written to. the old value will remain in the element’s row. To export the current watch variable configuration once a list file has been opened and the watch grid has been configured as desired. Click on each of the variable’s elements that are to be modified and type in a new value for the element. QwikBug will verify all values before they are written to the PIC. If the value entered cannot be interpreted for the chosen display type or if the value is outside the range of the variable type. Be sure to use the same display format when overwriting an element’s value. A1. The Value column in the watch grid will then be updated with the variable’s new value(s) once they have been successfully read back from the PIC. click the OK button to have QwikBug update the PIC with the new values.272 Appendix A1 QwikBug Program Debugger For variables that are configured as arrays.7. a row will be present for each element in the array and the associated index number is shown in the column to the left of an element’s value. A dialog will appear prompting the user for a destination file to save to: . The following dialog will appear: Select the file that contains the configuration that should be imported and click the Open button to begin the import process. A1. select Find Subroutine from .1 Find Subroutine Popup The find subroutine popup allows the user to quickly locate a C subroutine in the source box.Section A1. Watch variables can only be imported after a list file has been opened. it is possible to import any watch variable configuration with any list file. QwikBug will clear all current watch variables out of the watch grid once an import is initiated and will add the variables from the exported file to the watch grid.8. QwikBug does not associate watch variable export files with specific list files. QwikBug will check each variable during an import to ensure that it exists in the current source program. Therefore. QwikBug will not add the variable to the watch grid if the variable name does not exist or if there is a mismatch between the addresses of the exported variable and the current program’s variable.8 ADDITIONAL FEATURES A1. Once a configuration has been exported. The name of the file is insignificant to QwikBug and is only used to help the user keep track of multiple watch variable export files.8 Additional Features 273 Select the file to save the watch variable configuration to and click the Save button. To open the find subroutine popup window. the file can be imported by selecting Import Watch Variables from the File menu. 274 Appendix A1 QwikBug Program Debugger the Debug menu. it will be opened as the topmost window. stack over/underflow. A1. The popup window will display a list of all subroutine symbols that QwikBug has located in the source file: Double-clicking on the name of the subroutine in the list box will scroll the source box to the location of the first C source line in the selected subroutine and highlight the line. An example is shown below: . Potential reasons include: brown-out reset.8.2 Abnormal Stop Sources An abnormal stop occurs any time the PIC enters BDM for an irregular reason. If an abnormal stop occurs after a program has been loaded. the following icon will appear in QwikBug: Click on the abnormal stop source indicator to display a popup window with details on the abnormal stop source. power-on reset. and watchdog timer overflow. The console tab will flash when new data is received and the console tab is not in focus. When an abnormal stop occurs.8. and the box will scroll to always display the most recent data at the bottom of the console box. The names of the files can be found under the File menu as shown below: . as shown below: A1. right-click anywhere in the text box and select Clear. Click Cancel to close the popup window but keep the abnormal stop source indicator shown on the main QwikBug window.8. New data is appended to the end of the text box. A1.8 Additional Features 275 Click the OK button to close the popup window and clear the abnormal stop source indicator warning. the PIC will generally be in a reset condition and the user can resume execution from the reset vector or correct the reason for the abnormal stop source in the C source code.Section A1.4 Recently Opened Files QwikBug displays a list of the four most recently opened files. To clear the console box.3 Console Tab The console text box displays data received by the serial port that is not part of the QwikBug interface communications. Note that some of the keyboard shortcuts that use Ctrl will not work with the cursor positioned in the main source code text box.276 Appendix A1 QwikBug Program Debugger To open any of the previous files. simply click on its name in the File menu. . The most recent file is positioned at the top of the list and the oldest is positioned at the bottom. Click outside the text box to change the focus so that these keyboard shortcuts will work.9 KEYBOARD SHORTCUTS The table below shows all defined QwikBug keyboard shortcuts: Function Open File Reload File Show Add Watch Popup Clear Breakpoint Clear Console Export Watch Variables Import Watch Variables Usage Guide Reset PIC Load Program Pause Run Step Erase Program Keyboard Shortcut Alternate Keyboard Shortcut Ctrl+O Ctrl+Shift+O Ctrl+W Ctrl+Shift+B Ctrl+Del Ctrl+X Ctrl+I F1 F2 F3 F5 F7 F8 F12 none none none none none none none none none Ctrl+T Ctrl+L Ctrl+P Ctrl+R Ctrl+S Ctrl+E Show Find Subroutine Popup Ctrl+F Both the keyboard shortcut and the alternate keyboard shortcut provide the same functionality. A1. 1 OVERVIEW This appendix will describe the PIC18LF4321 CPU structure.lst file produced by the compiler into a qwik. RAM and Special Function Registers.exe utility to translate the *. program memory.lst file translates the code writer’s expectations into the reality of what is actually being executed by the MCU Cody Planteen has written a qwiklst. The intent is not to arm the reader to write assembly code for the MCU.2 HARVARD ARCHITECTURE The PIC18LF4321 CPU is organized around two buses in what is known as the Harvard architecture.4). shown in Figure A2-1.exe utility used by Alex Singh’s C18.LST FILES A2. it is to help with the interpretation of the list file generated by the C18 compiler. and instruction set. When the execution of a user program does not match the expectations of the code writer. Rather.lst file that is easier to interpret.Appendix A2 INTERPRETING .lst file’s cryptic display of the address of the variable or register. For instructions that return an operand to either of two locations. It substitutes the name of a variable or of a Special Function Register in place of the normal . A2. the resulting . it substitutes an F or a W for the more cryptic 0x1 or 0x0 (see Section A2. One bus reaches out to program memory 277 . addressing options. the preceding MOVLW instruction is being executed. The next column lists the 2-byte opcode (i.lst Files Program address Program memory (8192 bytes) 13 bits CPU Instruction 16 bits Operand address 12 bits Operand memory (RAM and Special Function Registers) Data 8 bits FIGURE A2-1 Harvard architecture and fetches one of the CPU’s many 2-byte instructions during each CPU clock cycle. MOVLW MOVWF MOVLW MOVWF 0x2C ALIVECNTL 0x01 ALIVECNTH implements the source file line ALIVECNT = 300.lst file. The Harvard architecture has a twofold impact on the performance of the CPU relative to the performance of a single-bus 8-bit microcontroller: • The wide 16-bit instruction bus can fetch instructions with half the fetch cycles and thus twice the speed for a given clock rate. //Blink immediately The CPU fetches each 2-byte instruction during its 1-microsecond fetch cycle.278 Appendix A2 Interpreting . 0E2C) that identifies the instruction to the CPU. At the same time that the CPU is fetching one instruction.e. as the MOVWF instruction is being fetched.. The next two columns list the assembly language instruction(s) that the compiler has selected to implement the source file line shown to the right. That is. . • The time required to execute instructions is largely hidden beneath the ongoing fetching of successive instructions rather than requiring additional cycles. The effect of the pipelined operation can be explained via the four-line qwik. The left column lists the first of the two addresses (i.lst example of Figure A2-2 derived from the T3.. 4-byte instructions. Furthermore. it is executing the instruction fetched during the previous cycle. 0116 and 0117) holding an instruction. These fetches of 1-cycle instructions are occasionally augmented by the fetches of 2-cycle.e. In addition to the 8-bit address field of an instruction. another bit (“a” in Figure A2-4a) indicates how the remaining bits of an operand address are to be formed.. F/W. The operand.e. the default case for the C18. the compiler uses the access-bank direct addressing of Figure A2-4b.lst A2. upper four bits) of the full 12-bit address.3 INSTRUCTION SET AND DIRECT ADDRESSING The PIC18 family of microcontrollers has the instruction set shown in Figure A2-3. For programs making use of less than 128 bytes of RAM. f. These would extend over the RAM locations that cannot be reached by access-bank direct addressing. In effect.e.lst file calling for interpretation. An application making use of more than 128 bytes of RAM is likely to use indirect addressing to access one or more large arrays. some of these addresses would be accessed using the banked-memory. associated with many instructions is an 8-bit field in the 16-bit instruction that accounts for 8 bits of the 12-bit direct address of the operand.Section A2. If a program were to use more than 128 named RAM addresses. it is necessary to understand the role of the operands associated with an instruction. A2. The result is one less parameter in the . An instruction using this scheme is preceded by a MOVLB 0x00 or a MOVLB 0x01 instruction to load the Bank Select Register with the number to be used as the upper nibble (i. To understand the role of an instruction beyond the somewhat cryptic Description expressed in the table. not the 512 actually available. the microcontroller behaves as if it only has 128 bytes of RAM. // Blink immediately FIGURE A2-2 A snippet from qwik. 0x00 to 0x7F). It is one of the distinguishing characteristics of Microchip’s PIC microcontrollers that the result of an operation on a variable can be returned . Cody Planteen’s QwikLst utility suppresses the a = 0 parameter of an access-bank directly addressed RAM variable. The 8-bit address field in an instruction can access any of 128 RAM bytes using addresses ranging from 0 to 127 (i.exe utility.4 F/W Distinction 279 0116 0118 011A 011C 0E2C 6E05 0E01 6E06 MOVLW MOVWF MOVLW MOVWF 0x2C ALIVECNTL 0x01 ALIVECNTH ALIVECNT = 300.4 F/W DISTINCTION Another parameter associated with instructions that directly address an operand is the destination parameter.. direct-addressing scheme of Figure A2-4c. copy (WREG)→ WS. where b = 0 to 7. putting result into F or W AND literal value into WREG AND WREG with f.Z N.Z C. skip if clear Test bit b of register f. putting result into F or W Skip if f is equal to WREG Skip if f is greater than WREG (unsigned compare) Skip if f is less than WREG (unsigned compare) Decimal adjust binary sum in WREG of two packed BCD numbers f. putting result into F or W Decrement f. where b = 0 to 7 If negative (N=1). putting result into F or W Add WREG and f and carry bit. then branch to labeled instruction If no overflow of signed-number operation.k f.OV.F/W i.b label 1 1 1 1 1 1 1 2 or 1 2 1 2 or 1 2 or 1 1 2 or 1 - BZ CALL CALL CLRF CLRWDT COMF CPFSEQ CPFSGT CPFSLT DAW DECF DECFSZ DCFSNZ GOTO INCF INCFSZ INFSNZ IORLW IORWF LFSR MOVF label label label. then branch to labeled instruction Branch to labeled instruction Set bit b of register f.F/W f.280 Appendix A2 Interpreting .b label label label label Add WREG and f. putting result into F or W. skip if set Toggle bit b of register f.N. then branch to labeled instruction Call subroutine Call subroutine.Z C.F/W f.F/W f. then branch to labeled instruction Clear bit b of register f. putting result into F or W Increment f.F/W Decrement f.b f.F/W f.OV.Z - f.Z N.Z C C. skip if zero Increment f.b f.OV. skip if zero Decrement f. then branch to labeled instruction If no carry or if borrow (C=0).F/W f f f Complement f. where b = 0 to 7 Test bit b of register f.N. putting result into F or W If carry or if no borrow (C=1).N.Z N. then branch to labeled instruction If not zero (Z=0).F/W f.OV. then branch to labeled instruction If ≥0 (N=0). putting result into F or W.lst Files Mnemonic ADDLW ADDWF ADDWFC ANDLW ANDWF BC BCF BN BNC BNN BNOV k Operands Add literal value into WREG Description Words 1 1 1 1 1 1 1 1 1 1 1 Cycles 1 1 1 1 1 2 or 1 1 2 or 1 2 or 1 2 or 1 2 or 1 Status bits affected C.F/W label f.Z N.Z C. then branch to labeled instruction If zero (Z=1). skip if not zero Inclusive-OR literal value into WREG Inclusive-OR WREG with f. putting result into F or W.Z f. putting result into F or W Load FSRi with address of operand Move f to F or W FIGURE A2-3 Assembly language instruction set . (BSR)→ BSRS Load f with 0x00 Clear watchdog timer BNZ BRA BSF BTFSC BTFSS BTG BOV label label f.F/W k f. putting result into F or W.b f. (STATUS)→ STATUSS.Z N.F/W label f. where b = 0 to 7 If overflow of signed-number operation.FAST f 1 2 2 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 2 1 2 or 1 2 2 1 1 1 2 or 1 2 or 1 2 or 1 1 1 2 or 1 2 or 1 2 1 2 or 1 2 or 1 1 1 2 1 Z N.N.OV. where b = 0 to 7.N.F/W k f. skip if not zero Go to labeled instruction Increment f. Section A2. reenable interrupts FAST Return from interrupt. reenable interrupts. restore state from shadow registers (WS)→ WREG Copy f into F or W.N.F/W 1 1 1 1 1 1 C.OV.Z FIGURE A2-3 (continued) . restore state from shadow registers (WS)→ WREG.Z C.F/W 1 1 N. then increment TBLPTR Increment TBLPTR.Z C.OV. putting result into PRODH:PRODL Multiply unsigned WREG with f.F/W f.N. enter idle mode RLCF RLNCF RRCF f.4 F/W Distinction 281 Mnemonic MOVFF MOVLB Operands fS. to set the bank for direct addressing with a=1 Move literal value to WREG Move WREG to f Multiply unsigned WREG with literal value.N. putting result into F or W Swap four-bit nibbles of f. rotate left without carry bit (8-bit rotate left) Copy f into F or W. where k = 0 to 15.Z SETF SLEEP SUBFWB SUBLW SUBWF SUBWFB SWAPF TBLRD f 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 C.Z N.F/W f.Z C. rotate right without carry bit (8-bit rotate right) Load f with 0xFF Normally enter sleep mode. rotate left through carry bit (9-bit rotate left) Copy f into F or W.F/W 1 2 - 1 1 1 2 or 1 1 1 N. putting result in PRODH:PRODL Change sign of a twos-complement-coded one-byte number No operation Discard address on top of stack Push address of next instruction onto stack MOVLW MOVWF MULLW k f k 1 1 1 1 1 1 - MULWF NEGF NOP POP PUSH RCALL RESET RETFIE RETFIE f f 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 2 2 C.Z RRNCF f.Z N.N. then read from program memory location pointed to by TBLPTR into TABLAT Test f.OV. putting result into F or W Subtract WREG and borrow bit from f.OV.Z C.N.OV. rotate right through carry bit (9-bit rotate right) Copy f into F or W. (STATUSS)→ STATUS. putting result into F or W Subtract WREG from literal value. putting result into WREG Subtract WREG from f.Z C.Z label Call subroutine Software reset to same state as is achieved with the MCLR input Return from interrupt.N.N. (BSRS)→ BSR Return from subroutine. if IDLEN=1.N. then decrement TBLPTR Read from program memory location pointed to by TBLPTR into TABLAT. skip if zero Exclusive-OR literal value into WREG Exclusive-OR WREG with f.fD k Move fS to fD Description Words 2 1 Cycles 2 1 Status bits affected - Move literal value to BSR<3:0>. putting result into F or W TBLRDPOSTDEC TBLRDPOSTINC 1 2 - TBLRDPREINC TSTFSZ XORLW XORWF f k f.N.F/W f. putting result into F or W Read from program memory location pointed to by TBLPTR into TABLAT Read from program memory location pointed to by TBLPTR into TABLAT.OV.Z C.OV.N. putting literal value into WREG Return from subroutine RETLW RETURN RETURN k 1 1 1 2 2 2 C.Z FAST Return from subroutine.F/W k f.F/W Subtract f and borrow bit from WREG.OV.Z - f.F/W f. alternatively.lst Files 15 Instruction opcode 9 8 7 0 a f (a) Nine bits of an instruction identifying the source of an operand.282 Appendix A2 Interpreting . FIGURE A2-4 Direct addressing to the variable or. BSR (Access bank RAM) Bank0 12-bit effective operand address Instruction opcode More RAM 512 bytes of RAM 1 a f Still more RAM Bank1 Unused memory space Special Function Registers (c) Banked memory direct addressing (a = 1). Full 12-bit address Bank Select Register. as shown in Figure A2-5. 8-bit address 128 RAM addresses 128 Special Function Register addresses (b) Access bank direct addressing (a = 0).lst file generated by the linker shows both the “a” parameter of the last section and the “F/W” parameter of this section as 0x0 or 0x1 . to the CPU’s WREG working register. The . 6 COUNTING CYCLES One reason to look at the . is reexpressed as ALIVECNTL and ALIVECNTH. This clarification is especially helpful when one source file line produces many lines of assembly code. Consider the assembly code produced for implementing the Delay macro. INCF). For example. The improvement in clarity is evident.lst file’s listing of the address of an operand by its name. ADDWF).. Using a utility developed by Kenneth Kinion.g. to indicate the low and high bytes. FIGURE A2-5 Specifying the F or W destination of an instruction The QwikLst utility suppresses the a = 0 parameter (as discussed in the last section) and converts the 0 or 1 value listed for the “F/W” parameter into a W when the destination of the operation is WREG and an F when the operation returns the result back to the source address used by the instruction.lst code segment of Figure A2-6b. A2. shown in Figure A2-7.lst file code segment shown in Figure A2-6a and the recasting of the segment into the qwik.g.lst file is to discern the number of cycles that a segment of code generated by the compiler will take to execute. F Addressed location Instruction operation WREG W (b) Two-operand instruction (e.Section A2. A2.5 NAME REPLACEMENTS FOR OPERAND ADDRESSES The final and most significant clarification performed by the QwikLst utility is the replacement of the .6 Counting Cycles 283 F Addressed location Instruction operation WREG W (a) One-operand instruction (e. The loop that is traversed repeatedly as the delay parameter is counted down to zero ends with the line 00FA D7F7 BRA L002 . ALIVECNT. consider the raw .. the two-byte int variable. // Reset ALIVECNT 0x83.0x1. } 0x0 (a) Listing file void BlinkAlive() { PORTDbits.0x0 PORTDbits.0x0 0x90 0x5.4 } } (b) Translation into qwik.0x0 0x6.0x4.lst Files 0192 0012 L003 RETURN FIGURE A2-6 QwikLst translation of operands .0x0 0x5.F 0x90 ALIVECNTL.0x0.0x0 0x83.4 ALIVECNTL. PORTD.W L003 0x01 ALIVECNTH.RD4 = 0.0x0. if (++ALIVECNT == 400) } // Turn on LED for one looptime ALIVECNT = 0.lst ALIVECNT = 0.284 000178 00017a 00017c 00017e 000180 000182 000184 000186 000188 00018a { 0x5.0x4.RD4 = 1.RD4 = 0. if (++ALIVECNT == 400) // Turn off LED // Increment counter and return if not 400 00018c 00018e 000190 6a05 6a06 8883 CLRF CLRF BSF 000192 0012 RETURN 0178 017A 017C 017E 0180 0182 0184 0186 0188 018A { ALIVECNTL ALIVECNTH PORTD.F 0x00 ALIVECNTH.W L003 // Turn off LED // Increment counter and return if not 400 Appendix A2 018C 018E 0190 6A05 6A06 8883 CLRF CLRF BSF // Reset ALIVECNT // Turn on LED for one looptime Interpreting .0x0 0x192 void BlinkAlive() { PORTDbits.0x0 0x192 0x1 0x6.0x1.RD4 = 1.0x0 0x0 0x6. PORTDbits. the CPU will take two cycles as it branches to address 0x00FC.999 loops (beginning with the DECF instruction and ending with the BRA instruction) is 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 10 cycles A2. Actually. It just sets the C bit if that ninth bit of the operation is a 1 and clears C otherwise. the BZ instruction does not branch. the number of cycles taken to execute one of these 49. Thus. in addition to writing 0x00 to a RAM variable or a Special Function Register. the Z bit will be set to 1. However. If that 8-bit result was 0x00. the largest 8-bit unsigned number. The C bit will be set by an add operation of two unsigned 1-byte numbers that produces a result that is greater than 255. Every instruction in this loop of instructions executes in one cycle except BRA (2 cycles) and BZ (2 or 1 cycles). putting the result back into either the operand (F) or WREG (W). will set the Z bit.W DELAYH.999 times. the IORWF instruction will (inclusive) OR the content of WREG bit by bit with the addressed operand.F This instruction decrements the low byte of the 2-byte variable DELAY. // Pause for half a second L002 FIGURE A2-7 Delay macro’s assembly code The BRA instruction tells the CPU to branch to the program address labeled L002 that holds the instruction 00EA 060F L002 DECF DELAYL. while the CPU is looping for the first 49. As another example.F 0x00 DELAYH. If this result is 0x00. . The BZ instruction tests the result of an operation that preceded it.W L001 Delay(50000).Section A2.7 Flag Bits 285 00E2 00E4 00E6 00E8 00EA 00EC 00EE 00F0 00F2 00F4 00F6 00F8 00FA 00FC 0E50 MOVLW 6E0F MOVWF 0EC3 MOVLW 6E10 MOVWF 060F L002 DECF 0E00 MOVLW 5A10 SUBWFB 500F MOVF 1010 IORWF E003 BZ 0000 NOP 0000 NOP D7F7 BRA 9CD0 L001 0x50 DELAYL 0xC3 DELAYH DELAYL.7 FLAG BITS The right-most column of Figure A2-3 lists any of four STATUS register flags that are affected by an instruction. For example. the Z bit will be cleared to 0. the CLRF instruction. the CPU does not know if numbers are signed or unsigned. otherwise.F DELAYL. For a source file that adds two 1-byte numbers. A2. Subtract operations of unsigned and signed numbers represent a borrow condition with the complement of the C and OV bits. A borrow resulting from a signed subtraction will produce OV = 0. Then the operand can be accessed indirectly via this pointer. then N = 0. If the result is 0 or positive. FSR1. The instruction tells the CPU to read a byte from the location pointed to by FSR1. a borrow resulting from an unsigned subtraction will produce C = 0. The N status bit signifies whether the result of an operation on signed numbers is negative (N = 1). has been initialized to point to the first byte of MSGSTRING in Figure A2-8a.8 INDIRECT ADDRESSING OF RAM VARIABLES The PIC18 family of microcontrollers includes in the CPU three 12-bit pointers. the C compiler will look to see if they are defined as unsigned or signed numbers and then test the C bit or the OV bit to determine whether an overflow occurred. the largest 1-byte signed number. The initialization of FSR1 can be carried out in either of two ways.lst Files An add operation of two signed 1-byte numbers expressed in two’s-complement code will set the OV (overflow) bit if the result is larger than 127. This is especially useful for implementing pointers arising in a user program. FIGURE A2-8 Indirect addressing into a variable string FSR1 RAM FSR1H FSR1L MSGSTRING 12-bit address of operand • • • 'P' 'R' 'E' 'S' 'S' ' ' 'P' 'B' ' ' • • • (a) FSR1 use as a variable pointer . An example of indirect addressing is illustrated in Figure A2-8. but is also employed by the C compiler for more prosaic tasks. and to write the byte to the Serial Peripheral Interface’s SSPBUF register.286 Appendix A2 Interpreting . Figure A2-8c shows the instruction that can be included in a loop of instructions to send each byte to the LCD. to increment FSR1. as shown in Figure A2-8b. such as providing a function with scratchpad variables. any one of which can be loaded with the address of an operand. one of the three pointers in the CPU. That is. F increments the location pointed to by FSR1. where i = 0. Notice that the working register is identified in two ways.MSGSTRING .Send string element to PC (c) Copy operand pointed to by FSR1 to SSPBUF. FSR0. If the operand is PREINCi. FSR1. It should be pointed out that the address associated with any one of the five indirect addressing operations is not a physical register. 1. POSTINCi.FSR1H = high byte of address of MSGSTRING 1.FSR1 = address of MSGSTRING (b) Loading FSR1 pointer MOVFF POSTINC1. WREG (treated as a signed number). or FSR2. If the operand is INDFi. As the destination of an operation. Thus the instruction INCF INDF1.. or 2 to identify which of the three pointers.FSR1L = low byte of address of MSGSTRING . is to be used for carrying out the operation.9 CPU REGISTERS The CPU registers are shown in Figure A2-9. INDF0). If the operand is POSTDECi. it is W: SUBWF COUNTER. PREINCi.SSPBUF . to the address in FSRi to form the address of the instruction operand. the CPU first increments FSRi and then accesses the location pointed to by the incremented FSRi. the CPU accesses the location pointed to by FSRi and then increments FSRi. together with the operands associated with indirect addressing (e. then increment FSR1 FIGURE A2-8 (continued) The five operations associated with indirect addressing are INDFi. A2.Section A2. and PLUSWi. if the operand is PLUSWi.g. POSTDECi. the CPU accesses the location pointed to by FSRi. Rather.9 CPU Registers 287 MOVLW MOVWF MOVLW MOVWF or LFSR low MSGSTRING FSR1L high MSGSTRING FSR1H . the CPU accesses the location pointed to by FSRi and then decrements FSRi. the CPU temporarily adds its working register. the CPU interprets an access of the address as a signal to carry out the specified indirect addressing operation.W . Finally. If the operand is POSTINCi. 288 WREG (instruction source) or W (instruction destination) STATUS WREG STATUS (C. Z) BSR Bank Select Register FSR0H FSR0 FSR1H FSR1 FSR2H FSR2 PRODH PROD PCLATH Transferred by a read of PCL Transferred by a write to PCL PRODL FSR2L INDF2 POSTINC2 POSTDEC2 PREINC2 FSR1L INDF1 POSTINC1 POSTDEC1 PREINC1 FSR0L INDF0 POSTINC0 POSTDEC0 PREINC0 Access and leave FSRi unchanged Access then increment FSRi Access then decrement FSRi Increment Temporarily FSRi add WREG to FSRi then access then access PLUSW0 Indirect addressing pointers PLUSW1 PLUSW2 Multiplication result Program Counter Latch PCL Appendix A2 Program Counter Thirty-one level stack • • • Interpreting . OV. N.lst Files FIGURE A2-9 CPU registers . 7 Any multiply operation makes use of one of the two 8-bit unsigned multiply instructions.lst file segment is shown in Figure A2-11b. It returns the ASCII-coded hex character corresponding to that value. An example of the creation and use of a table is shown in Figure A2-11. produces the result in ASCII in 10 cycles. PCL. for the benefit of QwikBug and also for the benefit of execution speed. arrays. They include the option of postincrementing. or preincrementing TBLPTRH:TBLPTRL. then. and tables stored in program memory with the mechanism shown in Figure A2-10. This FormHex table expects to be handed a char variable containing a value ranging from 0 to 15. Subroutine calls and interrupts nest return addresses onto the 31-level stack. it is WREG: BCF WREG. Any instruction that operates on the program counter operates on the lower 8 bits. However. These instructions are TBLRD.10 INDIRECT ADDRESSING OF PROGRAM MEMORY The instruction set of Figure A2-3 includes four instructions that are used for accessing constant strings. to support a more powerful compilation. Thus. the content of PCLATH (Program Counter LATcH) is written into the upper byte of the program counter. MULLW or MULWF.11 SPECIAL FUNCTION REGISTERS The special function registers are listed in Figure A2-12 along with their addresses. A2. TBLRDPREINC They use the TBLPTRH:TBLPTRL register pair to identify the program memory address that is to be copied to the TABLAT register. TBLRDPOSTINC. . at the same time that the write takes place. If that instruction is going to write back to PCL.11 Special Function Registers 289 As the source of an operation. putting the 16-bit result into the CPU registers PRODH: PRODL. postdecrementing. the source file line ASCII = FormHex[NIBBLE]. A2. in the example whose qwik.Section A2. that extended instruction set is disabled. TBLRDPOSTDEC. both in 3-nibble full address form and 2-nibble Access Bank address form. The PIC18 family of microcontrollers has an extended instruction set that can be used to facilitate the extension of the stack into RAM. (a) A table to be compiled into program memory beginning at address 0x02F8.290 Appendix A2 Interpreting . then increment TBLPTRH:TBLPTRL Read from program memory location pointed to by TBLPTRH:TBLPTRL into TABLAT. then read from program memory location pointed to by TBLPTRH:TBLPTRL into TABLAT (b) Special instructions for reading from program memory. then decrement TBLPTRH:TBLPTRL Increment TBLPTRH:TBLPTRL. TBLRDPOSTDEC TBLRDPREINC FIGURE A2-10 Reading operands from program memory FIGURE A2-11 Creation and use of a program memory table to convert a number between 0 and 15 to the ASCII code for its hex representation /******************************* * Constant table ******************************* */ const char rom FormHex[] = "0123456789ABCDEF". .lst Files Program address 13 bits Program memory Instruction 16 bits CPU Operand address 12 bits Operand memory Data 8 bits TBLPTRH TBLPTRL Selected bytes Address of byte to be read 13 bits Content of selected address 8 bits (a) Special mechanism for reading from program memory. TABLAT TBLRD TBLRDPOSTINC Read from program memory location pointed to by TBLPTRH:TBLPTRL into TABLAT Read from program memory location pointed to by TBLPTRH:TBLPTRL into TABLAT. W ASCII ASCII = FormHex[NIBBLE]. executes in 10 cycles.F TABLAT.11 Special Function Registers 291 02ce 02d0 02d2 02d4 02d6 02d8 02da 02dc 02de 502d 6af7 0f46 6ef6 0e04 22f7 0008 50f5 6e2e MOVF CLRF ADDLW MOVWF MOVLW ADDWFC TBLRD MOVF MOVWF NIBBLE.W TBLPTRH 0xF8 TBLPTRL 0x02 TBLPTRH. (b) Assembly code for ASCII = FormHex[NIBBLE].Section A2. FIGURE A2-11 (continued) FIGURE A2-12a Special Function Registers and their full hex addresses FC2 FC1 FC0 FC4 FC3 FB8 FE0 FBD FBA FBF FBE FBC FBB FB4 FB5 FB6 FB7 FA9 FA6 FA7 FA8 FEA FE9 FE2 FE1 FDA FD9 FD FEF FE7 FDF FF2 FF1 FF0 F9F FA2 F89 F8A F8B F8C F8D FD3 F9B FF9 FFA FFB F9D FA0 F9E FA1 FEB FE3 FDB F80 F81 F82 F83 F84 FED FE5 FDD FEE FE6 FDE FCB FEC FE4 FDC FF4 FF3 FD0 FAE FAB FAF FB0 FC8 FC9 FC6 FC5 FC7 FD8 FFC FD5 FCD FCA FB1 FF5 FF7 FF6 FF8 FD7 FD6 FCF FCE FCC FB3 FB2 FFE FFD FFF F92 F93 F94 F95 F96 FAD FAC FD1 FE8 . 292 Appendix A2 Interpreting .lst Files C2 C1 C0 C4 C3 B8 E0 BD BA BF BE BC BB B4 B5 B6 B7 A9 A6 A7 A8 EA E9 E2 E1 DA D9 D EF E7 DF F2 F1 F0 9F A2 89 8A 8B 8C 8D D3 9B F9 FA FB 9D A0 9E A1 EB E3 DB 80 81 82 83 84 ED E5 DD EE E6 DE CB EC E4 DC F4 F3 D0 AE AB AF B0 C8 C9 C6 C5 C7 D8 FC D5 CD CA B1 F5 F7 F6 F8 D7 D6 CF CE CC B3 B2 FE FD FF 92 93 94 95 96 AD AC D1 E8 FIGURE A2-12b Special Function Registers and their Access Bank hex addresses . com along with the schematic and parts list for the board. Inc.qwikandlow. If a user wants to add a transducer to the board that has a UART output. Georgia. the link between the PC and RX pins is cut. in Tucker. In this case. H1.. the 100-mil shunt. The jumper can be moved between RX' and RX to run the user code. Then a jumper (i. The RX' pin is connected to a 100kΩ pull-up resistor. to ensure that the RX input does not float. with creative insights from Rick Farmer who developed the board layout and from Bill Kaduck and Dave Cornish of MICRODESIGNS. The cuttable link on the back of the board between the pins labeled PC and RX provide the default connection. the application program must reinitialize the UART so that RXDTP = 0 in the BAUDCON register. The UART circuitry shown in the top left of Figure A3-1 includes an (unpopulated) 3-pin header. The Gerber files for the board artwork are freely available from www. The input is pulled high to match a transducer with a normal idlehigh UART output. a 3-pin header is added to the board. H2X. R4.e. What follows are a few comments to explain some of the circuitry. This undoes QwikBug’s inversion of 293 .Appendix A3 QWIK&LOW BOARD IN DETAIL The Qwik&Low board was designed by the author. in the parts list of Figure A3-2) can be used to connect PC to RX for downloading user code. and the UART output from the new device is connected to the RX' pin of the header (using #30 wirewrap wire). 1 µF 7 VDD 28 VDD 6 VSS 29 VSS 17 16 In-cicuit debugger pins PGD (RB7) PGC (RB6) UART RX (RC7) “Switch to QwikBug” signal PC RX RX' RX TP2 CON1 DB-9F serial port socket for connection to PC 5 3 2 R3 1 kΩ R2 100 kΩ Cuttable link User-defined UART input 1 TX TP1 44 TX (RC6) MCU test points R4 100 kΩ R11 (unpopulated) Y1 32768 Hz crystal C2 15 pF VDD 35 C3 15 pF Timer1 oscillator T1OSO (RC0) 32 T1OSI (RC1) 8-character starburst LCD Varitronix VIM-878-DP-FC-S-LV (Digi-key 153-1113) 20 COM0 19 COM1 18 COM2 17 COM3 SEG0 SEG1 SEG2 SEG3 SEG4 SEG5 35 1 36 2 33 3 24 14 21 15 22 • • • 63 62 61 60 58 55 54 53 52 51 8 6 5 4 3 59 C10 0.1 µF C8 0.1 µF C5 0.1 µF C4 0.1 µF C7 0.1 Ω VDD Banana jacks for digital microammeter +Vin BT1 CR2032 3V coin cell + 18 VPP/MCLR I SW1 Power switch R1 1 MΩ H1 (unpopulated header) C4 0.1 µF C11 0.294 Appendix A3 Qwik&Low Board in Detail MCU PICkit 2 header (unpopulated) PGC PGD GND VDD VPP U3 PIC18LF4321 MCU H3 PB1 Reset pushbutton NC R12 100 Ω R13 51.1 µF LCD test points FOSC/4 TP11 INT0 TP10 INT0 48 SCK TP9 SDI TP8 6390 RC7 TP7 57 56 38 41 19 26 25 20 R15 1 475 kΩ R14 2 475 kΩ R16 475 kΩ 40 VDD VSS VDD VSS VDD VSS AVDDVDDVSS AVSS 64 LCDbias3 COM0 COM1 COM2 COM3 SEG0 SEG1 SEG2 SEG3 SEG4 SEG5 SEG26 SEG27 SEG28 SEG29 SEG30 SEG31 PGC PGDGND VDD VPP/MCLR LCDbias2 LCDbias1 U4 PIC18LF6390 LCD controller FOSC/4 3 RD5 Serial Peripheral Interface 37 SEG26 SEG27 SEG28 SEG29 SEG30 16 SEG31 SCK 34 SCK (RC3) 43 SDI RC7 35 32 SDO (RC5) 42 37 NC 41 38 R17 475 kΩ 7 R18 100 kΩ SW2 4PDT push-to-close push-to-open switch H5 PGC PGD GND VDD VPP LCD PICkit 2 header (unpopulated) FIGURE A3-1 Qwik&Low schematic .1 µF C9 0.1 µF 10 9 C6 0. 6 kΩ VDD AN2 H6 Expansion header GND RA4 KEY RB0 RB3 RD1 RA5 RB1 RD0 39 RD1 38 RD0 UART RX (RC7) TX (RC6) SDO (RC5) SDI (RC4) SCK (RC3) 1 44 43 42 37 U3 Silicon Serial Number LED1 36 CCP1/RC2 35 Timer1 T1OSI (RC1) oscillator T1OSO (RC0) 32 In-circuit debugger pins PGD (RB7) PGC (RB6) RB5 RB4 CCP2/RB3 INT2 (RB2) INT1/RB1 INT0/RB0 17 16 15 14 11 10 9 8 30 Switched power RA7 F /4 − TP6 FOSC/4 (RA6) 31 OSC 24 (AN4) RA5 23 RA4 22 VREF+ −TP3 VREF+(RA3) 21 AN2 (RA2) 1 U1 20 AN1 − TP4 2 Temp. AN1 (RA1) 19 3 sensor AN0 (RA0) POT1 20 kΩ VDD 7.99 kΩ Jumper H2 R9 1 kΩ R8 22.29 GND H4 (unpopulated header) R10 1 MΩ GND VDD SDI SD0 SCK RC2 RB5 RB4 RB3 RB1 RB0 RA5 RA4 AN2 CCP1 CCP2 INT1 INT0 AN4 VDD GND FIGURE A3-1 (continued) .Appendix A3 Qwik&Low Board in Detail 295 U3 PIC18LF4321 MCU RPG1 Detented RPG RPG with integral pushbutton RE2 RE1 RE0 RD7 RD6 To LCD (RD5) RD4 RD3 RD2 Switched R6 27 power 1 MΩ 26 25 Switched power 5 4 Switched power 3 2 41Switched power 40 RD2 − TP5 R7 4.28 6.6 kΩ R5 22. 15.94 0.27 Back of board components = LED1 U1 POT1 CON1 LCD1 BT1 BT1X 1/4” Dia hole SW2 H1 H2 H2X H3.6.38 2.99KFRCT Digi-Key 2 311-22.12 0.92 1.27 17.12 CR2032 coin cell holder 2” x 1” 8-char starburst LCD Female DB-9 socket POT_HFAA 20K Thumbwheel POT TO-92 Temperature sensor T-1 Red LED.10 0.92 1.9 R7 R5.10.34 2.18 0.6.6KFRCT Digi-Key 1 311-51.3 C1.18 0.07 2.90 0.11 R12.36 0.6K 1/4W 1% thick film resistor Yageo RC1206FR-0722K6L 1206 4. VJ1206A150JXACW1BC 0.17 R1.07 2.8.00K 1/4W 1% thick film resistor Yageo RC1206FR-071KL 0.18 0. 3M AWHW10G-0202-T-R KSA0M211 LFT EC11G1524402 108-0051-EVX SJ-5003 (BLACK) 0.296 Quantity Order Number Qwik&Low board C2.25 2.768KHZ-T PIC18LF4321-I/PT DS2401P+ PIC18LF6390-I/PT 1. Yageo RC1206FR-07100RL 0.1KFRCT Digi-Key 2 311-100KFRCT Digi-Key 4 311-475KFRCT Digi-Key 3 311-1. push-off switch (leave this unpopulated) Male straight 2-pin header Tyco AMP Sullins 4-103239-0 SPC02SYAN 0.09 1206 0.18 0.86 2.4 R14.52 3. through-hole mounting Panasonic Analog Dev.05 3.52 3.16.05 3.1uF 50V X7R ceramic capacitor Yageo CC1206KRX7R9BB104 0.72 2.13 Remaining components = Total = 0.10 0. Panasonic Tyco AMP Varitronix MPD Panasonic Johnson E-Switch LN28RALXU AD22103KTZ EVL-HFAA06B24 5747844-4 VIM-878-DP-FC-S-LV BH32T-C CR2032 108-0740-001 TL4201EEYA 0.1K 1/4W 1% thick film resistor Yageo RC1206FR-0751K1L 1206 22.10 R11 Y1 U3 U2 U4 TQFP-64 LCD controller Microchip TSOC-6 Silicon Serial Number Dallas Semi.44 1. TQFP-44 Microcontroller Microchip 32768 Hz watch crystal Abracon 1206 (leave this unpopulated) ABS25-32.00KFRCT Digi-Key 1 311-4.96 2.9.99K 1/4W 1% thick film resistor Yageo RC1206FR-074K99L 0.97 0.37 1.09 0. SPDT toggle switch Four rubber bumpers for feet Assmann Cannon ALPS Mountain Sw.04 0.48 2.27 1206 15 pf 50V NPO ceramic capacitor BC Comp.19 1.7.30 PCBCART 6.97 0.00 Distributor Designation Footprint Part Description Manufacturer Manufacturer’s Part Number Cost Each Total Cost 1 2 BC1305CT Digi-Key 9 311-1179-1 Digi-Key 2 311-100FRCT Digi-Key 2 311-1.34 2.59 0.5 H4 H6 PB1 RPG1 SW1 SIP100_3P SIP100_17P SIP100_6P SIP100_2P 100 mil shunt (leave these unpopulated) (leave this unpopulated) Male shrouded 5x2 pin header Sealed pushbutton switch Detented RPG-PB switch comb.09 0.8 R13 R2.09 0.10 0.00MFRCT Digi-Key Digi-Key 1 535-9166-1 Digi-Key 1 PIC18LF4321-I/PT Digi-Key 1 DS2401P+ Digi-Key 1 PIC18LF6390-I/PT Digi-Key 1 P605 Digi-Key 1 AD22103KTZ Digi-Key 1 P4D2203 Digi-Key 1 A32117 Digi-Key 1 153-1113 Digi-Key 1 BH32T-C Digi-Key 1 P189 Digi-Key 2 J147 Digi-Key 1 EG1874 Digi-Key Appendix A3 1 A26512-40 Digi-Key 1 A26512-40 Digi-Key 1 S9001 Digi-Key 2 A26512-40 Digi-Key 1 A26512-40 Digi-Key 1 HRP10H Digi-Key 1 855-0017 Allied 1 688-EC11G1524402 Mouser 1 108-0051-EVX Mouser Qwik&Low Board in Detail 4 517-SJ-5003BK Mouser FIGURE A3-2 Qwik&Low parts list .47 41.09 1206 100 ohm 1/4W 1% thick film resist.4.25 1.52 23.09 0.19 1.37 1.41 SIP100_3P CR2032 coin cell Nickel plated banana jack 4PDT push-on.09 0.86 2.72 2.15 0.00M 1/4W 1% thick film resistor Yageo 1206 475K 1/4W 1% thick film resistor Yageo RC1206FR-071ML 1206 100K 1/4W 1% thick film resistor Yageo RC1206FR-07100KL RC1206FR-07475KL 1206 51.04 0.09 0.44 1206 1.09 1206 1.5.38 2.18 R3.59 0.09 0. . This is sufficiently accurate so that if an output pin is changed appropriately at intervals of 1. The test points dispersed over the board are designed for the pin probe of a scope. an SOIC part with up to 28 pins).com. A Microchip application engineer intimately involved with the oscillator design suggested this pullup resistor modification.000. not the 3 V supply of the Qwik&Low board.g. one of the few free output pins of the LCD controller. This choice. to test user-generated outputs (e. The unpopulated header also provides solder points for an add-on part installed on the surface-mount pads located on the front or the back of the board. *. the CPU clock for each of the PIC microcontrollers on the board. ≈ 3 MΩ) resistor. For surface-mount parts that do not fit on the available surface-mount patterns (e. The CPU clock of the PIC16F505 is 1 MHz ± 2%. can be monitored.08333 µs ≈ 52 µs then the MCU will read this serial input exactly as it would from a 19. The intent is to be unobtrusive for normal use of the board. The Timer1 crystal oscillator circuitry shown in Figure A3-1 immediately below the UART circuitry includes pads labeled R11. 14-pin PIC16F505 microcontroller providing: • The decoding of the keypad. #) keypad with an 80¢. The intent is to make it possible to add a high-impedance (e. located near the right edge of the board below TP8.200 baud UART. allows a user to gauge the awake/sleep behavior of each chip under varying circumstances. the R4 resistor should be removed from the board.g. especially if water-soluble (i. If a transducer is used with a UART output that idles low. to try to get the Timer1 oscillator to run reliably with the # pragma config LPT10SC = ON configuration choice. In like manner.e.beldynsys. It is labeled on the back of the board. but available for users who wish to explore modifications to the LCD controller’s program code. for a pulse-width measurement on the RC2 or RB0 pin). The prototype area on the board allows DIP parts and discrete parts to be added easily. Point-to-point wiring with #30 wirewrap wire can produce a clean job of the addition.. consider the use of one of the surface-mountto-DIP adapters available from. One interesting addition to the board is a 12-key (0–9. . conductive) flux is used.. RC7. FOSC/4.200 = 52. the reliability of which has not been thoroughly explored. Be sure to remove any solder flux. That low-power oscillator configuration is meant to run with a 5 V supply. would decrease the current draw of the Timer1 oscillator and the Timer1 counter from about 6 µA to 1 µA.000/19. It is unlabeled (but can be probed) on the front of the board.Appendix A3 Qwik&Low Board in Detail 297 the RX input. TP7 is such a test point.. • A bit-banged UART interface. The unpopulated H4 header provides test points for the pin of a scope probe. An output pin on the MCU can be employed in a user program to monitor time intervals of interest. 298 Appendix A3 Qwik&Low Board in Detail 8 1 ← I 6 5 4 3 2 1 H3 6 5 4 3 2 1 H5 8 1 MCU PICkit 2 36 35 34 33 32 31 30 29 28 27 26 LCD PICkit 2 25 24 23 22 21 20 19 LCD Testpoints 1 1 2 3 VDD 1 2 +Vin ON U1 CR2032 3 2 F /4 OSC TP11 1 + SW1 RESET 3 2 INTO TP10 1 SCK TP9 1 4 1 PB1 2 1 SDI TP8 H2 LED1 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 − LCD1 1 2 2 SW2 4 7 10 H4 GND VDD 16 8 8 8 8 8 8 8 8 8 8 8 8 8 15 8 8 8 8 8 8 8 8 8 8 8 8 8 BT1 1 1 Vref+ AN1 TP3 TP4 11 1 5 RX TP2 PC RX RX’ 3 9 5 Qwik&Low 1 2 1 1 SDI SDO SCK IN = LCD ON RC2/CCP1 3 6 9 12 2 5 8 11 14 8 8 8 8 8 8 8 8 8 8 8 8 8 13 8 8 8 8 8 8 8 8 8 8 8 8 8 12 8 8 8 8 8 8 8 8 8 8 8 8 8 11 8 8 8 8 8 8 8 8 8 8 8 8 8 9 4 8 3 7 2 6 1 6 1 H1 1 2 3 RD2 TP5 1 FOSC/4 TP6 RB5 RB4 RB3/CCP2 RB1/INT1 RB0/INT0 RA5/AN4 RA4 AN2 10 8 8 8 8 8 8 8 8 8 8 8 8 8 9 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 8 8 8 8 8 8 8 8 8 6 8 8 8 8 8 8 8 8 8 1 2 5 8 8 8 8 8 8 8 8 8 3 4 4 8 8 8 8 8 8 8 8 8 5 6 RPG1 3 8 8 8 8 8 8 8 8 8 7 8 10 TX TP1 7 6 2 4 VDD GND 8 8 SO−16 / SOT−23 2 8 1 16 8 8 1 8 3 2 3 8 4 5 4 13 8 14 8 2 1 6 15 8 9 10 CON1 H6 8 8 5 1 8 6 2 3 6 5 4 12 8 11 8 8 2 8 5 4 3 7 10 8 RPG/PB POT1 Ground 8 8 9 8 50 mil 8 1 2 3 4 5 6 1 2 3 4 5 6 8 5 2 2 R16 C8 C11 R15 C7 2 2 1 2 2 1 1 2 1 1 1 2 R13 1 1 1 1 R18 R17 1 19 20 21 22 23 24 2 1 R14 27 28 29 30 31 32 33 34 35 36 3 1 2 1 25 26 C10 1 1 U4 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 C6 2 2 3 1 1 1 2 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 2 3 2 1 4 C9 18 1 17 16 15 14 13 12 1 1 C5 1 2 7 6 5 4 3 2 1 11 10 9 8 6390 RC7 TP7 8 8 8 8 8 8 8 8 8 8 8 8 8 6 1 8 8 8 8 8 8 8 8 8 8 8 8 8 5 1 R9 2 1 2 2 2 1 GND VDD 1 10 7 4 1 R12 1 2 1 1 8 8 8 8 8 8 8 8 8 8 8 8 8 4 1 8 8 8 8 8 8 8 8 8 8 8 8 8 3 1 8 8 8 8 8 8 8 8 8 8 8 8 8 2 1 8 8 8 8 8 8 8 8 8 8 8 8 8 1 8 8 8 8 8 8 8 8 8 8 8 8 8 0 1 8 8 8 8 8 8 8 8 8 8 8 8 8 9 1 1 1 8 8 8 8 8 8 8 8 8 8 2 2 2 8 8 8 8 8 8 8 8 8 7 2 1 1 1 1 8 8 8 8 8 8 8 8 8 6 4 3 2 2 2 8 8 8 8 8 8 8 8 8 5 6 5 8 8 8 8 8 8 8 8 8 4 8 7 8 8 8 8 8 8 8 8 8 3 SDI SDO SCK RC2/CCP1 RB5 RB4 RB3/CCP2 RB1/INT1 RB0/INT0 RA5/AN4 RA4 AN2 12 11 8 5 2 R10 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1 2 1 2 2 1 9 6 3 22 21 23 24 25 1 26 27 28 29 2 30 31 C1 1 11 C4 R11 Y1 1 1 1 2 2 1 32 33 34 35 36 37 38 39 40 41 42 43 44 R4 U3 3 2 1 R2 5 9 1 5 9 2 4 1 R7 U2 1 6 2 5 3 4 R1 2 2 4 8 2 3 7 1 1 1 2 6 2 3 2 1 1 C3 C2 1 1 3 2 R3 1 1 2 1 6 10 10 9 R8 8 0.5 mm 1 2 3 4 8 7 6 5 8 8 R6 7 2 8 VDD GND 8 8 4 2 6 2 2 1 8 1 8 8 5 8 R5 8 1 8 2 3 8 4 8 7 6 5 8 8 8 5 8 8 8 0.65 mm Ground 3 1 4 5 Rev 5 8 FIGURE A3-3 Front and back of Qwik&Low board . The LED also blinks every second.00 price shown in Figure A3-2 was the approximate unit price with an order for 30 boards. be sure to consider the alternative of purchasing a built and tested board. This part is actually a 40-pin strip that is designed to be cut with diagonal cutters into headers having the desired number of pins. and H5. and to verify the operation of the Timer1 oscillator and the operation of the potentiometer/ADC combination.com website can be used to place an order for boards. As the potentiometer is turned from full CCW to full CW. The current draw of the board while running this program (with the LED jumper removed and the LCD switched off) is about 20 µA. If the Timer1 oscillator is working correctly.c. See. However. when completed. high-quality boards made in China with a nominal two-week delivery schedule. a PICkit 2 programmer must be available to program the two chips. particularly the two PIC microcontrollers.com website.qwikandlow. PV. Turning the RPG clockwise or counterclockwise also increments/decrements a number sent to the QwikBug console. Chris Bruhn and Peter Ralston have developed a Performance Verification program. Also. call for considerable experience in dealing with fine-pitch parts. A26512-40. the right-hand number changes from 00 to FE or FF. a vendor for having low-cost. This program can be compiled. available from the www. verifying both the chip and the serial interface. loaded via QwikBug. proceed cautiously! As the artwork of Figure A3-3 for the front and the back of the board illustrates.qwikandlow. H3.com). The parts list shows the Qwik&Low board as being manufactured by PCBCART (www. The Gerber files on the www. verifying that no adjacent pins of the display are shorted together. and run. The $6. It then runs the LCD display through four quick tests before moving on to display the temperature. H1.qwikandlow. the middle number on the display will increment every second. Turning the RPG turns on individual segments of the LCD.com/purchase. for all of the single-in-line (SIP) headers. the surface-mount parts for the back of the board.Appendix A3 Qwik&Low Board in Detail 299 The parts list includes the same Digi-Key part number. The LED is turned on in response to the pressing of the RPG’s pushbutton. H2. Before undertaking such a venture. . It initially sends the serial number from the DS2401 chip (Chapter Fifteen) to the QwikBug console. H4.pcbcart. provides an RF bypass for the Allegro chip’s logic supply voltage. As the motor steps. The 3.0 V) is to ensure that the DIR (Direction) and STEP inputs from the Qwik&Low board do not exceed this supply voltage. from the 12 V motor supply voltage.3 V voltage regulator. the DMM will display the average current. R4 300 .3 V (rather than 3. D1. The intent of using a supply voltage of 3. are included to meet the stability requirements of the voltage regulator. C5. TB2Y. The motor current can be monitored by connecting a digital milliammeter between the two pins of the H1 header labeled Vm → I and opening the power switch. C9 and C8. Its 12 V power is supplied by a wall-transformer power supply. (If a higher motor supply voltage is used. The Schottky rectifier.Appendix A4 STEPPER-MOTOR BOARD IN DETAIL The schematic for the stepper-motor controller board discussed in Chapter Eight is shown in Figure A4-1. This current is set by the values of the two current-sensing resistors. The 0. it must not exceed the 20 V maximum input specification of this voltage regulator. is present to reduce the risk of burning out the board circuitry by inadvertently plugging in a wrong wall transformer having its polarity reversed.) The input and output capacitors. U1.1 µF ceramic capacitor. derives the logic supply voltage used by the controller chip. U2. 01 µF H2 (Unpopulated) Cuttable link Motor current control Components mounted on stand TB2X LED TB2Y Toggle Switch DMM (Measure motor current) TB1X Stepper motor 301 .CON1X Wall transformer for 12 V @ 0.3 V PWM TB1 Terminal block R B W Y 21 16 9 4 OUT1B OUT1A OUT2A OUT2B SENSE2 8 R5 (Unpopulated) R4 1.1 kΩ D1 Schottky rectifier VCC 1 REF RESET SLEEP VCC 14 VCC 24 Cuttable link MS2 13 VCC H4 MS2 MS1 (Unpopulated VCC header) Cuttable links 22 3 TB2 Terminal R9 block 10 kΩ B R S S H1 Vm 5 VLOAD1 GND GND VLOAD2 GND GND SENSE1 ENABLE 15 17 R7 (Unpopulated) R6 1.1 kΩ POT1 100 kΩ (Unpopulated) RC1 Imotor I 7 VCC 20 + C7 33 µF 19 18 PWM 6 + C1 33 µF 23 PWM C6 0.1 mm barrel connector U1 Allegro Microsystems A3967SLB-T (24-pin SOIC) 11 DIR STEP R2 51.5 A regulated power supply Input protection circuit R10 1.00 kΩ R1 51.001 µF R8 51.1 kΩ POT2 100 kΩ (Unpopulated) C9 0.3 V Voltage regulator MS1 12 MS2 MS1 0 0 1 1 0 1 0 1 K E Y Input header R11 1.00 kΩ 10 Appendix A4 Stepper-Motor Board in Detail FIGURE A4-1 Stepper motor driver board Full-step operation(default) Half-step operation Quarter-step operation Eighth-step operation POT3 20 kΩ (Unpopulated) Slow-mixed-fast decay control (Default is slow decay) PWM frequency control 3.5 Ω C4 0.001 µF R3 51.1 µF C8 33 µF PFD C5 0.1 µF U2 3.01 µF RC2 2 C2 0.5 Ω C3 0.1 kΩ D2 VCC H3 Shrouded header CON1 2. the power supply voltage is cut off from the motor winding. or 1. The stepper motor listed in the parts list of Figure A4-2 steps 200 full steps per revolution. When full stepping (the default stepping mode).3 V. both windings are energized with this (±) current at each step position for a total load of 386 mA for the wall transformer. With this pin voltage defaulting to 3.com/stepper_support/ for information on obtaining the bare stepper-motor controller board. shown in the lower-right corner of Figure A4-1. The Allegro chip is designed to be able to drive each of the two stepper-motor windings with a voltage of up to 30 V and a current of up to ±750 mA. Check with www. cutting the two links on the back of the board as shown near the upper right of Figure A4-1. The Allegro chip carries out full stepping by alternately reversing the current in one winding and then the other winding. At that point. The winding current decays for a time determined by C2−R3 (for one winding) or C6−R8 (for the other one). The rate of decay is determined by the voltage on the PFD pin of Figure A4-1. parts. 800 s/r. for any of the other modes. Each motor winding is subjected to a current that alternates between ramping up and decaying down. 3–4 .707 times that value. between a maximum equal to that found for full stepping and a minimum equal to 0. In contrast to the Qwik&Low board. When operating in the fullstep mode. if both center pins are connected to the bottom pins of H4. with minimum current ripple. a help for checking the board. and then adding two jumpers to select the stepping mode. these are relatively large (for surfacemount parts). eighth-step operation will result. With Rs = 1. albeit with increased audible noise and vibration. While the total current drawn from the wall transformer for full stepping is constant. The pulse-width-modulation (PWM) control circuit defaults to the nominal RC values suggested by Allegro in the data sheet for this driver chip.707 × VREF 292 Iwinding = ± ___________ = ± ____ mA Rs 8 × Rs with VREF = 3.qwikandlow. The maximum stepping rate is evidently achieved with the fast decay setting of 0 V on the PFD pin.5Ω. Even finer resolution (i.e. the current decays relatively slowly. the stepper-motor board is a simpler board to build. and a stepper motor..302 Appendix A4 Stepper-Motor Board in Detail and R6. 400 s/r. the 12 V power supply voltage is applied across the winding until the voltage across the current-sensing resistor crosses its threshold voltage.600 s/r) can be achieved by adding a 2 × 3 pin header in the H4 header pattern on the board. 1 Allegro Microsystems Technical Paper STP 01-2.3 V. pp. When one of the winding currents is low. The resistors are stamped with their resistor values. the total current varies with the step position. Figure A4-3 shows the front and back artwork. the current in each winding is approximated by the equation1 0. Iwinding = 194 mA. Even though the board employs size 1206 surface-mount resistors and capacitors. For example. 23 0. side adjust trimpot 100K 1 turn.20 0.50 0.79 0.1uF 50V X7R ceramic capacitor 33uF 35V electrolytic capacitor PCBCART Yageo Yageo Yageo Panasonic 4.00 0.04 0.2W 5% thick film resistor 20K 1 turn.09 0.18 0.75 1.08 3.2 H2.18 0.50 0.45 Appendix A4 Stepper-Motor Board in Detail x x x x x 2 1 4 2 2 0 1 2 2 1 1 2 1 1 1 1 DO-41 SOT-23 DPAK SOIC-24 0.36” Digi-Key Digi-Key Digi-Key Digi-Key U1 TB1.11 R9 R1.38 5.30 0.08 0.10 0.38 CUI Inc.23 0. side adjust trimpot Male straight 2 row x 3 pin header Male straight 7x1 header with 2. 5 feet 30V.09 0.001uF 50V X7R ceramic capacitor 0. 0.60 1.25” Dia.75 Phoenix 0.59 0. right angle 2.3.90 0.09 0.15 Designation Footprint Part Description Manufacturer 1 2 2 2 3 311-1170-1 311-1174-1 311-1179-1 P835 4.1mm barrel connector for power 12V@0. Assmann Elect.36 0.32 0.00 Allegro 2.6 C3. 5.00 3M Keystone Building Fasteners Building Fasteners 0.00KFRCT 311-10.1KFRCT P1.2ASCT 490-2839 490-2834 S2011E-36 S1011E-36 HRP10H HKC10H AE10G-5 1N5818 BAT54C-FDICT MC33269DTRK-3OSCT Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key Digi-Key R10.3V voltage regulator Yageo Yageo Yageo Panasonic Panasonic Panasonic Murata Murata Sullins ($2.02 Parts for motor and stand = Total = 0.02 0.59 1.22 1 2 1 1 620-1073 277-1736 CP-202A T983-P5P 1 Digi-Key Digi-Key TB2X TB2Y 4mm Dia.0K 1/4W 1% thick film resistor 51.2 ohm 1.00K 1/4W 1% thick film resistor 10.36 0.70 3.70 3. 8.36 0.8 ohm 1.20 0.0KFRCT 311-51.90 CUI Stack 0.45 10.04 27. 6-32 1 1 1 Mouser Digi-Key Digi-Key Digi-Key Bolt Depot Bolt Depot Bolt Depot Bolt Depot 1/4” round 350-1592 EG2446 4 4 4 4 4 2 2 2 517-SJ-5003BK 2036K H781 H216 3011 7914 3012 2643 Total Cost 303 FIGURE A4-2 Stepper Motor Driver parts list .38 Stepper driver board + power = Applied Motion Dialight E-Switch 4.58 0.60 1.27” 0.00 2. Stepper motor driver board 0.72 0.2W 5% thick film resistor 1.38 48.01uF 50V X7R ceramic capacitor 0.18 0.79 2. Assmann Elect.26”x0.36 0. 6 Hex machine screw nuts.23 0.5 ohm 1.9 C1.90 0.2 CON1 CON1X Motor driver.09 0. 5mm Dia.00 2.45 10.1K 1/4W 1% thick film resistor 1.7 POT3 POT1.51/36pins) Assmann Elect.57”x0.27” 3x2 pin header 7x1 pin header 1. 1/8” long 4-40 x 3/8” machine screw 4-40 hex nut Internal tooth lock washers.6 R5.80 0.30 0.4 H1 H3 H3X H3Y D1 D2 U2 1206 1206 1206 1210 1210 1210 0.02 0. 280mA/phase Panel-mounted blue LED SPDT toggle switch Aluminum stand Four rubber feet for aluminum stand Round spacer for 4-40 screw. Vishay Diodes Inc.8 R4.7 R5.32 0.2.8ASCT P1.79 2.6 removed Male shrouded 100 mil header.79 0.36 0.8 1206 1206 1206 0.50 0.26”x0.72 0.Cost Each Unpopulated Quantity Distributor Part Number Digi-Key Digi-Key Digi-Key Digi-Key C2.09 0. A3967SLB-T 4-conductor terminal block.00 0.36” 0.09 0.80 0.4.52 0. 6-32 x 1-1/2 Internal tooth lock washers. 163395 Jameco TB1X Bipolar stepper motor. 5x2 pins Mating female ribbon cable connector 10-conductor ribbon cable.79 1.7.08 0.5ASCT P1.57”x0.1A Schottky rectifier Dual Schottky diode 3.84 4.38 20.18 0.5A regulated wall wart 311-1.4 C5.08 0. ON Semi.4V.46 0.2W 5% thick film resistor 1.74/72pins) Sullins ($1. 4 Socket head screws. 304 1 TB1 1 2 3 4 TB2 1 2 3 4 2 3 1 H1 2 1 1 1 Appendix A4 Stepper-Motor Board in Detail 1 1 3 2 2 4 1 3 2 1 2 1 4 3 2 1 2 1 4 3 2 1 1 Ground 6 4 2 5 3 1 8 8 2 1 10 9 5 6 7 8 3 4 5 6 1 2 3 4 1 2 3 2 1 3 2 1 3 2 1 1 Vm U1 1 1 24 2 2 1 2 2 3 22 1 1 2 23 4 1 2 21 2 5 1 6 19 1 R3 C2 C1 + 20 R8 C6 C7 + D1 CON1 7 3 8 17 2 2 18 9 16 1 11 1 2 1 12 13 2 14 2 10 15 4 4 R2 R1 C5 U2 H2 2 1 2 1 1 2 8 1 3 4 2 2 1 8 2 3 1 2 1 2 1 1 2 5 6 R5 C3 R4 POT1 2 4 6 R7 C4 R6 D2 POT2 POT3 R11 2 1 1 3 1 1 2 3 1 2 3 1 2 B R S S 1 R B W Y R9 Rev 2 Stepper Driver 3 1 C9 2 1 I 3.3 V PWM MS2 MS1 H4 R10 3 2 4 6 8 10 Ground 5 1 3 5 7 + 1 2 C8 9 1 H3 FIGURE A4-3 Front and back of Stepper Driver board . . 89. 33 Global variables vs. 280 Average current intermittent sleep mode. 257 Bit manipulations in C. 221 LCD. 15. 215 Editor. 51 Digital inputs vs. 27 Keypad interface. 289 of RAM variables. 79 ASCII conversion of a hex digit. 89 effect of separate handlers. global variables. 21 block diagram. 277 MCU (microcontroller unit) block diagram. 297 LCD (liquid crystal display). interrupt vectoring.c. 55 Lst files. 119 ADT7301 temperature sensor. 159 high.and low-priority. 61 Displayable characters. 23 example (table). 251 Analog vs. 59 starburst segment coding. 219 controller test points. 51 Loop time via Timer1. 163 sources (table). 19 Compilation of C code. 127 AD5601 DAC. 233 Learning curve. 229 BDM (Background Debug Mode) vector.INDEX AD22103 temperature sensor. 62 DMM. outputs. 58. 56 Configuration selections. Crimson. 221 Fosc/4 test point. 17 CPU registers. 38 schematic. 21 block diagram. 54 Direct addressing of CPU. 14 Local vs. 31 DS2415 1-wire time chip. 288 Crystal oscillator. 241 Indirect addressing of CPU of program memory. 223 schematic. 246 Delay macro. 222. 150 Coin cell (CR2032) aging. 53 306 . 294 SPI interface. 54 ASCII and ASCIID functions. 81 Assembly language instruction set. 166 INTOSC internal oscillator. 37 characteristics. 22 calibration. 286 Interrupts. 290 ASCII4 and ASCII4D functions. 50. 32 pin. 282 Display function. 193 Electronix Express (. 223 multiplexed waveforms. 91 via watchdog timer. 278 iButton. 165 I2C bus. 173 INTRC low-power internal oscillator. 56. 27 and interrupts. 294 DAC (digital-to-analog converter). 28 Calibrate. 246 ADC (analog-to-digital converter). 187 EEtest. 17 address. 50 Breakout timer. 181 capture mode (figure). 38. 57 EEPROM. 213 Idle mode current (table).elexp. 31 Expansion header. 182 C18 utility. local variables. 16 clock rate decision. 22 effect on run/idle mode current. 134 Harvard architecture. 176 CCP1 and CCP2 modules. 49 C programming language use.com). digital I/O pins. 26 Awakening vs. 40 4PDT switch. 47 without QwikBug. 51 Gray code.c. 68 Display strings. 219 controller. 229 Brownout reset module (figure). 50. 170 Timer1.c. 13 5 billion microcontrollers. 213 Open-drain output. 31 Monotonic DAC output. 69 Timer0. 293. 247 Motorola. 142 polled RPG function.c. 94 Timer1 oscillator.c. 32 signal inversion. 303 schematic. 17. 301 Switch debouncing. 251 with voltage output. 17.com. 44 I/O connections. 32. Stop. 68 Pushbutton debouncing. 201 for multiple devices. 78 1-wire interface. 113.c template. 296 schematic. 154 OSCTUNE register. 54 TXascii macro. 98 Temperature sensor with SPI output. 278 Power-on resetting of MCU and LCD controller. cover. 213 Time function. 85 Stepper motor.c. 154 Start. 20 PICkit 2 programmer. 137 RPGcounter function for interrupt-driven RPG. 23 pin use (table). 107 stepping code. 25 T1.Index 307 current draw vs. 58. 17. 15 C18 compiler. 72 Watchdog timer. 201 SSN. 78 UART. 138 Serial test port. 183 in Measure. 67. performance verification program. frequency (chart).c template. 201 Oscilloscope for loop time measurement. 24 www. 249 SSN (silicon serial number). 298 parts list. 29. 153 persist mode. 32. 155 useful work in main loop. 241 MOSI/MISO terminology. 71 QwikProgram 2 utility. 91 Timer3. 66. 294 Measure. 15 Nop macro. 114.c template. 169 Parasitic power. 32. 19 MICRODESIGNS. 258 . 96 Totem-pole output. and Send functions. 304 parts list. 69 PV. 27. 33 SFRs (special-function registers) 8-bit parts of 16-bit SFRs. 17. 202 TRIS registers for input/output choice. 300. 291 SPI (Serial Peripheral Interface). 258 Pipelined operation of CPU. 141 for polled operation. 56 Number-to-ASCII conversion. 299 Qwik&Low board. 162 Sleep plus Nop macro combination.c. 63 T3. 53 Shadow registers. 294 QwikBug. 32. 133 interrupt-driven RPG. 219 PIC18LFxxxx family features. 41 schematic. 115 Stepper motor driver board. 17. 256 console window. 57 nanoWatt Technology. 32 USB-to-serial adapter.qwikandlow. 202 PIC18LF6390. 206 Start and Stop macros. 132 Thermochron parts. 127 TenthsFahr. 258 RPG (rotary pulse generator). 25 function. 52 for time interval measurement. 156 Microchip Technology Steve Sanghi. 82 Measurement interrupt duration. 56 Special Function Register addresses. 55 T2.c template.
https://www.scribd.com/doc/99949600/PIC-Microprocessor-circuit-design
CC-MAIN-2017-13
refinedweb
86,345
66.54
JA-SIG CAS Client Plugin for Grails Introduction This plugin provides a simple way of enabling JA-SIG CAS client integration. Current release version is 1.0 and it is strongly recommended to upgrade to this version. It uses CAS Java Client, which is a less complicated client library with fewer dependencies compared to another Java client called CAS Client for Java. Although the latter is developed with Spring Framework in mind, I personally think it is too heavy to be). Prerequisite The plugin is developed with Grails As a Grails plugin, it couldn't be easier to install it. 'grails install-plugins' should be able to take care of that from either locally downloaded file or remote plugin repository. grails list-plugins should give you a list of available plugins. grails install-plugin cas-client [current-release-version] should install this plugin from remote repository. grails install-plugin /path/to/local/cas/cliet/plugin.zip will install from a locally downloaded file. Please click here to download the latest version, in case the 'grails list-plugins' or 'grails install-plugin' is not responding. Usage As mentioned above, the plugin requires some extra work in Config.groovy to make CAS server and local parameters known to the plugin. So in application's Config.groovy you may add some lines of code below, // Last but not least, there are parameters to control the plugin instead of the behaviour of underlying CAS client library: Examples Simple Solution for Authorization First of all, as users of JA-SIG CAS may already know, CAS is only for authentication but not for authorization (up to 2.x). Therefore authorization is down to users to implement, if necessary. A common pattern is to use the interceptors available with Grails, For instance, you can have a controller AccessController like this, with this plugin installed import edu.yale.its.tp.cas.client.filter.CASFilter class AccessController { def beforeInterceptor = [action: this.&check] def check() { def username = session?.getAttribute(CASFilter.CAS_FILTER_USER) // check username and return a boolean accordingly. // ... } } Please note it looks different from the example controller showed in Grails user guide for before interceptors because: - To take the above example further, a simpler solution is available, In Config.groovy you can have a list of users allowed to access your application, users = ['foo', 'bar'] and then the 'check' method above will look like, def check() { def username = session?.getAttribute(CASFilter.CAS_FILTER_USER)?.toLowerCase() return username in grailsApplication.config.users } That could be helpful if your application has a simple authorization need. Handling Large Number of Protected URLs The plugin can handle a list of urls using 'cas.urlPattern' but it can be quite messy to list every one of them. Thanks to this mailing list post, you can group all the urls to be protected by the plugin using Grails URL mappings feature and then feed the url pattern after mapping to the plugin. Misc. CHANGELOG TODO - upgrade to coming new release of the cas client library which contains a simple authorization utility that can replace the trick mentioned in the example above. Also pls submit your suggestions to Grails users list. Suggestions or Comments Please feel free to submit them in Grails users mailing list. Alternatively you can contact the author of the plugin directly, Chen Wang, contact at chenwang dot org
http://www.grails.org/CAS+Client+Plugin
crawl-001
refinedweb
553
55.34
On Thu, Mar 17, 2011 at 05:29:51PM +0100, Vladimir 'φ-coder/phcoder' Serbinenko wrote: > On 17.03.2011 17:09, Lennart Sorensen wrote: > > On Wed, Mar 16, 2011 at 11:16:05PM +0100, Vladimir 'φ-coder/phcoder' > > Serbinenko wrote: > > > >> It's not really a fixup. Correct return on no error is CF=0 AH=0. Some > >> BIOSes in some other functions returned CF=0, AH!= 0 on no error so it > >> was a wild guess. > >> > >>> Failed int13_ext call: ah=42, drive=80, dap= 6fe00 returned eax=8000 > >>> > >>> > >> Error 0x80 according to > >> means timeout. > >> Following code would retry on timeout: > >> === modified file 'grub-core/disk/i386/pc/biosdisk.c' > >> --- grub-core/disk/i386/pc/biosdisk.c 2011-01-04 14:42:47 +0000 > >> +++ grub-core/disk/i386/pc/biosdisk.c 2011-03-16 22:13:12 +0000 > >> @@ -72,6 +72,8 @@ > >> grub_biosdisk_rw_int13_extensions (int ah, int drive, void *dap) > >> { > >> struct grub_bios_int_registers regs; > >> + int tries = 4; > >> + retry: > >> regs.eax = ah << 8; > >> /* compute the address of disk_address_packet */ > >> regs.ds = (((grub_addr_t) dap) & 0xffff0000) >> 4; > >> @@ -80,6 +82,16 @@ > >> regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; > >> > >> grub_bios_interrupt (0x13, ®s); > >> + if (!(regs.flags & GRUB_CPU_INT_FLAGS_CARRY)) > >> + return 0; > >> + > >> + if (((regs.eax >> 8) & 0xff) == 0x80 && tries) > >> + { > >> + grub_millisleep (10); > >> + tries--; > >> + goto retry; > >> + } > >> + > >> return (regs.eax >> 8) & 0xff; > >> } > >> > > So that didn't make any difference to it. > > > > It just keeps returning 0x8000 in eax on every retry. > > > > > Another wild guess: > @@ -506,6 +520,8 @@ get_safe_sectors (grub_disk_addr_t secto > grub_size_t size; > grub_uint32_t offset; > > + return 1; > + > /* OFFSET = SECTOR % SECTORS */ > grub_divmod64 (sector, sectors, &offset); No go either. Here is what I see with some more debugging: [snip] int13_ext call: ah=42, drive=80, dap= 6fe00 (len=16 rsvd=0 blks=1 buf=1744830464 sec=2078) int13_ext call: ah=42, drive=80, dap= 6fe00 (len=16 rsvd=0 blks=1 buf=1744830464 sec=2079) int13_ext call: ah=42, drive=80, dap= 6fe00 (len=16 rsvd=0 blks=1 buf=1744830464 sec=72091664) failed int13_ext call: ah=42, drive=80, dap= 6fe00 returned eax=8000 error: hd0 out of disk. Entering rescue mode... grub rescue> Now it has no excuse for failing a call for sector 72091664 when the drive has 156000000 or so sectors. I imagine if I made a small boot partition (less than 8G), the stupid thing would boot fine, but that's not acceptable on a brand new design. I am going to try resizing the partition as a test. -- Len Sorensen
http://lists.gnu.org/archive/html/grub-devel/2011-03/msg00033.html
CC-MAIN-2013-48
refinedweb
396
73.88
In this program, you will learn how to java program check whether Your friend is older or you. We will use the LocalDate method to calculate your age. Then we will compare your age(day, month, year) with your friend’s age. How the program will work? - First of all, we will calculate your and your friend’s age. - If your age is greater than your friend then print “You are older”. - If your friend age is greater than your then print “Your friend is older” - Same step 2 and 3 is check for months and date. Lets write this logic in a Java Program. Example: Yourage=18-10-1992 Yourfriendage=18-10-1992 if (Yourage > Yourfriendage) You are older ! else if (Yourage < Yourfriendage) Your Friend is older ! else if (Yourage==Yourfriendage) You and your friend has born on same day! Example: Program to get birth dates and find who is older In this program, we have used a scanner to read the birth date and the program check whether your age is greater than your friend or not. To understand this program you should have basic knowledge of LocalDate and if-else-if statement in Core java programming. import java.time.LocalDate; import java.time.Period; import java.util.Scanner; public class find_who_is_older { public static void main(String[] args){ Scanner sc = new Scanner(System.in); //Your birth date System.out.println("Enter Your birth date:"); System.out.print("date: "); int urDate = sc.nextInt(); System.out.print("Month: "); int urMonth = sc.nextInt(); System.out.print("Year: "); int urYear = sc.nextInt(); LocalDate l = LocalDate.of(urYear, urMonth, urDate); LocalDate now = LocalDate.now(); Period diff = Period.between(l, now); //Friend birth date System.out.println("Enter Your Friend birth date:"); System.out.print("date: "); int fDate = sc.nextInt(); System.out.print("Month: "); int fMonth = sc.nextInt(); System.out.print("Year: "); int fYear = sc.nextInt(); LocalDate l1 = LocalDate.of(fYear, fMonth, fDate); Period diff1 = Period.between(l1, now); if(diff.getYears()>diff1.getYears()){ System.out.println("You are older !"); } else if(diff.getYears()<diff1.getYears()){ System.out.println("Your Friend is older !"); } else if(diff.getYears() == diff1.getYears()){ if(diff.getMonths()>diff1.getMonths()){ System.out.println("You are older !"); } else if(diff.getMonths()<diff1.getMonths()){ System.out.println("Your Friend is older !"); } else if(diff.getMonths() == diff1.getMonths()){ if(diff.getDays()>diff1.getDays()){ System.out.println("You are older !"); } else if(diff.getDays()<diff1.getDays()){ System.out.println("Your Friend is older !"); } else if(diff.getDays() == diff1.getDays()){ System.out.println("You and your friend has born on same day!"); } } } } Output: Enter Your birth date: date: 22 Month: 11 Year: 1998 Enter Your Friend birth date: date: 3 Month: 1 Year: 1987 Your Friend is older ! Recommended: - Java Program to Add Two Integers - Java program to convert Hexadecimal to octal number? - How do you reverse a number without a loop in Java? - Java program to check if the number is greater than 100 or not
https://quizforexam.com/java-program-to-get-birth-dates-and-find-who-is-older/
CC-MAIN-2021-21
refinedweb
492
54.08
C# for Java Developers 382 First things firstFirst of all, let's deal with the Microsoft issue. I was surprised to find that this book even existed given the problems MS has had in the courts recently. I was even more surprised to find that C# for Java Developers is very balanced and does not hype up C# at the expense of Java -- throughout the book there are places where the authors say that "Java is better at this" or "We have no idea what the C# designers were thinking." A refreshing attitude from a company that is not known to be an admirer of Java. I was reluctant to pay for a Microsoft book, but I have to admit that I am impressed. This is the first MS book I have ever purchased, and it is clearly written, well thought-out and very, very comprehensive. One of the best features for me is that all of the instructions for compiling and managing code assume that you are using the command-line tools, rather than Visual Studio. For someone on a tight budget, this was a real bonus. The Scoop The first part of the book is an overview of .NET, and contains the boiler-plate description that you get from the .NET web site. Not that useful, but pretty short. There is a chapter that compares .NET to Java (J2SE and J2EE), but again, there is nothing new or important there. The second part of the book covers the C# language, using Java as a starting point. The coverage seems comprehensive, and explains where the two languages are the same (quite often), where they are different (now and then) and when they appear to be the same, but you are likely to spend a couple of hours tracking down something weird (more often than I would like). I had started playing around with C# before buying this book, and all of the problems that I had in the early days were detailed here with clear explanations. Part three delves into the .NET class library, covering basic topics such as collections, IO and handling XML. Once again, I was impressed with the depth of coverage and the way in which the authors use Java classes to explain the workings of .NET. It was while I was reading through this section that I realized just how different C#/.NET and Java can be. The last part of the book covers "advanced" topics. There seems to be little reason for the division between basic and advanced topics, but chapters cover areas such as threading, security and networking. The one thing that is consistent in this part of the book is that there is less of a parallel between Java and C#. For example, "Windows Forms" is used to build client UI applications, but is very different toolkit from Swing/AWT. The appendix list is a little dull, covering topics like GC and configuration files. There are some interesting snippets, but I got the impression that these were topics that the authors thought were important, but didn't know where else they should go. The exception is the "Java to .NET API Reference" which, for me at least, sets this book apart from the competition. Every class from the J2SE class library is mapped to an equivalent .NET class and a reference to where the topic is covered in the book -- having something like this has saved me hours of searching. What's to Consider? This book uses a lot of C# fragments to demonstrate how classes are used, but contains very few full "working" examples. I found this to be great once I knew the basics of C# (because I could focus on the topic), but difficult at first (because I could not play with complete code). C# for Java Developers covers much more of the .NET Framework than the other books in my local bookstore, but because of this the text can be dense at times, as the authors try and pack in a bit too much detail. I can't find major fault with this book, and a (small) part of me admires Microsoft for publishing such an unbiased book. Summary If you are a Java programmer who wants or needs to learn about C# and .NET, then this is a great book. Don't be put off by the Microsoft logo, and bear in mind that you don't need a copy of Visual Studio to follow the examples. The book effectively uses Java as a tool to teach C# and explain the workings of .NET. If you are like me, then you will find this book invaluable and will likely keep it close at hand for quick reference. Table of Contents - Introducing .NET - Introduction to Microsoft .NET - Comparing Java and .NET Technologies - The C# Language - Creating Assemblies - Language and Syntax Features - Data Types - Advanced Language Features - Programming .NET with C# - Strings and Regular Expressions - Numbers and Dates - Collections - Streams, Files, and I/O - XML Processing - Advanced Topics - Reflection - Threading and Synchronization - Networking - Remoting - Database Connectivity - Security and Cryptography - Graphics and UI - Introduction to XML Web Services - Appendices - Platform Integration - Shared Assemblies - Configuring Applications - Garbage Collection - Cross-Language Code Interoperability - Java to .NET API Reference You can purchase C# for Java Developers from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. C# may not stand for long... (Score:4, Insightful) But I think C# will be used to convert the C, C++, and Java crowd into the Yeah, I think C# is MS's way to convert everyone to VB.NET. Luckily, Re:C# may not stand for long... (Score:5, Informative) No one at Microsoft likes VB.NET. It was meant as a crutch to get old VB developers into the new programming model. All of the Re:C# may not stand for long... (Score:2) Re:C# may not stand for long... (Score:2) Seems reasonable: get the competition using product. Re:C# may not stand for long... (Score:2) Re:C# may not stand for long... (Score:2) Re:C# may not stand for long... (Score:2) I love VB.NET. On the scale of most flexible to least flexible, you've got managed c++, C#, and VB.NET, however, the difference in capabilities between C# and VB.NET is so miniscule that i suspect that if i were in a situation that vb.net didn't address, i'd do it in MC++ and expose it to VB.NET anyhow. So for me C# is the niche language - its for people that are too snobby to use VB, and does't really have any day-to-day benefits over C#. I happen to love the case-insensitivity, and the code-block autocompletion. Finally, the background IDE-mode compiler is fantastic. VB.NET is easily the most productive development tool i've ever used. For grins, I loaded up one of my old unix C++ apps in xemacs and hacked around on it. c++ on solaris with xemacs and ddd is nowhere CLOSE to the ease of use and quick turnaround from idea to debugged code, for me anyway VB.NET (Score:3, Informative) I'm not a big fan of VBisms such as "MustOverride", "MustInherit", "NotInheritable" etc, which can easily become unreadably verbose for my taste as you combine them, but after trying it out for a couple of simple apps as an experiment I find it an outstanding improvement over the original VB. I think it's perfectly feasible to build a relatively big project in VB.NET without destroying some hardware and going on Prozac, as I would expect with any other VB. Not that I would, but it has become a matter of taste or distaste for the VB-like syntax, not a major disfunctionality of the language itself. VB.NET is a crutch. But it's a crutch that manages to fix VB as a language. I consider that an achievement, to say the least. Re:C# may not stand for long... (Score:2, Insightful) You're right, I think it is a much nicer alternative to Java for client side apps. "But I think C# will be used to convert the C, C++, and Java crowd into the C# is far from just a tool to convert people to the "Yeah, I think C# is MS's way to convert everyone to VB.NET." I think its other way around. "Luckily, True. I refuse to use ASP.NET on IIS since IIS is such a crock. I hope Mono keeps going strong for client side however. Re:C# may not stand for long... (Score:2) I think the opposite. C# is made easier than C++. VB.NET is *very* rewritten in But, of course, due to the nature of However, C# wasn't written to match VB.NET. VB.NET, on the other hand, went throught one of its greatest rewrites so far to match C#. Make up what you want from that. Re:C# may not stand for long... (Score:2, Interesting) The There you go. Pipe that to wc -w and I think you'll find I win. graspee Re:C# may not stand for long... (Score:2) Re:C# may not stand for long... (Score:2) Re:C# may not stand for long... (Score:3, Interesting) So you can run it on FreeDSD or Linux using Rotor or Mono. Re:C# may not stand for long... (Score:2) Rotor and Mono are merely opportunistic parasites in the Re:C# may not stand for long... (Score:2) There's a huge difference between cloning the CLR and the Dotnet Framework, that's why most serious cross-(hardware)-platform apps on Linux use Java, Python or Perl. Re:C# may not stand for long... (Score:2) Really? [go-mono.com] Bytecode has its place (Score:2) We've already heard about Windows CE.NET, which runs on ARM. MS has released a "preview" of a 64-bit version of Windows for Itanium, and it is making noises about a new version optimzed for the AMD Opteron. I believe MS intends to eventually produce one deliverable (the CLR bytecode assembly) which will be compiled into native code on the ARM, x86, Itanium and Opteron, with different optimizations for each. Also, one of the concepts I like about the CLR is the possibility of optimizing for your platform at the last possible moment. Imagine having different JIT compilers for Pentium III, Pentium IV and the Athlon, producing a different executable depending on your machine. I doubt it will happen, though. Re:Bytecode has its place (Score:2) ARM has an extension for their chips that allows them to run many (not all) java bytecodes as native instructions. The future is now! Re:Bytecode has its place (Score:2) I know Java does that. I've run gcj, Supercede (an old Asymetrix IDE) and the experimental native compiler from IBM (later rolled up into Visual Age Enterprise), and they all produce native executables. My point is that Microsoft seems to want that flexibility in deployment for their products... So they can (for example) do one release of Money.NET (or whatever, just an example) without having to place multiple executables on the CD for Pentium, Itanium and Opteron. They did it before with NT 3.x... I remember 3.5.1 having i386, ppc, mips and alpha directories on the install CD. ARM has an extension for their chips that allows them to run many (not all) java bytecodes as native instructions. Really? That's very cool! I didn't know that... There must be some really good JVMs using these shortcuts. The future is now! Agreed. Re:C# may not stand for long... (Score:2) An attempt at a multi-linguange Java clone because MS is afraid of Java, and they copy what scares them (regardless of the merit of the monster). Re:C# may not stand for long... (Score:2) In the process, I discovered a couple articles (no obvious bias from MS) comparing C# and Java. More than convince me of C#'s merits though, I discovered 4 things lacking in Java that utterly turn me off of the language: no passing by reference, no preprocessor directives (and hence no conditional compilation), no enums, and no overloaded operators. Sure, in each of those cases it's possible to work around the problem, but in each of the cases it would make the code less readable. Also, having done C++ for a while, I feel that I shouldn't have to work around them. C# includes support for all four of these features, while still fixing most of the problems that I suspect led Java's developers to not include them. Now, whether the benefits I see in the language of C# outweigh the drawbacks of it being MS (if you see it that way) is a matter of opinion. For me, I'm going with C# for stuff I write for Windows, but will stick with C++ for things I want to be cross-platform. EvanED has it wrong I think. (Score:2, Interesting) For someone who has done a good deal of research on languages, I find it odd that you should point to four of THE most superficial differences. Had you pointed to differences between the CLR and the JVM, you might have had an audience. Instead, you rehashed the oulde argument between C++ and Java. Who won that debate? The people who realized that it was a waste of time to argue THESE points. EvanED, I wish you well in your research. I would like to point out to you that there is not a junior college on Earth that will give you any extra credit for your penetrating analysis. Sincerely, sweet jonnie Re:C# may not stand for long... (Score:2, Informative) Will anyone take the challenge, I wonder? Don't confuse this with advocacy, Microsoft.NET is a product, note not a standard, intended to develop enterprise class web services. Microsoft.NET is comprised of ASP.NET, Microsoft.NET is mostly a rewrite of Windows DNA with enhanced language support and web services. The primary 'benefit' is language independence and inter-operability. The There are several pluses for the Mircosoft.NET framework and a great deal of draws with J2EE. The programming model is simpler than J2EE. The Terrarium (Score:3, Interesting) The thing that finally got me to play with C# was Terrarium [gotdotnet.com]. Players create 'creatures' which then compete in a peer-to-peer set of virtual terrariums. You can create plants, herbivores, or carnivores. It was quite fun (in a super geek way) and VERY challenging. Refreshing indeed (Score:2, Interesting) Try finding that balance in a Java book, most of which devote all of Chapter 1 to a buzzword parade and list of Java perks (prevents bugs, write once run anywhere, cures baldness, etc). Wow- C# review on Slashdot? (Score:3, Insightful) C# really is a nice language. It is more powerful than other C# also gives you the ability to write XML comments in your code that can be parsed by the compiler to generate documentation. There is also an open source project called "NDOC" (hosted on Source Forge) that lets you generate really cool and helpful docs. However, the majority of Slashdot readers probably don't care how C# is better than other Re:Wow- C# review on Slashdot? (Score:2) There's of course much, much more to it like the What I personally like most with C# is this: - Isn't a "layer" above another language, like C++. Clean. - The ease of use of Java with much of the power of C++. - Many annoying shortcomings in Java are fixed while preserving invaluable support for things like garbage collection. I'm not advertising VS.NET by this in any way. Always remember that *nix (and Windows!) users can go with the Mono project [go-mono.com] to get the C# language with platform independence, while still not supporting Microsoft if that's a concern. Re:Wow- C# review on Slashdot? (Score:2) I'm excited about the mono project. I hope it comes to fruition and can keep up. It would be nice to see what kind of development tool (if any) will be available on the linux platform. VI just doesn't do justice. Emacs might do the trick, but I like intellisense like VS.NET has (but I hate a lot of the nuances that come with it) I'd like to see some open source editors come out that could be used on different platforms. I wonder if anyone is working on that? I've used WebMatrix, not sure if that is open source, but it is free. There is also a free one called "Sharp Edit" but no auto complete, at least not the last time I checked. Re:Wow- C# review on Slashdot? (Score:2) Re:Wow- C# review on Slashdot? (Score:2) Thats not exactly new, that the same feature as Javadoc did for java since version 1.0 generating documentation (Score:2) Re:Wow- C# review on Slashdot? (Score:3, Interesting) No, C# doesn't allow you to write unsafe code, you have to use C++ for that. What's new about C++ in the You can write UNSAFE CODE [dotnetextreme.com] with C#. Yes, it is mixed in, but it is still unsafe code. See this article for reference. I never said it runs outside the CLR, just the GC. C# the only real choice (Score:2, Funny) Also with the upcoming war on Iraq it's best if we're all patriotic and support our country's companies with our hard-earned dollars. Why, if you use Java, you might as well hang an Iraqi flag in your yard and wear a Republican Guard uniform to work every day. That's how important this is. Don't you Java developers feel ashamed of yourselves? I would. The Canonical C# for Java Developers Article (Score:5, Informative) Mirrors: What was wrong with J# for Java users? (Score:3, Informative) Re:What was wrong with J# for Java users? (Score:2) But, yes, it would probably help a bit. I didn't have a problem making pure Java apps (Score:2) What was so hard about developing a platform independant app with J++? It seemed pretty clear to me what was Win32 and what was Java. Good starting point online (Score:3, Interesting) This is a great site. If anyone wants to learn C# coming from a C/C++ or Java background I send them here. Shows source in all three languages (where applicable). Good place to start. I must say I was a hard-core Java fan until I found C#. I must qualify that statement since I develop exclusively for Windows. If you write code that will only live in the Windows world, you owe it to yourself to check out C#/.NET. Re:Good starting point online (Score:4, Insightful) After a first glance I saw This is typical code you might write in Java or C++:. I just knew it. For C/C++ coders C# is what Windows is to a proper OS users. It may be easier if you're a numwit, but I'm quite sure that the design is rigid and quite quickly you'll wind face to face with some illogicality or utter impracticality. And there you are... not happy as a clam, but happy as a lion with a hedgehog rammed up in it's butt. If you're now thinking "well, C++ is flawed, too" the you've missed the point or you only think you know C/C++. There's a big difference in knowing and mastering and my guess is that that in particular will be the problem with C#, as with all other Mickeyware. Re:Good starting point online (Score:2) Re:Good starting point online (Score:2) Re:Good starting point online (Score:2, Informative). Actually, IIRC, C# supports some syntactic sugar called "accessors;" basically, label.font.bold = true maps to a call to label.getFont().setBold(true). They didn't make the member data publically acessible, they just lowered the keystrokes to call simple mutator methods. This is SO not insightful (Score:2) What the f*** is so insightful about bashing language on the basis of it being high-level and created by Microsoft? C, C++, Java and C# all looks like nice languages, and even if you are sceptical you should base languages on its merits, and not who created it. I'm really paranoid about Microsoft, I run a small norwegian Linux site, and I'm a Linux user, but this is just BS. Besides, reasonable C-coders might prefer to code in C, but won't dismiss C# or Java as some sort of "Mickey Mouse"-language just because it is high-level. Some times you need the power of C, sometimes you just want rapid development without the hassle. There are at least enough C-coders that think C# is great, to create Mono [go-mono.com]. Re:Good starting point online (Score:3, Interesting) Couldn't agree more, but the same won't hold for C/C++ which they referred to. I bet you thought those were direct property accesses, right? I wouldn't expect such a staunch defender of The One True Faith to actually look up the mechanisms of property declarations... Doh, it being methodized was obvious enough. It just kinda bugged the hell out of me seing foo.setSize (getSize () + 1); label.getFont().setBold (true); Labeled as "typical code" in C++. And the part which you were obviously referring to as it cannot be done in C++ (because one can't overload label.font.bold = true Well, I for one am quite doubtfull wether that is better than what C++ has now label.font().bold = true The article goes on and argues that the Well, I sure don't see the "extra" parentheses harmfull, moreover I'm worried about the complexities of the scoping rules for similarily named fields. Having read the cursive (italic) parts of the article, I have to say that I don't agree with most of it. And just as my comments here are biased, so is the article. Rants like these don't make good articles. That's why I post my crap here, which would've been a fair idea for that author aswell. Re:Good starting point online (Score:3, Informative) Re:Good starting point online (Score:2) It *should* be mistakable for a field. The user of a class should not need to know how an item is implemented, whether it's via a field or a method should be opaque. That way the implementor can change the implementation without breaking code. Re:Good starting point online (Score:2) If you write code that you think will only live in a windows world, you should always consider carefully using cross-platform or portable solutions. I've seen the windows-only assumption fail many times: the developers were stuck with the difficult and tedious task of gettin their built-for-ms code to be cross-platform. It's just one consideration. If vendor lock in doesn't bother you or your clients, or you will never need to reach other platforms or scale your solution, .MicroSoft might be right for you. Windows.Forms (Score:2) There are some articles about it too. [gotdotnet.com] Re:Windows.Forms (Score:2) Re:Windows.Forms (Score:2) This attitude wont help java anywhere. Even with hotspot, java is slow, especially the GUI stuff on Linux/Unix. Array handling sucks big time too. Tomcat jsp:s get wiped down with hacks like php. Setting up J2EE is a real pain in ass. Etc, Etc. Never done If java want's to survive, sun needs to make it easier and faster, and show studies PROVING it. The "Pet shop is not a benchmark" cry needs to replaced by "Hey, this version beats Ignorance, or cluelessnes? (Score:2) Where in any of the court documentation for any of the court proceedings that MS is invloved with does it say, "You have to divest yourself of your publishing brand?" Wow.. review sounds pretty good! (Score:3, Flamebait) Re:Wow.. review sounds pretty good! (Score:3, Insightful) Of course not (Score:2) Re:Wow.. review sounds pretty good! (Score:2) The Cappuchino PC pt. 3? Re:Wow.. review sounds pretty good! (Score:3, Funny) Funny, I saw the opposite (Score:3, Insightful) Pretty sad when the political orthodoxy is so overwhelming that every sentence has to start with the equivalent of "please don't hate me for saying it, but this wasn't as bad as I naturally assumed..." when discussing a book on programming. C# is what you get if you take several years of Java real-world experience and ask "if we could do it over again from scratch, with no backward compatibility requirements with existing Java, what would we do?" C# is what you get if, instead of taking Sun's attitude of "please, you're a programmer, not a language designer -- if what you're asking for were a good idea, we would have done it", you take MS's "mercenary" attitude of "what changes would you make to Java if you could?". Re:Wow.. conspiracy theory sounds pretty good! (Score:2) If you all really care SO MUCH, go to your local Barnes & Noble and RTFB. If you want to know if something if bullshit, there's really nothing like seeing for yourself. Why should it seem strange to mention C#? (Score:5, Insightful) There is absolutely nothing strange with not keeping your head buried in the sand. Just because some folks seem to have a knee-jerk reaction to all things Microsoft doesn't mean Slashdot should be expected to ignore relevant and widespread programming practices. Re: Why should it seem strange to mention C#? (Score:2) It's true I have only anecdotal evidence to back up my assertion that C# and .NET are gaining widespread adoption. The division of the company I work for is heavily involved in .NET development, and we are in an industry that is traditionally behind the curve in software practices. I think only common sense will tell you of the general interest in .NET. I attended the kick-off in Denver and the place was packed. I don't know why I'm responding to you, it is easy to close your eyes and say "show me the statistics or I believe nothing." Not to mention you're posting as an AC. Can't figure it out? Try it out (Score:2) It's free. You'll get a C# compiler, a bunch of class libraries, and a runtime, plus other goodies (e.g. other languages, but stick with C# if you're starting new.) Get a beginning C# book and go to work. It's no different from learning what Java was about in Java's early days. If your complaint is then, "but I'm not a Windows user", I can relate. One of the main reasons I became a Windows user was because I was having such a hard time learning the "cross-platform" Java language on my Mac back in the early days. If you're not a Windows user, you should be used to waiting by now, so wait for (or go help) Mono [go-mono.org]. Since I'm not a Windows user on the server side, I have to wait with you for some things, but I think that there will eventually be an excellent C# vs. Java comparison (Score:2) ExtremeTech: Java vs. C#, a Code-for-Code Comparison [extremetech.com] Microsoft press has some good titles. (Score:3, Informative) Re:Microsoft press has some good titles. (Score:2) WOW (Score:2) And no, there's nothing wrong with posting books about C# or Review of this review (Score:3, Insightful) I propose slashdot community lay down some guidelines about reviewing a technical book. I applaud the reviewer's efforts and for keeping an open mind towards the source curious? download the SDK. (Score:4, Informative) The sound you here is a dozen moderators clicking 'Troll'. mono for windows (Score:4, Informative) And as is said elsewhere, every language has its place. C# is pretty nice for building Windows native applications. If you don't want to do that, then use a different language. More on-topic, I'll definitely be checking this book out of the company library. Versa Vise (Score:2) You know that Example please (Score:2) Can you provide an example? -- Brian C# for Java programmer? (Score:2) All you have to do is add "MS" to the front of all the standard Java classes, methods, and member variables, and run your code through a C# compiler isn't it? Cash (C + Hash) == nice Idea, .Net == teh suxxo0rz (Score:2) Did anyone in the Industrie notice yet that near to zilch people are actually using Either I wanna go M$, then I go native. Or I want go independent, then I go Java. Is that so hard to get across? No, folks, Re:Cash (C + Hash) == nice Idea, .Net == teh suxxo (Score:2) The No, folks, Thanks for the prophecy nostradumbass. Can you back any of what you said up with facts and not FUD? Are you a developer or do you just play one on TV? Go write more than a hello world before you blab about how It's MUCH cleaner than Java (Score:2) We need an open source language similar to C#. Java's not open source, either. But I'd rather see a C#-type language than a Java-type language. I hate to say it, but C# is definitely the better language. It's main drawback for me is that it doesn't (currently anyway) run on anything but the shitty Windows platform. C# on Linux and I'd be in heaven. Re:C# (Score:2) Funny, I thought that C# was supposed to reduce complexity. Although pronouncing it "C-sharp" is a little counter intuitive; my first thoughts are always "C-pound". The maybe the first `Obfuscated C#' contests can center on it's name. Re:C# (Score:2) I believe it was The Register which approached this topic in some detail. For me, I've found that the best cross-cultural pronunciation is "C-hash". "C-octothorpe", though perhaps the most precise and technically correct, doesn't roll off the tongue nearly as fluidly. Re:C# (Score:2, Funny) Re:C# (Score:2, Funny) Maligned? (Score:2, Interesting) It really is just scared developers concerned that anything redmond can cough up is too mainstream and below them... Take a look at the ecma standards, download mono, and crawl out of your shell. Re:Maligned? (Score:3, Interesting) I'm pretty sure most of us developers are just a frightful bunch. Ada is an infamously derided language ("oh the government made it, so it's basically a beauracracy of a language") - yet it has more built in support for requirements validation and maintainability. If you look carefully at Ada, it is a pain to work with, but the result can be readily and meticulously examined by people other than the original developers. If you were a sailor and an exocet was screaming towards your vessel 500 yards out and skimming the waves and the only thing between walking the deck and treading the waves is your Phalanx close-in weapon system, you're probably hoping the software which controls the Phalanx was developed with Ada. Now would not be the time to file a support request because your C++ caused a general protection fault. So whether it's C# or anything else... I think way too many are afraid of having to re-stock their toolset from scratch. There's comfort in working with what you've always worked with. Insert cliche dinosaur analogy here. Re: C# (Score:4, Funny) > This is a maligned language. Is it byte maligned, or word maligned? Re:Good Stuff! (Score:2) Perhaps. Absolutely not. Re:Good Stuff! (Score:3, Interesting) Not quite, since Java is widely implemented. Sun doesn't expend time and money trying to make these implementations incompatible; instead, Sun wants them to be compatible and has test suites available for that purpose. Conversely, Microsoft has a history of prefering their implementation over any others and works hard to drive other implementations into obscurity. Only time will tell if history will repeat itself with respect to efforts such as Mono. No, but I do consider the amount of risk associated with a technology. Re:Good Stuff! (Score:2, Interesting) Small SUmmary from page, "The Mono Project is a community initiative to develop an open source, Linux-based version of the Microsoft.NET development platform. Incorporating key Open Source C# (.NET) for Win32 as well. (Score:2) [formativ.net] Only 4.2 megabytes, in all of its glory. Re:It's pronounced *SEE-SHARP* by the way. (Score:2) Re:It's pronounced *SEE-SHARP* by the way. (Score:2) "Ouch!! That hurt! Fuck, now I'm bleeding cash! Soko Wow... (Score:2) If you decide that you're going to stick only to assembly and nothing else, you're going to find little love in the computer industry. High-level languages are designed so that you don't have to go through a couple billion lines of extraneous code to do something. Sure, if you program in assembler, your code will be cleaner, faster and has a greater potential for looking brilliant to other hackers, but I dare you to try coding around in assembler making a couple of graphics engines and tell me how simple it is in x86 against C++. I mean, christ, I love assembler. You can do whatever you want with the memory, write self-modifying code, know at all times what is going on with the processor and everything else in the system, but fer crying out loud, if I want to make something as simple as a function call in Motorola HC11 that requires about 6 lines of code per call. A simple 4-line if block can result in a 20-line assembly instruction that would just be bloody easier to do if you just let a compiler automagically run it for you. While Assembly is pretty, and I encourage that if you want to be a programmer, learn it and use it well, but for crying out loud, don't stop there. Re:Assembly (Score:2) FYI, there are kids taking high school level Visual Basic that can't fathom the concept of a loop... Let alone assembly. I think "anal-retentive programmer" doesn't fit your average (probably not even above-average) high school student. Re:Assembly: Why It Will Replace C++/Java (Score:2) Couldn't have been Steve Gibson, UNLESS! Unless someone has DEVIOUSLY edited his post and STOLE all his capitalized words. The REAL Steve Gibson would NEVER have made such an unexciting post. HUZZAH! Re:Java developers should use J#, no? (Score:3, Interesting) However, syntax is often the easiest thing to relearn when switching language. Often much easier than to relearn an entire API. And since J# use the Re:Java developers should use J#, no? (Score:2) Re:Java developers should use J#, no? (Score:2) Re:C# not so bad folks (Score:2) Sad really Re:C# ~= Java (Score:2) I only knew about Bruce Eckel's wonderful online books [64.78.49.204] earlier (and lookie there - a C# book over there too!) But I agree with you, I only needed a few web tutorials to get started. The online IDE help in VS.NET did the rest. What I found hardest in learning C# wasn't the syntax that's almost identical to Java or C++, but learning where to find everything in the huge Framework and how the classes were all organized. Multiple inheritance (Score:2) Oh quit your bitching. Want to reuse the same few functions across a set of classes? That's what the clipboard is for. You know, copy and paste. Just paste that useful code into every class that needs it. Want to change, extend, or trim back that code that cut-pasted code that should have been a base class? That's what search-and-replace is for. You've got a lovely IDE, learn to use it. Me? Bitter? Seriously though, I've been thinking about creating a language called D. D is a half-step above C#. D will look just like C#, but it will add a new keyword: derivesfrom. Then you can write code like this: public class BaseClass // you know { // implementation and stuff goes here } public class Widget derivesfrom BaseClass, OtherBaseClass : IWhatever, ISomethingElse { } The D "compiler" will read such things and emit perfectly compilable C# code, sparing you the cut-paste madness known as "code reuse" in the C# world. The only question is whether D should be implemented as a perl script (because I have a sense of humor) or as a D application (because geeks (like me) are fond of self-reference). As a friendly gesture to those who oppose MI, the D compiler will spit out an error message if you attempt to derive from two classes that share a common base class. This one pathological example seems to have scared the bejeezus out of language designers everywhere. Other abuses of MI might be handled with stern warnings. I submitted the project [sourceforge.net] to the good people at SourceForge a few minutes ago. In the meantime, contact me directly [natew.com] if you're interested in bringing D to fruition. Re:compare web architectures (Score:2) But jsp pages are nasty for complex code, so are asp.net pages. And the execution of some of the ASP.net controls take up a lot of bandwidth; the calendar control is an example. ASP.NET's web service model is good; it is very easy to export methods from a class as SOAP actions against a URL. But to build and deploy a production quality, high availablity web service is always a management and config nightmare, and there java still has the edge over IIS+WinNT. Re:another new language? technology churn (Score:2) I agree with this. Programming matured quite a while ago, and most recent contributions have added only unneccessary complexity to what should be a tractable situation. The last five years have introduced more acronyms, buzzwords, and brand names into my vocabulary than my brain can handle. Yet, what am I using on a daily basis? 20-year-old technology: vi, sh, sccs, make, etc. Relatively few new software technologies have really pushed beyond where we were in 1982, and many of those technologies are simply eye candy-enabled versions of what was around 10, 20, and even 30 years ago. It seems we could be better off not reinventing the platform on which everything is built every five years. FORTRAN, C, C++, Java, C# all touted revolutionizing our lives. FORTRAN and C really did revolutionize things; they broke us free of assembly code. But what about the rest? Why is software quality about the same now as it always has been? It's because none of these newer platforms have changed the fundamental complexity of making good software. Writing software today still requires the same amount of "brains" as it did decades ago. Re:C# for non-java developers? (Score:2) I do reccomend the Petzold though. (I got that in the same shipment.) If you're not familiar with Windows Forms and want to do client programming for Windows, you'll almost need it. The Wrox Press book gives an intro on WinFoms (the O'Reilley appears to as well from a listing of topics on Amazon), but if you do any serious development you'll want a dedicated book. (It's expensive though; order it online for a lot less; it's $60 retail, but I paid $42 on Amazon. I believe other OL places have similar deals.)
http://developers.slashdot.org/story/02/09/03/1431251/c-for-java-developers?sdsrc=next
CC-MAIN-2015-14
refinedweb
6,753
73.37
REST::Neo4p – A Perl “OGM”This is a guest post by Mark A. Jensen, a DC area bioinformatics scientist. Thanks a lot Mark for writing the impressive Neo4j Perl library and taking the time to documenting it thoroughly. You might call REST::Neo4pan “Object-Graph Mapping”. It uses the Neo4j REST API at its foundation to interact with Neo4j, but what makes REST::Neo4p“Perly” is the object oriented approach. Creating node, relationship, or index objects is equivalent to looking them up in the graph database and, for nodes and relationships, creating them if they are not present. Updating the objects by setting properties or relationships results in the same actions in the database, and returns errors when these actions are proscribed by Neo4j. At the same time, object creation attempts to be as lazy as possible, so that only the portion of the database you are working with is represented in memory. The idea is that working with the database is accomplished by using Perl5 objects in a Perl person’s favorite way. Despite the modules’ “REST” namespace, the developer should almost never need to deal with the actual REST calls or the building of URLs herself. The design uses the amazingly complete and consistent self-describing information in the Neo4j REST API responses to keep URLs under the hood. The BackstoryI am a bioinformatics scientist contracted to a large US government research initiative. Our clients were interested in alternatives to RDBMS to represent the big data we manage. As a long-time object-oriented Perler with only a smattering of Java, I wanted to investigate Neo4j, but on my own terms. My CPAN and other searches came up with some experimental approaches to working with the Neo4j REST service, but there was little true object functionality and robustness in place. I was surprised to see so little Neo4j activity in the open-source Perl domain, in the face of many pleading requests in the Neo4j community for a decent Perl interface. So I took on the challenge, and I am definitely hoping for positive feedback and constructive criticism. The Basics Download and install REST::Neo4pis really a family of Perl modules/classes. Get it and install it like this: $ cpanThat’s it. The cpan utility comes with every Perl installation. If you haven’t used it before, you will be asked some setup questions, for most of which the defaults will be fine. cpan> install REST::Neo4p Tests: The installation process will run a complete suite of tests. To take advantage of these, enter the full API URL and port of your (running!) neo4j engine when prompted. (It defaults to.) If any tests fail, please report a bug right here. The cpan utility will also help you install the dependencies, other CPAN modules that make REST::Neo4pgo. There are only a few. A trick to get them all to install automatically is the following: $ cpan cpan> o conf prerequisites_policy follow cpan> install REST::Neo4p Connect and manipulateI’m going to assume you’re familiar with Perl 5 objects. If you’re not, check out camel‘s mouth. I’ll walk through a simple model from the bioinformatics domain, nucleotides in DNA (follow link for a nice introduction). Nucleotides are the letters which spell the words (genes) encoded in DNA. There are four that are most important, and are referred to as A, C, G, and T. These letters stand for their chemical names. DNA can change or mutate when one of these letters is changed to another. The letters are the nodes in our model. Mutations are changes in the DNA from one letter to another. These changes themselves are classified, and are called either transistions or transversions. The details don’t matter here, except that mutations from one letter to another are the relationships in our model. First, include the REST::Neo4pmodules, then connect to the database: #-*- perl -*- use REST::Neo4p; use strict; use warnings; eval { REST::Neo4p->connect(''); }; ref $@ ? $@->rethrow : die $@ if $@; Errors, including communication errors, are transmitted as exception objects from a hierarchy (see REST::Neo4p::Exceptionsfor a full description). The last line here just checks whether an exception was thrown at connect time and, if so, dies with a message. More sophisticated handling is possible and encouraged. Now to create nodes along with indexes to easily handle them. The new constructor does the creation and returns the objects for the Neo4p entity classes Index, Node, and Relationship. my @node_defs = ( { name => 'A', type => 'purine' }, { name => 'C', type => 'pyrimidine' }, { name => 'G', type => 'purine'}, { name => 'T', type => 'pyrimidine' } ); my $nt_types = REST::Neo4p::Index->new('node','nt_types'); my $nt_names = REST::Neo4p::Index->new('node','nt_names'); my @nts = my ($A,$C,$G,$T) = map { REST::Neo4p::Node->new($_) } @node_defs; $nt_names->add_entry($A, 'fullname' => 'adenine'); $nt_names->add_entry($C, 'fullname' => 'cytosine'); $nt_names->add_entry($G, 'fullname' => 'guanosine'); $nt_names->add_entry($T, 'fullname' => 'thymidine'); for ($A,$G) { $nt_types->add_entry($_, 'type' => 'purine'); } for ($C,$T) { $nt_types->add_entry($_, 'type' => 'pyrimidine'); } In general, you provide a hash reference that maps properties to values to the Node and Relationship constructors. To create an Index, the first argument is the index type (‘node’ or ‘relationship’), followed by the index name. Use the add_entry method to add an object to an index with a tag => value pair. On to relationships. We create a relationship index to corral the mutation types, and express the mutation types as relationship objects. Using the relate_to method from node objects, we create relationships between pairs of nodes with a pretty natural syntax: my $nt_mutation_types = REST::Neo4p::Index->new('relationship','nt_mutation_types'); my @all_pairs; my @a = @nts; while (@a) { my $s = shift @a; push @all_pairs, [$s, $_] for @a; } for my $pair ( @all_pairs ) { if ( $pair->[0]->get_property('type') eq $pair->[1]->get_property('type') ) { $nt_mutation_types->add_entry( $pair->[0]->relate_to($pair->[1],'transition'), 'mut_type' => 'transition' ); $nt_mutation_types->add_entry( $pair->[1]->relate_to($pair->[0],'transition'), 'mut_type' => 'transition' ); } else { $nt_mutation_types->add_entry( $pair->[0]->relate_to($pair->[1],'transversion'), 'mut_type' => 'transversion' ); $nt_mutation_types->add_entry( $pair->[1]->relate_to($pair->[0],'transversion'), 'mut_type' => 'transversion' ); } } The relate_to method returns the relationship object that is created. Here we use that side effect directly in the add_entrymethod of the index. If you prefer, you can use a relationship constructor: $transition = REST::Neo4p::Relationship->new($A, $G, 'transition');Relationship properties can be added in the constructor, or after the fact: $transition->set_property('involved_types' => 'purines'); Perl garbage collection removes objects from memory, but does not delete from the database. You must do this explicitly, using the the remove method on any entity: for my $reln ($A->get_relationships) { $reln->remove; } $A->remove; $nt_types->remove; # etc. Retrieve and queryThe REST::Neo4pmodule itself contains a few methods for retrieving database items directly. The most useful is probably get_index_by_name. Index objects have find_entries for retrieving the items in the index. use REST::Neo4p; use strict; use warnings; REST::Neo4p->connect(''); my $idx = REST::Neo4p->get_index_by_name('nt_names','node'); my ($node) = $idx->find_entries(fullname => 'adenine'); my @nodes = $idx->find_entries('fullname:*'); Note that find_entries always returns an array, and it supports either an exact search or a lucene search. REST::Neo4palso supports the CYPHER query REST API. Entities are returned as REST::Neo4pobjects. Query results are always sent to disk, and results are streamed via an iterator that is meant to imitate the commonly used Perl database interface, DBI. Here we print a table of nucleotide pairs that are involved in transversions: my $query = REST::Neo4p::Query->new( 'START r=relationship:nt_mutation_types(mut_type = "transversion") MATCH a-[r]->b RETURN a,b' ); $query->execute; while (my $result = $query->fetch) { print $result->[0]->get_property('name'),'->', $result->[1]->get_property('name'),"n"; } The query is created with the CYPHER code, then executed. The fetch iterator retrieves the returned rows (as array references) one at a time until the result is exhausted. Again, the result is not held in memory, so queries returning many rows should not present a big problem. Production-quality FeaturesMy goal for REST::Neo4pis to go beyond the Perl experiments with Neo4j that are out there to create modules that are robust enough for production use (yes, people DO use Perl in production!). This meant a couple of things: - Be robust and feature-rich enough that people will want to try it. - Be responsive enough to bugs that people will see it maintained. - Incorporate unit and integration tests into the user installation. - Have complete documentation with tested examples. - Create bindings to as many of the Neo4j REST API functions as is possible for a guy with a real job. - Be concerned with performance by being sensitive to memory use, and taking advantage of streaming and batch capabilities. - Capture both Perl and Neo4j errors in a catchable way. There isn’t space here to discuss these points in detail, but here are some highlights and links: - REST::Neo4p::Agent is the class where the REST calls get done and the endpoints are captured. It subclasses the widely-used LWP::UserAgent and can be used completely independently of the object handling modules, if you want to roll your own Neo4j REST interface. - The batch API can be used very simply by including the REST::Neo4p::Batch mixin. Visit the link for detailed examples. - When paths are returned by CYPHER queries, they are rolled up into their own simple container object REST::Neo4p::Path that collects the nodes and relationships with some convenience methods. - You can choose to have REST::Neo4pcreate property accessors automatically, allowing the following: $node->set_property( name => 'Fred' ); print "Hi, I'm ".$node->name; - REST::Neo4p::Index allows index configuration (e.g., fulltext lucene) as provided by the Neo4p REST API. I hope Perlers will give REST::Neo4pa try and find it useful. Again, I appeciate the time you take to report bugs.
https://neo4j.com/blog/restneo4p-a-perl-ogm/
CC-MAIN-2020-05
refinedweb
1,616
53.41
in reply to Word and Win32::OLE package readWord; use strict; use Win32::OLE qw(in with); require Exporter; use vars qw(@ISA @EXPORT); #use LTG::DocBuddy::Config qw($DEBUG); @ISA = qw(Exporter); @EXPORT = qw(readActiveDoc); sub readActiveDoc # this method returns the name of the active document and a hash containing every single # word found in the document. Hence it is ready for use { if (my $word = Win32::OLE->GetActiveObject('Word.Application'))# connect to word document { # next line for debug only # print "\nSuccessfully connected to existing word"; my $docName = $word->ActiveDocument->Name; # retrieve name my $wordRange = $word->ActiveDocument->Content; return ($docName,$wordRange); } else { return undef; } } 1. Keep it simple 2. Just remember to pull out 3 in the morning 3. A good puzzle will wake me up Many. I like to torture myself 0. Socks just get in the way Results (289 votes). Check out past polls.
http://www.perlmonks.org/index.pl?node_id=266217
CC-MAIN-2016-44
refinedweb
147
56.96
Application: Summing the Even Integers from 2 to 20 The program of Fig. 5.5 uses a for statement to sum the even integers from 2 to 20. Each iteration of the loop (lines 11–12) adds control variable number’s value to variable total. 1 // Fig. 5.5: fig05_05.cpp 2 // Summing integers with the for statement. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 unsigned int total = 0; // initialize total 9 10 // total even integers from 2 through 2011 for ( unsigned int number = 2; number <= 20; number += 2 )12 total += number; 13 14 cout << "Sum is " << total << endl; // display results15 } // end main Sum is 110 Fig. ... Get C++11 for Programmers, Second Edition now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/c11-for-programmers/9780133439885/ch05lev2sec9.html
CC-MAIN-2020-05
refinedweb
142
60.55
The Sequential Search When data items are stored in a collection such as a list, we say that they have a linear or sequential relationship. Each data item is stored in a position relative to the others. In Python lists, these relative positions are the index values of the individual items. Since these index values are ordered, it is possible for us to visit them in sequence. This process gives rise to our first searching technique, the sequential search. The diagram below shows how this search works. Starting at the first item in the list, we simply move from item to item, following the underlying sequential ordering until we either find what we are looking for or run out of items. If we run out of items, we have discovered that the item we were searching for was not present. The Python implementation for this algorithm is shown below. The function needs the list and the item we are looking for and returns a boolean value as to whether it is present. Remember in practice we would use the Python in operator for this purpose, so you can think of the below algorithm as what we would do if in were not provided for us. def sequential_search(alist, item): position = 0 while position < len(alist): if alist[position] == item: return True position = position + 1 return False testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] sequential_search(testlist, 3) # => False sequential_search(testlist, 13) # => True Analysis of Sequential Search To analyze searching algorithms, we need to decide on a basic unit of computation. Recall that this is typically the common step that must be repeated in order to solve the problem. For searching, it makes sense to count the number of comparisons performed. Each comparison may or may not discover the item we are looking for. In addition, we make another assumption here. The list of items is not ordered in any way. The items have been placed randomly into the list. In other words, the probability that the item we are looking for is in any particular position is exactly the same for each position of the list. If the item is not in the list, the only way to know it is to compare it against every item present. If there are items, then the sequential search requires comparisons to discover that the item is not there. In the case where the item is in the list, the analysis is not so straightforward. There are actually three different scenarios that can occur. In the best case we will find the item in the first place we look, at the beginning of the list. We will need only one comparison. In the worst case, we will not discover the item until the very last comparison, the nth comparison. What about the average case? On average, we will find the item about halfway into the list; that is, we will compare against items. Recall, however, that as n gets large, the coefficients, no matter what they are, become insignificant in our approximation, so the complexity of the sequential search, is : We assumed earlier that the items in our collection had been randomly placed so that there is no relative order between the items. What would happen to the sequential search if the items were ordered in some way? Would we be able to gain any efficiency in our search technique? Assume that the list of items was constructed so that the items were in ascending order, from low to high. If the item we are looking for is present in the list, the chance of it being in any one of the n positions is still the same as before. We will still have the same number of comparisons to find the item. However, if the item is not present there is a slight advantage. The diagram below shows this process as the algorithm looks for the item 50. Notice that items are still compared in sequence until 54. At this point, however, we know something extra. Not only is 54 not the item we are looking for, but no other elements beyond 54 can work either since the list is sorted. In this case, the algorithm does not have to continue looking through all of the items to report that the item was not found. It can stop immediately. The code below shows this variation of the sequential search function. def ordered_sequential_search(alist, item): position = 0 while position < len(alist): if alist[position] == item: return True if alist[position] > item: return False position = position + 1 return False testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] ordered_sequential_search(testlist, 3) # => False ordered_sequential_search(testlist, 13) # => True The table below summarizes these results. Note that in the best case we might discover that the item is not in the list by looking at only one item. On average, we will know after looking through only items. However, this technique is still . In summary, a sequential search is improved by ordering the list only in the case where we do not find the item.
https://bradfieldcs.com/algos/searching/the-sequential-search/
CC-MAIN-2018-26
refinedweb
851
70.23
Hi I am learning C++ for the first time; I use Dev C++ as i am 14 with no cash; My programe has two if statments in and i use the cin.get(); thing to see what i have done. but after the second if statment, the dos window with my programe in it, is gone. What do i do; can someone help me plz Code:#include <iostream> using namespace std; int main() { char N; char Y; int uname; int pword; cout << "Welcome to the hackers gateway\n" <<endl; cout << "Do you have an account? Y or N (You need to say 'N' if you say"; <<endl; cin >> N; if (N == true); { cout << "Please type in your username\n"; cin >> uname; cout << "And now your Password"; cin >> pword << endl; cout << "You now have grated access to the hackers gateway\n"; cout << "Well done!"; cin.get(); } cout << "To gain access to the hackers gateway"; cout << "Please enter your username\n"; cin >> uname; cout << "Please enter your Password"; cin >> pword; cout << "Checking username and password...."; if (uname AND pword == true); { cout << "Hello and Wellcome to the hackers gateway"; <<endl; } cin.get(); return 0; }
https://cboard.cprogramming.com/cplusplus-programming/81359-newbie-needs-help-plz.html
CC-MAIN-2017-30
refinedweb
191
82.07
So I'm working on an automation script for a workflow in my company. I have written the whole thing in Python, as most of our databases API's were in Python. However, one of our databases uses Perl for their API. It would obviously take me weeks if not months to port their excellent API into python. So, and I assume this is probably a simple problem, how can I take an array from the main function of my Python script, feed it into my Perl script as input, then return the modified version back into my main Python script? Thank you very much for any help! I've created an example using three scripts. The first one is a Python script that creates a list, then writes it to a JSON file. We then have a Perl script that reads in the JSON, modifies it (adds three more elements to the array), then writes it back to the JSON data file. The last script, in Python, shows how to read in JSON and use the data. Python script, create a list, write it out to a json file import json data = [1, 2, 3] with open('data.json', 'w') as jsonfile: json.dump(data, jsonfile) The data file now looks like: [1, 2, 3] Perl script, reads the JSON file, mucks with the data, writes it back out: use warnings; use strict; use JSON; my $', $file or die $!; print $fh $json; close $fh or die $!; Data file now looks like: [1, 2, 3, 4, 5, 6] Python script, reads the updated JSON file, and transforms it back into a list: import json file = 'data.json'; data = json.loads(open(file).read()) print(data) Prints: [1, 2, 3, 4, 5, 6]
https://codedump.io/share/2e6t0mgf9Osb/1/feeding-a-python-array-into-a-perl-script
CC-MAIN-2018-05
refinedweb
292
80.21
I wrote a metaclass that I'm using for logging purposes in my python project. It makes every class automatically log all activity. The only issue is that I don't want to go into every file and have to add in: __metaclass__ = myMeta Is there a way to set the metaclass in the top level folder so that all the files underneath use that metaclass? No, you can only specify the metaclass per class or per module. You cannot set it for the whole package. In Python 3.1 and onwards, you can intercept the builtins.__build_class__ hook and insert a metaclass programatically, see Overriding the default type() metaclass before Python runs. Here's a simple technique. Just subclass the class itself with __metaclass__ attribute in the subclass. This process can be automated. util.py class A(object): def __init__(self, first, second): self.first = first self.second = second def __str__(self): return '{} {}'.format(self.first, self.second) main.py from datetime import datetime from util import A def meta(*args): cls = type(*args) setattr(cls, 'created', datetime.now().ctime()) return cls try: print(A.created) except AttributeError as e: print(e) class A(A): __metaclass__ = meta print(A.created, str(A('Michael', 'Jackson'))) Test; $ python main.py type object 'A' has no attribute 'created' ('Wed Mar 9 22:58:16 2016', 'Michael Jackson') Similar Questions
http://ebanshi.cc/questions/1072003/python-setting-the-metaclass-for-all-files-in-a-folder
CC-MAIN-2017-22
refinedweb
227
61.02
Viewing HTML mail messages from Mutt (or other command-line mailers) Command-line mailers like mutt have one disadvantage: viewing HTML mail with embedded images. Without images, HTML mail is no problem -- run it through lynx, links or w3m. But if you want to see images in place, how do you do it? Mutt can send a message to a browser like firefox ... but only the textual part of the message. The images don't show up. That's because mail messages include images, not as separate files, but as attachments within the same file, encoded it a format known as MIME (Multipurpose Internet Mail Extensions). An image link in the HTML, instead of looking like <img src="picture.jpg">., will instead look something like <img src="cid:0635428E-AE25-4FA0-93AC-6B8379300161">. (Apple's Mail.app) or <img src="cid:1.3631871432@web82503.mail.mud.yahoo.com">. (Yahoo's webmail). CID stands for Content ID, and refers to the ID of the image as it is encoded in MIME inside the image. GUI mail programs, of course, know how to decode this and show the image. Mutt doesn't. A web search finds a handful of shell scripts that use the munpack program (part of the mpack package on Debian systems) to split off the files; then they use various combinations of sed and awk to try to view those files. Except that none of the scripts I found actually work for messages sent from modern mailers -- they don't decode the CID links properly. I wasted several hours fiddling with various shell scripts, trying to adjust sed and awk commands to figure out the problem, when I had the usual epiphany that always eventually arises from shell script fiddling: "Wouldn't this be a lot easier in Python?" Python's email package Python has a package called email that knows how to list and unpack MIME attachments. Starting from the example near the bottom of that page, it was easy to split off the various attachments and save them in a temp directory. The key is import email fp = open(msgfile) msg = email.message_from_file(fp) fp.close() for part in msg.walk(): That left the problem of how to match CIDs with filenames, and rewrite the links in the HTML message accordingly. The documentation on the email package is a bit unclear, unfortunately. For instance, they don't give any hints what object you'll get when iterating over a message with walk, and if you try it, they're just type 'instance'. So what operations can you expect are legal on them? If you run help(part) in the Python console on one of the parts you get from walk, it's generally class Message, so you can use the Message API, with functions like get_content_type(), get_filename(). and get_payload(). More useful, it has dictionary keys() for the attributes it knows about each attachment. part.keys() gets you a list like ['Content-Type', 'Content-Transfer-Encoding', 'Content-ID', 'Content-Disposition' ] So by making a list relating part.get_filename() (with a made-up filename if it doesn't have one already) to part['Content-ID'], I'd have enough information to rewrite those links. Case-insensitive dictionary matching But wait! Not so simple. That list is from a Yahoo mail message, but if you try keys() on a part sent by Apple mail, instead if will be 'Content-Id'. Note the lower-case d, Id, instead of the ID that Yahoo used. Unfortunately, Python doesn't have a way of looking up items in a dictionary with the key being case-sensitive. So I used a loop: for k in part.keys(): if k.lower() == 'content-id': print "Content ID is", part[k] Most mailers seem to put angle brackets around the content id, so that would print things like "Content ID is <14.3631871432@web82503.mail.mud.yahoo.com>". Those angle brackets have to be removed, since the CID links in the HTML file don't have them. for k in part.keys(): if k.lower() == 'content-id': if part[k].startswith('<') and part[k].endswith('>'): part[k] = part[k][1:-1] But that didn't work -- the angle brackets were still there, even though if I printed part[k][1:-1] it printed without angle brackets. What was up? Unmutable parts inside email.Message It turned out that the parts inside an email Message (and maybe the Message itself) are unmutable -- you can't change them. Python doesn't throw an exception; it just doesn't change anything. So I had to make a local copy: for k in part.keys(): if k.lower() == 'content-id': content_id = part[k] if content_id.startswith('<') and content_id.endswith('>'): content_id = content_id[1:-1]and then save content_id, not part[k], in my list of filenames and CIDs. Then the rest is easy. Assuming I've built up a list called subfiles containing dictionaries with 'filename' and 'Content-Id', I can do the substitution in the HTML source: htmlsrc = html_part.get_payload(decode=True) for sf in subfiles: htmlsrc = re.sub('cid: ?' + sf['Content-Id'], 'file://' + sf['filename'], htmlsrc, flags=re.IGNORECASE) Then all I have to do is hook it up to a key in my .muttrc: # macro index <F10> "<copy-message>/tmp/mutttmpbox\n<enter><shell-escape>~/bin/viewhtmlmail.py\n" "View HTML in browser" # macro pager <F10> "<copy-message>/tmp/mutttmpbox\n<enter><shell-escape>~/bin/viewhtmlmail.py\n" "View HTML in browser" Works nicely! Here's the complete script: viewhtmlmail. [ 11:49 Oct 07, 2013 More tech/email | permalink to this entry | comments ]
https://shallowsky.com/blog/tech/email/mutt-viewing-html-mail.html
CC-MAIN-2020-34
refinedweb
934
66.33
On this page: [Kinds of Classes] [Design Issues] [Documentation Issues] [Implementation Issues] Other pages: [ Tracking Discussion] Enter your email address if you'd like to be notified when this page changes: #include "BaBar/BaBar.hh" The floating point representations are harder to quantify, but the net effect is that only "double" should be used in classes that are likely to be reused or written out. Optimization to "float", where needed and acceptable, can be done later. "inline" makes accessor functions a very good idea. In particular, only accessing member data via accessor functions, even within the class member functions, is required for all data and computational classes to ease migration and maintenance. Performance improvements may not be used as a reason to avoid this; all our compilers will inline accessors at a high enough optimization level, and most accessors are not a performance problem in any case. On the other hand, long, complex in-line member functions should be avoided. They reduce clarity, make it take longer to compile and harder to debug, and the performance gain from making them inline is small for large routines. It is bad design to make a function inline if that requires additional header files to be referenced by #include. In particular, one or more compilers have restrictions that make it unacceptable to inline: enum { nlay=15 }; A& inside (); void outside(A& a); outside(inside()); for (int i=0; ... ) { ... } ... for (int i=0; ... ) { ... } int i; for (i=0; ... ) { ... } ... for (i=0; ... ) { ... } while (Foo* p = bar() ) { ... } Foo* p; while (p=bar() ) { ... } class Foo { static Bar& refBar(); } Foo::refBar () { static Bar b; return b; } assert(iPtr); assert(iPtr != 0); To temporarily get around this lack, use const inline functions for every data member which would have been declared mutable, that 'casts off the const' for that variable. Const functions which need to alter the cache variables then access through this inline. This approach is somewhat safer than simply casting off the const of the entire object (*this) at the begining of these functions. An example is as follows: class MyClass{ void doSomethingNice() const; private: double _cachevalue; // should be declared mutable double& cacheValue() const { return (double&) _cachevalue;} RWTPtrSList<double> _doublelist; // should be declared mutable RWTPtrSList<double>& doubleList() const { return (RWTPtrSList<double>&) _doublelist; } }; MyClass::doSomethingNice() const { // loop over the list RWTPtrSListIterator<double> iter(doubleList()); ... // update the cache cacheValue() = newvalue; } #include "packagename/filename.hh" If you omit the packagename part, there will be trouble with template instantiations. #include "assert.h" To avoid accidentally dereferencing a zero pointer, all pointer values that are returned from functions should be checked for zero values. If the program cannot cope with an non-existant value, an assert() can be used. Otherwise, use an explicit comparison to zero in an if statement.
http://www.slac.stanford.edu/BFROOT/www/Computing/Offline/Reconstruction/CompRecCheck.html
crawl-002
refinedweb
458
53.21
I have written this program in cpp to perform basic calculations on two variables using functions and switch.The program does compile with zero errors,but the answer it gives is false.Please tell me if its a glitch with the code or the program itself is untrue. Code:#include<iostream> using namespace std; int menu(int x, int y,char choice) { switch(choice){ case'A': cout<<"The sum of "<<x<<" and "<<y<<" is "<<x + y; break; case'S': cout<<"The difference between "<<x<<" and "<<y<<" is "<<x - y; break; case'M': cout<<"The product of "<<x<<" and "<<y<<" is "<< x * y; break; case'D': cout<<"The ratio of "<<x<<" and "<<y<<" is "<<x / y; break; default: cout<<"Invalid Input"; } } int main() { int a,b; char choose; cout<<"Enter the first number:"; cin>>a; cout<<"Enter the second number:"; cin>>b; cout<<"Enter your choice:"; cin>>choose; cin.ignore(); cout<<menu(a,b,choose); cin.get(); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/154902-please-help-i%27m-new-programming.html
CC-MAIN-2015-35
refinedweb
158
66.78
In Lesson 3, we saw that a piece of information used in an application. In Lesson. The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file. One of the valuable operations that the File class can perform is to check the existence of the file you want to use. For example, if you are creating a new file, you may want to make sure it doesn't exist already because if you try to create a file that exists already, the compiler may first delete the old file before creating the new one. This could lead to unpredictable result,: static bool Exists(String ^path); would produce a false result. Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows: public: static FileStream ^ Create(String ^ path); public: static FileStream ^ Create(String ^ path, int buffersize);: static FileStream ^ Open(String ^ path, FileMode mode); public: static FileStream ^ Open(String ^ path, FileMode mode, FileAccess access); public: static FileStream Open(String ^ path, FileMode mode, FileAccess access, FileShare share);: Besides the access to the file, another option you will most likely specify to the operating system is referred to as the mode of a file. It is specified through the FileMode enumerator. The members of the FileMode Enumerator are: File streaming consists of performing one of the routine operations on a file, such as creating it (the second) of the FileStream class has the following syntax: public: FileStream(String ^ path, FileMode mode); This constructor takes as its first argument the name or the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example: using namespace System; using namespace System::IO; int main() { String ^ NameOfFile = L"Persons.spr"; FileStream ^ fstPersons = gcnew FileStream(NameOfFile, FileMode::Create); return 0; } A streaming operation is typically used to create a stream. Once the stream is ready, you can write data to it. The writing operation is perform through various classes. One of these classes is BinaryWriter. The BinaryWriter class can be used to write values of primitive data types (char, int, float, double, etc). To use a BinaryWriter value, you can first declare its variable. To do this, you would use one of the class' three constructors. One of its constructors (the second) has the following syntax: public: BinaryWriter(Stream ^ output); This constructor takes as argument a Stream value, which could be a FileStream variable. Here is an example:); return 0; } Most classes that are used to add values to a stream are equipped with a method called Write. This is also the case for the BinaryWriter class. This method takes as argument the value that must be written to the stream. The method is overloaded so that there is a version for each primitive data type. Here is an example that adds strings to a newly created file:"); return 0; }(); return 0; } As opposed to writing to a stream, you may want to read existing data from it. Before doing this, you can first specify your intent to the streaming class using the FileMode enumerator. This can be done using the FileStream class as follows:); return 0; } Once the stream is ready, you can get prepared to read data from it. To support this, you can use the BinaryReader class. This class provides two constructors. One of the constructors (the first) has the following syntax: public: BinaryReader(Stream ^ input); This constructor takes as argument a Stream value, which could be a FileStream object. After declaring a FileStream variable using this constructor, you can read data from it. To do this, you can call an appropriate method. This class provides an appropriate method for each primitive data type. After using the stream, you should close it to reclaim the resources it was using. This is done by calling the Close() method. Here is an example of using the mentioned methods:); BinaryReader ^ rdrPersons = gcnew BinaryReader(fstPersons); String ^ strLine = nullptr; strLine = rdrPersons->ReadString(); Console::WriteLine(strLine); strLine = rdrPersons->ReadString(); Console::WriteLine(strLine); strLine = rdrPersons->ReadString(); Console::WriteLine(strLine); strLine = rdrPersons->ReadString(); Console::WriteLine(strLine); rdrPersons->Close(); fstPersons->Close(); Console::WriteLine(); return 0; } This would produce: James Bloch Catherina Wallace Bruce Lamont Douglas Truth Press any key to continue . . .
http://www.functionx.com/cppcli/Lesson28.htm
CC-MAIN-2015-22
refinedweb
757
60.04
Randall Davis: IBM Has No SCO Code 405 Mick Ohrberg writes ?" Wait... (Score:5, Funny) Re:Wait... (Score:5, Funny) We showed over a million lines of code and where it has existed. [Linux creator] Linus Torvalds has told me that the Linux kernel has around 5 million lines of code. This derivative code accounts for 20 percent of the Linux code base." Q&A: SCO Group CEO Darl McBride By Michael Singer WTF! This guy can find a single line!! he must be blind! The CEO of SCO says that 1/5 of linux is a copy. Darl Mcbride would not lie!!! Remeber SCO owns c++ too! "And C++ programming languages, we own those" -Darl McBride Caldera CEO waves UnitedLinux banner By ZDNet Staff August 15, 2002 Re:Wait... (Score:3, Informative) "And C++ programming languages, we own those" -Darl McBride And nobody was more surprised to hear it than Bjarne Stroustrup [att.com] himself! Re:What did Didio see? (Score:5, Informative) Davis saw no -infringing- code. That's not the same thing as seeing no common code. Copying a ten-line function almost verbatim is likely a copyright violation. Ending up with a handful of lines that look a lot alike, by contrast, is often just an unavoidable side-effect of writing two pieces of code that do the same thing. Small blocks of code (under 3 lines) are generally not protected by copyright (unless we're talking obfuscated C lines). Even larger blocks of code may not be protected, depending on content. For example, in many cases (drivers come to mind), there may only be exactly one way to do something (e.g. you must set this register to 1, wait 5 ms, set it to zero, wait 5 ms, then set a second register to 1), in which case those specific bits are unlikely to be copyrightable at all, even if they represent a fairly substantial number of lines of code. Also, in order for the code to be infringing, it must have been taken from AT&T UNIX or its descendants, and must not have been put there by someone who owned copyright on said code. That means that A. the code must not have been placed there by anyone working for SCO or Novell, and B. the code must not have come from a third, shared source such as BSD. A very large chunk of SCO's UNIX code fails the "B." test, and SCO was an active contributor to Linux, so many cases where code appears the same could easily fail the "A." test as well. Re:What did Didio see? (Score:3, Interesting) SO why is she publishing that she was copied code? If she does not have the qualifications to make such a decision then she certainly then she certainly should not be advising investors based on such analysis. "Davis saw no -infringing- code. That's not the same thing as seeing no common code. Copying a ten-line function almost verbatim is likely a copyright violation. Ending up wi Figures... (Score:3, Funny) Counter example would have helped. (Score:5, Interesting) It surely wouldn't have been hard to take some, say, early and "in the clear" code that has been reused and modified over time to show both that it can be identified and to show how code that has evolved can still leave the fingerprint of the original code. Without that counter example the failure to find matches would seem underwhelming. (The closest the testimony came to this was showing a positive result that was generated and showing how it was a commonly repeated pattern in all software written in C, not something specific to these two programs). Perhaps elsewhere in IBMs testimony there was reference to this same procedure being successfully? Counterexample DIY (Score:5, Insightful) 2. Get Linux 2.4.0 3. left out as an exercise for the reader 4. Show positive result 5. Don't profit, but have fun. Re:Counter example would have helped. (Score:5, Insightful) Everyone is getting so far off base on this. SCO is manging to convince people that this is somehow difficult to prove.. that they need more research and more time to PROVE that IBM stole code and put it in linux. Their only claim as to why they think Linux has SCO code is "because there is no way linux could have become as good as it did without stealing from us".. ie: denial They have yet to show ONE section of code that was lifted. They haven't even shown how one was *similar* enough to have potentially been stolen and heavily modified.. they have shown *NOTHING* IT's called an expert witness... and their word DOES mean something to the court.. they stake their reputation on it. Re:Counter example would have helped. (Score:5, Insightful) I've been thinking this was strange too. After all, if code was copied into Linux it is essentially a public document now - out there for everyone to see. All SCO would have to do is download it and print it out side-by-side with a copy of their matching code. Case closed. SCO wins. The fact that they haven't done this extremely simple thing seems to strongly point to SCO being a bunch of total bullshitters. Even if some malicious programmer intentionally stole code and modified it slightly (changed variable names, comments, re-arranged the order of functions in header files, etc.) it should be pretty trivial to show a judge what happened and move on to the 'get sacks of cash from IBM' phase of the trial. Funny, you would think that a company that is suffering continuous, ongoing harm to the tune of US$699 per user would be pretty quick to do such a thing... LAW (Score:3, Insightful) It only takes a . out of line to sway the legal result, not necessary the correct and right result. It not over until the fat penguin sings, then we can all rejoice. Re:Counter example would have helped. (Score:3, Informative) That's the SCO argument, isn't it, that derivative works are theirs by copyright. Trouble is that the law is different. Copyright covers the representation not the idea. And for software having malloc() in two pieces of code doesn't rise to copyright Re:Counter example would have helped. (Score:5, Insightful) It just hit me: He doesn't have to. It's SCO's responsibility to show that there is infringing code in Linux. It's not IBM's responsibility to show that there is none. All that Davis has to prove is that the search is feasible in a reasonable ammount of time (as opposed to SCO's claim of 25,000 man-years). He's done this admirably. Not being able to find anything is simply icing on the cake. One beautiful thing about this is that (AFAICT) all (or almost all) of the software he used seems to be Open source (although he has references some similar commercial software), so SCO has absolutely no excuse to not repeat his experiment and come up with different results (presuming that they've actually got a case), given that it takes about 1 hour to run the comparison on off-the-shelf hardware. The other beautiful thing about this is -- remember Darl's remarks about an MIT team deep-diving the code?...... (boot to the head!) "I've shown you mine, now you show me yours!" In other news... (Score:4, Funny) More at 11. Re:In other news... (Score:4, Funny) Re:In other news... (Score:3, Funny) rocks are wet and water is hard... Re:In other news... (Score:3, Funny) Also, magma and ice not being capable of existing in the same environmental conditions, may not meet the requirements of proper experimental research, therefore all experiments must be carried out at 0 degrees kelvin to avoid corruption of data, atmospheric pressure may be designated by the experimenter. Re:In other news... (Score:4, Funny) *bows* Wait... I don't have to commit nerd ritual suicide now, do I? *prepares to FLEE* Really??!! (Score:5, Funny) Re:Really??!! (Score:2) Re:Really??!! (Score:3, Funny) * Runs off crying. * Re:Really??!! (Score:4, Funny) Kind OF Honest? well you're getting closer Re:Really??!! (Score:3, Informative) To be fair, noone says they aren't, except an expert who was payed a lot of money (550/hr) by IBM to say so. To you and I that would be a lot of money, but TSG is willing to pay BS&F many multiples of that (their law firm charges over $600/hr per lawyer, more for courtroom time. Mr. Silver was paid for 3 hours in this last hearing AND HE SLEPT THROUGH PART OF IT) for their expertice, why should IBM be less willing to spend money for expertice o Friendly logic lesson. (Score:3, Informative) Your logic is flawed. If not true, it's unclear whether it's interesting. Your conclusion would be true if your premise were "interesting if and only if true." At $550 per hour... (Score:5, Funny) 20. These comparisons required on the order of 10 hours of computation time on a dual 3 GHz Xeon processor system with 2 GB of RAM. This is a high-end workstation routinely and easily available off the shelf from commercial vendors such as Dell. At $550 per hour, I would've used something like a 386 processor with 8MB of RAM. Re:At $550 per hour... (Score:5, Funny) At $550 per hour, I would've used something like a 386 processor with 8MB of RAM. Hell, I would have built a wetware turing machine using a dozen grad students armed with abacii. In treacle. With Natalie Portman implementing the I/O subsystem. Re:At $550 per hour... (Score:2) Re:At $550 per hour... (Score:5, Funny) Inevitably,... Imagine a Beowulf cluster of grad students armed with abacii,.... Re:At $550 per hour... (Score:4, Insightful) I guess that's one reason they didn't hire you. Re:At $550 per hour... (Score:5, Funny) Re:At $550 per hour... (Score:4, Informative) I expect it took more than 10 hours for him to write that document and painstakingly verify its accuracy and wording to avoid perjury. He'll likely spend significant amounts of time testifying in person on the subject as well. That rate is high but within reason for top-end expert witnesses (which is exactly what he is.) It's not uncommon for renowned professors to make a substantial second income by acting as an expert witness (very common in the chemistry and biology fields, at least.) Finally, IBM would not even blink if they were handed a bill for several hundred hours at $550 each on this issue. They may even get some of the money back, depending on the details of the final settlement and the subsequent SCO bankruptcy. What about all of these? (Score:5, Funny) */ while(1) { } return(0); return(1); i elseif (...) else And don't forget the white space! That is a clear copy! Re:What about all of these? (Score:5, Funny) Your compiler: We hates it, it burns us, precious, nasty syntax it is! Re:What about all of these? (Score:3, Funny) Wouldn't it be cool to run all of GCC's text messages through some sort of "Gollumnizer" (like the perl script out there that can convert english to Yoda-like phrasing)? Hell you could even rename it: "Gollum's Compiler Collection" in other news... (Score:3, Funny) Wade'da'minute... (Score:2, Insightful) Which method is covered for source code comparisions? 1. two printouts held together and up toward a lighted source? 2. side-by-side subjective eyeball comparision 3. diff (and all derivative comparision tools) 4. diff with some wiggle-room command line options? 5. NSA-grade pattern analysis supercomputer? I'm slightly guarded here, but these SCO FUD-busting articles seemed very promising... Read the PDF... (Score:5, Informative) Re:Read the PDF's methodology (Score:3, Informative) 1. ideas 2. purposes 3. procedures 4. processes 5. system 6. method of operations 7. facts 8. unoriginal elements WOW! Okey Doke. So, now the IBM legal team is really looking for "copy-cat" aspect of which we, the community, are certain there aren't any (save for a few comments). 1. Ideas can't be copyrighted (but they can be patented). 2. Purposes can't be copyrighted. 3. Procedures can't be copyrighted (but they can be patented). 4. Processes can't It's a matrix... (Score:5, Funny) SCO, don't try and claim that IBM has your code. That's impossible. Instead, realize the truth. There is no SCO code. Darl sez... (Score:5, Funny) There are no American tanks in Baghdad! They are nowhere near Baghdad. Their forces committed suicide by the hundreds.... The battle is very fierce and God made us victorious. The fighting continues. Ooops, wrong script. (fumbles with papers) IBM is lying about the lack of stolen code. We need another delay to find stolen code. There can be no doubt that Linux contains stolen code. Thanks Professor Davis... and thanks ESR... (Score:5, Informative) ESR [catb.org] deserves three cheers for 'scratching his itch', making a tool to compare copyrighted code. To have it actually used in the SCO case which was the annoying impetus for its creation (AFAICT) has to be a nice feeling. I'm not an ESR fanboy, but I'll give him props when I think he deserves it and in this case I think he does. --LP Re:Thanks Professor Davis... and thanks ESR... (Score:5, Interesting) see my work used in this comparison. Extremely good. you can now expect to be subpoena'd... (Score:3, Funny) Re:Thanks Professor Davis... and thanks ESR... (Score:3, Insightful) He didn't get $550/hr to run comparator, he got the fee for being an expert recognizable as such to the court and damned near irrefutable on the subject. His r $550 an hour....and he reviewed 15 lines of code? (Score:5, Funny) He basically had some software look for similarities in the code, and then manually verified the hits. Wow....$550/hour to do that. I've got a CS degree - I'll volunteer to do it for half that! Oh yeah, he also explained the significance of return statements so that non-programmer types could understand. -ted Re:$550 an hour....and he reviewed 15 lines of cod (Score:5, Insightful) See you in 10 years! (trans: read the relevant parts of his CV in the PDF- this guy is FOR REAL.) Duh! Can't you READ?! (Score:3, Informative) Check. Columbia Law Review article on "the Legal protection of Computer Programs". Check. Software Law journal article on "The Nature of Software and its Consequences for Establishing and Evaluating Similarity. BIG Check. Court Expert on Software Copyright Infringement. Check. Retained by the DOJ to investigate copyright theft (and subsequent cover up) by the FBI, NSA, DEA, US Not So Fast Mr. Davis! (Score:5, Funny) And now My name is Darl McBride, and I have authorized this message! Scope (Score:3, Interesting) Why? 6 million lines of code compared against 6 million (or more) will take a exponentially more time than 27000 vs 6 million. SCO code (Score:2, Funny) Hmmm...I wonder if he can prove that COMPARATOR and SIM do not contain any SCO code? busted! (Score:5, Funny) IBM: byte us. IBM has WMD, claims SCO. (Score:5, Funny) SCO hasn't played their trump card yet... (Score:3, Funny) Formal Request to Randall Davis (Score:5, Insightful) I do not fault your analysis; I would like to know more about your methodology, beyond the limited scope of the deposition. -Hope Re:Formal Request to Randall Davis (Score:5, Interesting) I'm more interested in the Abstraction and Comparision aspect. Forget the Filtration aspect as they seem only to pertain to non-Copyright (mostly patentable objects). Now, for Comparision... What are the wiggle room concepts introduced? I know of the most commonly used one such as "Upper-lowercase, multiple whitespaces" And for the Abstraction, ones I know of are: inverse logic (a gt b) vs. (b lt a) and inverted or flipped loops. I know in for Abstraction, one can evade the copyright in this manner. But for Comparision....? Re:Formal Request to Randall Davis (Score:5, Insightful) Um. Dr. Davis is the guy who first came up with the abstraction, filtration, comparison test - he was the expert witness in Computer Associates vs. Altai. Check his credentials in the first section. He actually addresses the point you're asking - the code actually finds looser matches than would be found with abstraction, filtration, comparison. So he just ran them through that, said "well, no matches" - since it's a looser comparison, a stricter comparison would be of no benefit. I think the court will give him the benefit of the doubt that he knows how to do something that he was the first one to do. Re:Formal Request to Randall Davis (Score:4, Interesting) Obligatory stock graph (Score:3, Insightful) IBM had to do this... (Score:5, Funny) His resume! (Score:4, Interesting) "I have also been retained by the Department of Justice in its investigation of the INSLAW matter. In 1992 (and later in 1995) my task in that engagement was to investigate alleged copyright theft and subsequent cover-up by the Federal Bureau of Investigations, the National Security Agency, the Drug Enforcement Agency, the United States Customs Service, and the Defense Intelligence Agency." Holy rat shit Batman! Re:His resume! (Score:4, Funny) So Professor Davis can not only tell us that there is no SCO code in linux, but he should also be able to tell us how much crack the SCO weasels had to smoke before formulating their outrageous claims. SCO's hubris (Score:5, Interesting) [2] Mr. Gupta of SCO told the court some specific lines of SCO code mathcing some specific lines of ibm code. That turns out to be a lie. Randall David points out on p. 10 that it is rather obvious even to a non-technical user that they are not similar! [3] SCO had the gall to claim a 3-line code #endif return } as being stolen!! Even among these 3 lines, the #endif was followed by one comment in one code, and one comment in another. And one code had a newline between, and one didn't. As Randall Davis points out, this is like saying that oen author stole from another author since in somewhere in 2 of their books, 2 sentences both end in "the end". In related news... (Score:3, Funny) Wilson was subpoenaed on July 3, 2004 for apparently using SCO Unix bullshit in his underwear. SCO lawyers contended that, in addition to all of their other bullshit, this particular stripe of fecal matter in Wilson's BVDs was, in fact, similar the other bullshit that they have spread around since they began their legal actions. Wilson, a World War II veteran and resident at the Shady Acres Memory Care facility on the western edge of Alatoosa, was not immediately aware of what SCO was in the first place. "I thought it was the VA -- finally giving me my money for that piece of Kraut shrapnel I took in 1942! Fucking Krauts! Where's my applesauce? Is my wife around?" Officials at the memory care facility noted that Wilson is an Alzheimers patient who frequently forgets to wipe himself after using the bedpan, hence the source of the stripe in his underwear. They were aware of the legal action again Wilson by SCO, but rather than stir up his angina and blood pressure by witholding the mail that he watches being delivered every day, they let him open the SCO legal letter himself. "We're just glad he didn't keel over with a stroke," said Frank Johnson, the head nurse of the memory care facility. "He just ranted about the VA and pissed down his leg while asking for his son, who has been dead for 16 years after a car accident. It could've been a lot worse." The examination of the fecal stripe in the suspect pair of BVDs turned up concrete evidence that, in fact, the shit was Wilson's. In fact, it was not even bullshit and thus not legally open to subpoena by SCO on the grounds that it was more of SCO's bullshit. No countersuit has been filed, as Wilson's surviving family members have apparently never visited him at the facility and only wish to pay the bills for his care. IronChefMorimoto Old news, McBride has already admitted this (Score:4, Interesting) Re:Old news, McBride has already admitted this (Score:5, Insightful) The basic result is that no such lines existed that can be demonstrated to be non-literal copying, or literal copying. -Rusty SCO Stalling (Score:3, Funny) Heh, paragraph 30 (Score:5, Informative) I think that pretty much sums up this whole case from the beginning. SCO is like a Smoke & Mirrors show... (Score:3, Funny) Maybe SCO should get Dan Rathers help. (Score:4, Funny) SCO MATRIX (Score:4, Funny) Only try to realize the truth: There is no code. Then you will see it is not the code that is gone; it is only your head. Hardly a surprise but there's more (Score:4, Insightful) Obligatory Simpson's quote... (Score:3, Funny) Justice upgrade (Score:5, Insightful) Re:Justice upgrade (Score:3, Interesting) Hey Darl, had enough yet?!?! (Score:3, Interesting) Not to mention the fact that you have no case!! Never had one, never will have one!! Do you sleep well at night, Darl? Do your employees welcome you to the office when you show up for work? Or do they jeer at the man whose cost them any future they could ever have had in the IT industry in the hope that they might "get rich quick" by trying to bust up Linux? Caldera (let's call it what it is...) was one of the Linux leaders and you've turned this once Linux company into a litigation machine just like you're famous for. Well this time, the joke's on you pal. You've come up against two things you didn't count on. One, that a mega corporation like IBM might actually fight you instead of just paying you off and two, the tenacity of the Linux community and our unique ability to find the facts about a given situation. *This* is how it works here, we police each other with the very same eye we've used to scrutinize this farce of yours. We have come out on top, and we will always come out on top. We've stared you in your ugly face and we've not flinched. Screw you, Darl McBride. Sincerely, Gregory Casamento. Re:Finally... (Score:5, Insightful) Re:Finally... (Score:5, Informative) This has been gone over at length on Groklaw. IBM HAS taken action. No matter what SCO does, IBM still has a huge countersuit under something called Lanham Act [internet.com]. Methinks SCO is in a bit of trouble question (Score:5, Interesting) Re:question (Score:5, Informative) Re:question (Score:5, Interesting) If Novell did that they would be violating the GPL and infringing on the copyrighted work of Open Sorce programmers. SCO tried almost the exact same thing (They distribute Linux source (including "stolen" code) under the GPL and then insist that it is illegel to distribute under the GPL and that the GPL is invalid and maybe even un American. Re:question (Score:5, Informative) Citing the GPL:Clear enough? Re:question (Score:3, Interesting) It looks like they weren't transferred. It is an open question if Novell would be required to make such a transfer (although most people think it unlikely). Novell could do that. They own they copyright. However, they would have to release the code under the GPL or whatever license is compatible with the GPL and on the files they r Re:Finally... (Score:4, Interesting) The courts have their thorough processes to run through. SCO will get umpteen chances to submit memorandums, emergency memorandums, memorandums in opposition to motions, memorandums in support of motions, motions to support memorandums in support of motions for summary judgement, no wait, theres more... It's making me ill to watch how easily the process is to abuse. But thank God, unless a MS steps in and ponies up the cash, it will eventually be over. Re:Finally... (Score:5, Funny) They're not quite dead yet. SCO: I don't want to go on the cart!Oh, don't be such a baby. You're not fooling anyone, you'll be stone dead in a moment. Re:Finally... (Score:3, Insightful) Re:Finally... (Score:5, Insightful) Since Dr. Randall Davis is an expert witness for IBM, I am guessing that SCO will say, "ain't so!" and then they will ask for time to refute Randall's findings and perhaps come up with an expert witness of their own that finds thousands of "matches." Hopefully the judge in this case will recognize Randall for the expert that he is and accept his findings. However, that just doesn't seem likely to me. This is just another round in a case that will continue like this ad nauseum. Erick SCO has their 'expert' (Score:4, Funny) Re:Finally... (Score:5, Insightful) Dr. Davis is the person who first elucidated how you compare code (the "abstraction, filtration, comparison" test - Computer Associates vs. Aitai) to see if it violates copyright. SCO will have a hard time trying to argue that its depositions (which are from non-experts, though they claim 'unnamed' experts performed the work) are from people more qualified than Dr. Davis. So I guess what I'm saying is that SCO will have a hard time finding an expert witness more qualified than Dr. Davis. (Please note that if they try to present a deposition from one, that will likely be stricken - as SCO has been ordered by the court to present such a deposition, and has not - thus indicating it doesn't have one) And I highly doubt that the court will value any other expert over Dr. Davis anyway. SCO has two of its own employees (Dr. Davis is not an IBM employee, though he is being retained by IBM). IBM has the expert witness who first defined how you compare code. Hmm, I wonder which the judge will believe... Re:Finally... (Score:5, Interesting) Whether they still have any patents or copyrights on the functionality of UNIX remains to be seen, and such a case wouldn't necessarily NEED code theft to go forward. Any idiot can see that Linux is a UNIX clone -- the question at that point would be the legality of the cloning process and the layers of licensing that surround it. Re:Finally... (Score:3, Informative) Whether they still have any patents or copyrights on the functionality of UNIX remains to be seen,...Ummm, no it doesn't. We already know that SCO doesn't have any patents, and there's no such thing as a copyright on functionality. We copyright code, not functionality. Re:Finally... (Score:3, Informative) Yep. You can't copyright ideas, only a particular expression of ideas. In as much as the code -is- the idea, or implements a standard, it can't be copyrighted (e.g. interfaces). Patents cover ideas, not copyright. Not that SCO hasn't argued exactly the opposite! They've been saying "UNIX concepts and methods" have been infringed as in the press, and even in the courts. It hasn't flown in court at all. The only examples they a judge will weigh. (Score:5, Informative) If I recall correctly, Randy told me that he has served as a special master in several cases. Re: a judge will weigh. (Score:5, Informative) One would hope, as a matter of fact, the SCOexpert would be required to show where he found matches. That (if it exists) can be explicitly shown to the court. Then, if need be, the experts can argue over wether or not they match. Kind of like fingerprints. The suspect's fingerprints are entered as evidence, as are fingerprints found at the scene. The experts can then argue about wether or not they match. But until those fingerprints are presented and accepted as evidence, there is no weighing of testimony to be done. Re: a judge will weigh. (Score:5, Interesting) As a matter of fact SCO did show the evidence. This was enumerated in Sandeep Gupta's deposition. The pointed to pdf file has a table of all the files aledged to be copied from Unix sources, and this deposition specifically states he looked at those also (since his automatic detection program failed to find it) and the evidence of copying failed to apply the normal legal standards (also outlined in the deposition). This is very interesting reading indeed. Re:Finally... (Score:4, Interesting) That's a final word as far as I'm concerned, and I'd venture so far as to say if IBM wants to make it so it's the final word as far as the law is concerned. Re:I found this out a while ago... (Score:5, Insightful) Re:I found this out a while ago... (Score:3, Funny) < IBMcode < IBMcode < IBMcode === > SCOliarscode > SCOliarscode > SCOliarscode > SCOliarscode Either that, or nedit couldn't open such a large file and wound up with a (null) when it tried to malloc the entire SCO code base and IBM code base. (Over-analysing jokes - it's not just for pendants any more!) Re:I found this out a while ago... (Score:2) Maybe it's because I've never used nedit and am missing something? Re:15 hits (Score:2, Insightful) All the SCO bullshit over? Far from it. There are still a few hundred million lines of AIX that haven't been compared. And even if it's over for IBM, doesn't make it necessarily over for Linux in general. Re:Sounds like.... (Score:3, Insightful) Actually, didn't Prof Davis also just prove that SCO's source doesn't include Linux code?? If SCO had stolen anything and included it in their code, it would have shown up in the comparator test, wouldn't it?? The comparison just shows common code, it doesn't distinguish which is
https://news.slashdot.org/story/04/09/17/1818233/randall-davis-ibm-has-no-sco-code
CC-MAIN-2017-30
refinedweb
5,137
74.39
4 years, 5 months ago. Nucleo L152RE Flash issue I'm trying to write some data on internal Flash of L152RE but after I reset the microcontroller either it hangs or whole flash is erased. It simple do nothing after reset. Here is the sample code: include the mbed library with this snippet #include "mbed.h" Serial pc(USBTX, USBRX); int main() { uint32_t a[32]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32}; uint32_t *rawdata=&a[0]; HAL_StatusTypeDef status; FLASH_EraseInitTypeDef erase_pages; erase_pages.PageAddress=0x0807ff00; erase_pages.NbPages=1; erase_pages.TypeErase=TYPEERASE_PAGES; uint32_t *error; HAL_FLASH_Unlock(); HAL_FLASHEx_Erase(&erase_pages, error); HAL_FLASH_Lock(); HAL_FLASH_Unlock(); status=HAL_FLASHEx_HalfPageProgram(0x0807ff00,rawdata); HAL_FLASH_Lock(); uint32_t address=0x0807ff00; for(int i=0;i<32;i++) { uint32_t tmp = 0; tmp = *(__IO uint32_t*)address; pc.printf("value=%d\n\r",tmp); address=address+4; } } Kindly help. Thank you. You need to log in to post a question Why yo udont check what is the error value? Not handling error conditions?posted by Martin Kojtal 09 Mar 2015 Actually the error was because of the 'error' value. I was passing 'error' without initializing it. Problem solved :)posted by Naveed Anwar 09 Mar 2015
https://os.mbed.com/questions/6576/Nucleo-L152RE-Flash-issue/
CC-MAIN-2019-35
refinedweb
212
50.53
Last week was interesting after I posted my article, Create an Aurelia Application with ASP.NET Core 1.0, Part 1 - Setup . On that same day, Aurelia 1.0 was released . Nice timing. Since Aurelia 1.0 just recently came out, there may be some adjustments we need to make, but we'll address them as they appear and fix them. Today, we'll focus on building the navigation for our application. But first, a word from the developer... Knowing Where To Hit For those new to JavaScript frameworks, you may find it a bit overwhelming with a steep learning curve when building applications. Especially with JavaScript. You always need to know where to hit . TL;DR;Study up on your JavaScript before diving even deeper into JavaScript frameworks. I won't lie. This is a new area for me as well, but there are a couple of observations I'm seeing with Aurelia. - Not only is it a new type of JavaScript (ES6 with new syntax), it's also a new framework (Aurelia), new environment (JavaScript CLI tooling), and new programming style (App In A Browser). Even though I know JavaScript, this is a whole new world and different way of approaching development... in a browser... with JavaScript. - Don't get frustrated if you don't get it right the first time because I'm experiencing the same thing you are. ;-) - I know most MVC developers don't want to hear this, but I'm starting to compare Aurelia to WebForms , making it a little easier to understand. As I continue to work with Aurelia, I'll be posting more observations. Now, on to building our Aurelia app. Need an Update With Aurelia 1.0 out, we need to update our library. - Open a command prompt in your project directory. - Based on the project from the last post, all you should need to do is type jspm updateand you should see Aurelia was updated to 1.0 at the end of the process. This should update all of your Aurelia libraries to 1.0. Along with this update, we do need a couple more libraries for this project, but let's focus on the basics with Aurelia for now. Initial Application Structure One possible structure of an Aurelia application inside an ASP.NET MVC application could look like this. The only reason I included MVC in this project was for the Web API aspect that we'll touch on in a later post. For now, let's discuss the different file types in the project. As you know, we created a default.html and this is our Aurelia Bootstrapper. This page provides the essentials to kick off the application. If you notice the body tag, you'll see an aurelia-app attribute. The default setting is "app" which loads an app.html/app.js pairing, but you can add aurelia-app="src/mynewapp" and it will load and execute that instead.> Just like any web page, we need to have an index.html, default.html, default.aspx, or whatever page is your platform's default. This is the primary entry point to kick off your application. We also have a system.js which allows us to use dynamic module loading of JavaScript (as you can see with the SystemJS.import()). Another file we need for our Aurelia application is the main.js. wwwroot/main.js export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging(); aurelia.start().then(() => aurelia.setRoot()); } This is where we can specify and load plugins, define the configuration, and add other features to our Aurelia application. For now, we'll set up the standard configuration and development logging. Think of this as your Startup.cs in the new ASP.NET Core project only a JavaScript version of your Middleware . Adding Additional Libraries As I mentioned, we are using the Jasny bootstrap library for the sliding menu. How do we add that to our Aurelia app? If you want to add any library, you can grab it easily from GitHub by typing: jspm install jasny=github:jasny/bootstrap With the prefix github, you can install any github library into Aurelia. See the 'jasny='? This is the name you include in your main.js. Oh, we also need font-awesome as well. jspm install fontawesome=github:FortAwesome/Font-Awesome Whoops! Almost forgot about jQuery for the Jasny Bootstrap library. jspm install jquery Next, we can include our imports of these libraries in our main.js file (changes in bold ) wwwroot/main.js import 'bootstrap'; import 'fontawesome'; import 'jasny'; export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging(); aurelia.start().then(() => aurelia.setRoot()); } We also need to modify our bootstrapper default.html file to include our JavaScript libraries.'); SystemJS.import('jquery'); SystemJS.import('bootstrap'); SystemJS.import('jasny'); </script> </body> </html> Now that our libraries are defined, we can work on the navigation for the app. We Need to Route! Our app.html/app.js is our host with a router attached to it. The navigation.html is taken from the previous code and modified to work with Aurelia. For starters, we need a page to introduce the application. Let's set up a dummy one. Our app.html and JS now look like this. wwwroot/app.html <template> <require from="./css/site.css"></require> <require from="./views/navigation.html"></require> <require from="./lib/bootstrap/dist/css/bootstrap.css"></require> <require from="./jspm_packages/github/jasny/bootstrap@3.1.3/css/jasny-bootstrap.min.css"></require> <navigation router.</navigation> <div class="page-host"> <router-view></router-view> </div> </template> wwwroot/app.js export class App { configureRouter(config, router) { config.title = 'Codemash App'; config.map([ { route: ['','codemash'], name: 'codemash', moduleId: './views/Codemash', nav: true, title:'Home'} ]); this.router = router; } } The app.html has some... interesting ways of writing HTML. ;-) - First, the navigation.html can be represented as a tag element (navigation). That functionality is out of the box. The only thing I added was a file and that filename became an element. - Next, the require tags are similar to your link tags defining your CSS for the application. - If a router is defined in the model (I still think it feels like "code-behind"), a router-view element is required to display your "navigation view." This reminds me of the @RenderBody() in ASP.NET MVC. Wherever that <router-view> tag is at, that is where your screens will appear. In our app.js, the configuration and router are injected into the configureRouter method and we define our map. The config.map has one important section to observe. It's the moduleId. The moduleId is the path to the view that we want to display on the page. Since we only have one page, we'll add this for now. We also save the router in a property for later use. Finally... The Navigation! If you remember the navigation on the client-side , we had the following HTML: > <div class="container-fluid body-content"> <div class="row"> @RenderBody() </div> <footer> <p>© @DateTime.Now.Year - Built for Codemash</p> </footer> </div> Examine the MVC View and you'll notice that when we're done, the @RenderBody becomes the <router-view> for all of the views in our app.html. It's very similar to the MVC way of doing things, only we're using JavaScript. For the navigation, luckily all we need are the two navigation items from the top. We'll place those into our navigation.html. wwwroot/views/navigation.html <template bindable="router"> <nav id="codemashMenu" class="navmenu navmenu-default navmenu-fixed-left offcanvas" role="navigation"> <span class="navmenu-brand">Menu</span> <ul class="nav navmenu-nav"> <li><a href="#"><i class="fa fa-2x fa-users fa-fw"></i> All Sessions</a></li> <li><a href="#"><i class="fa fa-2x fa-bullhorn fa-fw"></i> All Speakers</a></li> <li><a href="#"><i class="fa fa-2x fa-calendar fa-fw"></i> Pre-Compiler (Tuesday)</a></li> <li><a href="#"><i class="fa fa-2x fa-calendar fa-fw"></i> Pre-Compiler (Wednesday)</a></li> <li><a href="#"><i class="fa fa-2x fa-calendar fa-fw"></i> Conference (Thursday)</a></li> <li><a href="#"><i class="fa fa-2x fa-calendar fa-fw"></i> Conference (Friday)</a></li> <li><a href="#"><i class="fa fa-2x fa-list-ol fa-fw"></i> My Agenda<> </template> In our template, you'll notice we have to bind the router to the template. This exposes the router property to the view which allows us to perform actions using the router. I know I'm way off with the hard-coded URLs (yeah, a hashtag), but I want to explain something with the router. The router is how you get around throughout your application and it's very important. As I understand it, it's quite possibly the most important piece of an Aurelia app. In our app.js code, we saved the router in a property so we could use it later. Well... now it's later. In Aurelia, you can loop through all of the items in the router and display them in your HTML with a for..next syntax. Since we just have one screen, we can implement the URL and home page in the navigation (navigation.html). <nav id="codemashMenu" class="navmenu navmenu-default navmenu-fixed-left offcanvas" role="navigation"> <span class="navmenu-brand">Menu</span> <ul class="nav navmenu-nav"> <li repeat. <a href.<i class="fa fa-2x fa-fw"></i> ${row.title}</a> </li> </ul> </nav> How about that?! Less code with more impact! The router property is exposed from the app.js file and provides us the list of navigation elements for our menu. Another interesting tidbit in this piece of code is the href.bind. What the heck is this? This allows us to bind any HTML attribute to a JavaScript property in our model. Since we are using navigation and it automatically generates the href, we can access it and place it into the href attribute. Of course, we also have the title which is represented by a ${row.title}. Convenient, no? The Results While it's not very sexy (missing some CSS styles), let's see what we've built so far. And when we click on the hamburger (the three lines in the top left corner), we get the menu sliding out (thanks to Jasny). Not bad for a first-timer to Aurelia. Conclusion With Aurelia, your application can be as simple or as complex as you want it and Aurelia seems to handle it quite well. Over the past 4 months, something must've stuck in my head as I kept reading about Aurelia. During this entire process of two hours (and four hours writing this post), I only had to look up one aspect as to how Aurelia loads an external JavaScript library into the system. Once I figured that out, and based on everything I've learned about the framework, I think I'm on my way. But I haven't got to the screens or API section yet. Stay Tuned! We'll talk about Web Services in Aurelia next. Have you played with Aurelia yet? Do you think it's easy to use? Or difficult? Which part do you think is easy? Post your comments in the sidebar.
http://126kr.com/article/7sicytjkqj5
CC-MAIN-2017-09
refinedweb
1,889
59.6
Red Hat Bugzilla – Bug 70925 The getdents(2) page has multiple problems Last modified: 2007-04-18 12:45:17 EDT From Bugzilla Helper: User-Agent: Mozilla/4.78 [en] (X11; U; Linux 2.4.17 i686) Description of problem: The described structure and prototype do not match the kernel, the include list is incorrect, the 64bit call and structure are not documented, and the comment for the offset field is incorrect. Also, the array length is incorrect (the page should probably mention that this field is actually dynamic), the fact that the offset is only a cookie is not mentioned. Version-Release number of selected component (if applicable): How reproducible: Always Steps to Reproduce: 1. read manpage 2. try to use the information 3. end up reading kernel source and searching google for better info Actual Results: See below. Expected Results: See below. Additional info: Bug 1: getdents(2) should describe the kernel system call interface. The types do not match the kernel version in signedness. /* from Linux 2.4.18 */ struct linux_dirent { unsigned long d_ino; /* inode number */ unsigned long d_off; /* offset from the start of the directory */ unsigned short d_reclen; /* length of this record */ char d_name[1]; /* filename with null-termination, length is variable */ }; Bug 2: The d_off field is misdocumented as being the offset to the next directory entry in the current manpage. Bug 3: The name field is misdocumented as being limited to NAME_MAX+1 chars in the current manpage. That bug has a sub-bug which is that there should be no +1 since NAME_MAX should already include room for the NUL termination. Bug 4: The return type should be "long" instead of "int". The syscall prototype from 2.4.18: long sys_getdents(unsigned int fd, void * dirent, unsigned int count); (You can substitute "struct dirent" in place of "void".) Bug 5: getdents64() is not documented nor is the structure. struct linux_dirent64 { __u64 d_ino; /* inode number */ __s64 d_off; /* offset from start of directory */ unsigned short d_reclen; /* length of this record */ unsigned char d_type; /* hint for type of inode (file,directory,etc.) */ char d_name[0]; /* filename including null-termination, variable length */ } Bug 6: The manpage should describe how to use the function. The first thing to note is that one needs to allocate more space than given by struct dirent so that the kernel can fill in the file name. The second thing to note is that the return value does not give enough information to tell how many structures have been read without counting the d_reclen fields. It should also mention that the C library may have its own version of struct dirent which may conflict with the kernel version. The third thing to note is that the d_off field should not be treated as an offset in bytes (though it usually is) but as a cookie. This means doing to math on it. It may only be fed to lseek(64) as-is. This is especially important on non-POSIX filesystems like NFS. Bug 7: The list of includes is not correct. Including unistd.h may conflict with kernel headers (mixing glibc and kernel headers is usually a bad idea). The man page should probably warn against including unistd.h or sys/types.h from the C library since they also define a different struct dirent. The only headers which need to be included are: #include <linux/unistd.h> #include <linux/types.h> There is a linux/dirent.h header with what seem to be kernel structures, but they limit filenames to 256 characters. However, neither of those will define the kernel getdents structure. The manpage should make it clear that you will need to define it yourself. Summary: This man page has several factual problems and several omissions. If you would rather I report this bug directly to the LDP then I would be glad to do so. Please CC me on any updates or information requests. The best place to submit this is the man-page author, aeb@cwi.nl
https://bugzilla.redhat.com/show_bug.cgi?id=70925
CC-MAIN-2017-09
refinedweb
668
65.12
Spring Cloud Sleuth in a Monolith Application Last modified: February 12, 2020 1. Overview In this article, we're introducing Spring Cloud Sleuth – a powerful tool for enhancing logs in any application, but especially in a system built up of multiple services. And for this writeup we're going to focus on using Sleuth in a monolith application, not across microservices. We've all had the unfortunate experience of trying to diagnose a problem with a scheduled task, a multi-threaded operation, or a complex web request. Often, even when there is logging, it is hard to tell what actions need to be correlated together to create a single request. This can make diagnosing a complex action very difficult or even impossible. Often resulting in solutions like passing a unique id to each method in the request to identify the logs. In comes Sleuth. This library makes it possible to identify logs pertaining to a specific job, thread, or request. Sleuth integrates effortlessly with logging frameworks like Logback and SLF4J to add unique identifiers that help track and diagnose issues using logs. Let's take a look at how it works. 2. Setup We'll start by creating a Spring Boot web project in our favorite IDE and adding this dependency to our pom.xml file: <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> Our application runs with Spring Boot and the parent pom provides versions for each entry. The latest version of this dependency can be found here: spring-cloud-starter-sleuth. To see the entire POM check out the project on Github. Additionally, let's add an application name to instruct Sleuth to identify this application's logs. In our application.properties file add this line: spring.application.name=Baeldung Sleuth Tutorial 3. Sleuth Configurations Sleuth is capable of enhancing logs in many situations. Starting with version 2.0.0, Spring Cloud Sleuth uses Brave as the tracing library that adds unique ids to each web request that enters our application. Furthermore, the Spring team has added support for sharing these ids across thread boundaries. Traces can be thought of like a single request or job that is triggered in an application. All the various steps in that request, even across application and thread boundaries, will have the same traceId. Spans, on the other hand, can be thought of as sections of a job or request. A single trace can be composed of multiple spans each correlating to a specific step or section of the request. Using trace and span ids we can pinpoint exactly when and where our application is as it processes a request. Making reading our logs much easier. In our examples, we will explore these capabilities in a single application. 3.1. Simple Web Request First, let's create a controller class to be an entry point to work with: @RestController public class SleuthController { @GetMapping("/") public String helloSleuth() { logger.info("Hello Sleuth"); return "success"; } } Let's run our application and navigate to “”. Watch the logs for output that looks like: 2017-01-10 22:36:38.254 INFO [Baeldung Sleuth Tutorial,4e30f7340b3fb631,4e30f7340b3fb631,false] 12516 --- [nio-8080-exec-1] c.b.spring.session.SleuthController : Hello Sleuth This looks like a normal log, except for the part in the beginning between the brackets. This is the core information that Spring Sleuth has added. This data follows the format of: [application name, traceId, spanId, export] - Application name – This is the name we set in the properties file and can be used to aggregate logs from multiple instances of the same application. - TraceId – This is an id that is assigned to a single request, job, or action. Something like each unique user initiated web request will have its own traceId. - SpanId – Tracks a unit of work. Think of a request that consists of multiple steps. Each step could have its own spanId and be tracked individually. By default, any application flow will start with same TraceId and SpanId. - Export – This property is a boolean that indicates whether or not this log was exported to an aggregator like Zipkin. Zipkin is beyond the scope of this article but plays an important role in analyzing logs created by Sleuth. By now, you should have some idea of the power of this library. Let's take a look at another example to further demonstrate how integral this library is to logging. 3.2. Simple Web Request With Service Access Let's start by creating a service with a single method: @Service public class SleuthService { public void doSomeWorkSameSpan() { Thread.sleep(1000L); logger.info("Doing some work"); } } Now let's inject our service into our controller and add a request mapping method that accesses it: @Autowired private SleuthService sleuthService; @GetMapping("/same-span") public String helloSleuthSameSpan() throws InterruptedException { logger.info("Same Span"); sleuthService.doSomeWorkSameSpan(); return "success"; } Finally, restart the application and navigate to “”. Watch for log output that looks like: 2017-01-10 22:51:47.664 INFO [Baeldung Sleuth Tutorial,b77a5ea79036d5b9,b77a5ea79036d5b9,false] 12516 --- [nio-8080-exec-3] c.b.spring.session.SleuthController : Same Span 2017-01-10 22:51:48.664 INFO [Baeldung Sleuth Tutorial,b77a5ea79036d5b9,b77a5ea79036d5b9,false] 12516 --- [nio-8080-exec-3] c.baeldung.spring.session.SleuthService : Doing some work Take note that the trace and span ids are the same between the two logs even though the messages originate from two different classes. This makes it trivial to identify each log during a request by searching for the traceId of that request. This is the default behavior, one request gets a single traceId and spanId. But we can manually add spans as we see fit. Let's take a look at an example that uses this feature. 3.3. Manually Adding a Span To start, let's add a new controller: @GetMapping("/new-span") public String helloSleuthNewSpan() { logger.info("New Span"); sleuthService.doSomeWorkNewSpan(); return "success"; } And now let's add the new method inside our service: @Autowired private Tracer tracer; // ... public void doSomeWorkNewSpan() throws InterruptedException { logger.info("I'm in the original span"); Span newSpan = tracer.nextSpan().name("newSpan").start(); try (SpanInScope ws = tracer.withSpanInScope(newSpan.start())) { Thread.sleep(1000L); logger.info("I'm in the new span doing some cool work that needs its own span"); } finally { newSpan.finish(); } logger.info("I'm in the original span"); } Note that we also added a new object, Tracer. The tracer instance is created by Spring Sleuth during startup and is made available to our class through dependency injection. Traces must be manually started and stopped. To accomplish this, code that runs in a manually created span is placed inside a try-finally block to ensure the span is closed regardless of the operation's success. Also, notice that new span has to be placed in scope. Restart the application and navigate to “”. Watch for the log output that looks like: 2017-01-11 21:07:54.924 INFO [Baeldung Sleuth Tutorial,9cdebbffe8bbbade,9cdebbffe8bbbade,false] 12516 --- [nio-8080-exec-6] c.b.spring.session.SleuthController : New Span 2017-01-11 21:07:54 2017-01-11 21:07:55.924 INFO [Baeldung Sleuth Tutorial,9cdebbffe8bbbade,1e706f252a0ee9c2,false] 12516 --- [nio-8080-exec-6] c.baeldung.spring.session.SleuthService : I'm in the new span doing some cool work that needs its own span 2017-01-11 21:07:55 We can see that the third log shares the traceId with the others, but it has a unique spanId. This can be used to locate different sections in a single request for more fine-grained tracing. Now let's take a look at Sleuth's support for threads. 3.4. Spanning Runnables To demonstrate the threading capabilities of Sleuth let's first add a configuration class to set up a thread pool: @Configuration public class ThreadConfig { @Autowired private BeanFactory beanFactory; @Bean public Executor executor() {); } } It is important to note here the use of LazyTraceExecutor. This class comes from the Sleuth library and is a special kind of executor that will propagate our traceIds to new threads and create new spanIds in the process. Now let's wire this executor into our controller and use it in a new request mapping method: @Autowired private Executor executor; @GetMapping("/new-thread") public String helloSleuthNewThread() { logger.info("New Thread"); Runnable runnable = () -> { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("I'm inside the new thread - with a new span"); }; executor.execute(runnable); logger.info("I'm done - with the original span"); return "success"; } With our runnable in place, let's restart our application and navigate to “”. Watch for log output that looks like: 2017-01-11 21:18:15.949 INFO [Baeldung Sleuth Tutorial,96076a78343c364d,96076a78343c364d,false] 12516 --- [nio-8080-exec-9] c.b.spring.session.SleuthController : New Thread 2017-01-11 21:18:15.950 INFO [Baeldung Sleuth Tutorial,96076a78343c364d,96076a78343c364d,false] 12516 --- [nio-8080-exec-9] c.b.spring.session.SleuthController : I'm done - with the original span 2017-01-11 21:18:16.953 INFO [Baeldung Sleuth Tutorial,96076a78343c364d,e3b6a68013ddfeea,false] 12516 --- [lTaskExecutor-1] c.b.spring.session.SleuthController : I'm inside the new thread - with a new span Much like the previous example we can see that all the logs share the same traceId. But the log coming from the runnable has a unique span that will track the work done in that thread. Remember that this happens because of the LazyTraceExecutor, if we were to use a normal executor we would continue to see the same spanId used in the new thread. Now let's look into Sleuth's support for @Async methods. 3.5. @Async Support To add async support let's first modify our ThreadConfig class to enable this feature: @Configuration @EnableAsync public class ThreadConfig extends AsyncConfigurerSupport { //... @Override public Executor getAsyncExecutor() {); } } Note that we extend AsyncConfigurerSupport to specify our async executor and use LazyTraceExecutor to ensure traceIds and spanIds are propagated correctly. We have also added @EnableAsync to the top of our class. Let's now add an async method to our service: @Async public void asyncMethod() { logger.info("Start Async Method"); Thread.sleep(1000L); logger.info("End Async Method"); } Now let's call into this method from our controller: @GetMapping("/async") public String helloSleuthAsync() { logger.info("Before Async Method Call"); sleuthService.asyncMethod(); logger.info("After Async Method Call"); return "success"; } Finally, let's restart our service and navigate to “”. Watch for the log output that looks like: 2017-01-11 21:30:40.621 INFO [Baeldung Sleuth Tutorial,c187f81915377fff,c187f81915377fff,false] 10072 --- [nio-8080-exec-2] c.b.spring.session.SleuthController : Before Async Method Call 2017-01-11 21:30:40.622 INFO [Baeldung Sleuth Tutorial,c187f81915377fff,c187f81915377fff,false] 10072 --- [nio-8080-exec-2] c.b.spring.session.SleuthController : After Async Method Call 2017-01-11 21:30:40 : Start Async Method 2017-01-11 21:30:41 : End Async Method We can see here that much like our runnable example, Sleuth propagates the traceId into the async method and adds a unique spanId. Let's now work through an example using spring support for scheduled tasks. 3.6. @Scheduled Support Finally, let's look at how Sleuth works with @Scheduled methods. To do this let's update our ThreadConfig class to enable scheduling: @Configuration @EnableAsync @EnableScheduling public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer { //... @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(schedulingExecutor()); } @Bean(destroyMethod = "shutdown") public Executor schedulingExecutor() { return Executors.newScheduledThreadPool(1); } } Note that we have implemented the SchedulingConfigurer interface and overridden its configureTasks method. We have also added @EnableScheduling to the top of our class. Next, let's add a service for our scheduled tasks: @Service public class SchedulingService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private SleuthService sleuthService; @Scheduled(fixedDelay = 30000) public void scheduledWork() throws InterruptedException { logger.info("Start some work from the scheduled task"); sleuthService.asyncMethod(); logger.info("End work from scheduled task"); } } In this class, we have created a single scheduled task with a fixed delay of 30 seconds. Let's now restart our application and wait for our task to be executed. Watch the console for output like this: : Start some work from the scheduled task : End work from scheduled task We can see here that Sleuth has created new trace and span ids for our task. Each instance of a task will get it's own trace and span by default. 4. Conclusion In conclusion, we have seen how Spring Sleuth can be used in a variety of situations inside a single web application. We can use this technology to easily correlate logs from a single request, even when that request spans multiple threads. By now we can see how Spring Cloud Sleuth can help us keep our sanity when debugging a multi-threaded environment. By identifying each operation in a traceId and each step in a spanId we can really begin to break down our analysis of complex jobs in our logs. Even if we don't go to the cloud, Spring Sleuth is likely a critical dependency in almost any project; it's seamless to integrate and is a massive addition of value. From here you may want to investigate other features of Sleuth. It can support tracing in distributed systems using RestTemplate, across messaging protocols used by RabbitMQ and Redis, and through a gateway like Zuul. As always you can find the source code over on Github. great tutorial !! Thanks Kamran, I appreciate the feedback!
https://www.baeldung.com/spring-cloud-sleuth-single-application
CC-MAIN-2020-40
refinedweb
2,235
56.86
Run-Time Library Behavior | Overview | How Do I | FAQ | Details | Sample. While it is possible to specify another entry-point function using the /ENTRY: linker switch, switch .'s nothing special you have to do when building your DLL. If you need to initialize your DLL, where you add your code depends on the kind of DLL you are writing. See Initialize a DLL for more information..) #include "horses.h" CHorse Equus( ARABIAN, MALE ); CHorse Sugar( THOROUGHBRED, FEMALE ); BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) . . . Each time a new process attempts to use the DLL, the operating system creates a separate copy of the DLL's data: this is called "process attach". The run-time library code for the DLL calls the constructors for.
https://msdn.microsoft.com/en-us/library/aa295784(v=vs.60).aspx
CC-MAIN-2015-11
refinedweb
125
64.71
General Q: What is AWS CloudFormation? AWS CloudFormation is a service that gives developers and businesses an easy way to create a collection of related AWS and third party and third party: What resources does AWS CloudFormation support? To see a complete list of supported AWS resources and their features, visit the Supported AWS Services page in the Release History of the documentation. The AWS CloudFormation Registry and AWS CloudFormation custom resources enable management of additional AWS and third party: 1. An optional list of template parameters (input values supplied at stack creation time) 2. An optional list of output values (e.g. the complete URL to a web application) 3. An optional list of data tables used to lookup static configuration values (e.g., AMI names) 4. The list of AWS resources and their configuration values 5.. Getting Started Q: How do I sign up for AWS CloudFormation? To sign up for AWS CloudFormation, click Create Free Account on the AWS CloudFormation product. AWS CloudFormation Registry Q: What is the AWS CloudFormation Registry? The AWS CloudFormation Registry is a managed service that lets you register, use, and discover AWS and third party resource providers. Third party resource providers must be registered before they can be used to provision resources with AWS CloudFormation templates. Please refer to our documentation for details. Q: What are resource providers in AWS CloudFormation? A resource provider is a set of resource types with specifications and handlers that control the lifecycle of underlying resources via create, read, update, delete and list operations. You can use resource providers to model and provision resources using CloudFormation. For example, AWS::EC2::Instance is a resource type from the Amazon EC2 provider. You can use this type to model and provision an Amazon EC2 instance using CloudFormation. Using the AWS CloudFormation Registry, you can build and use resource providers to model and provision third party resources such as SaaS monitoring, team productivity, or source code management resources. Q: What is the difference between AWS and third party resource providers? The difference between AWS and third party resource providers is their origin. AWS resource providers are built and maintained by Amazon and AWS to manage AWS resources and services. For example, three AWS resource providers help you manage Amazon DynamoDB, AWS Lambda, and Amazon EC2 resources. These providers contain resource types such as AWS::DynamoDB::Table, AWS::Lambda::Function, and AWS::EC2::Instance. For a complete reference, go to our documentation. Third party resource providers are built by another company, organization, or the developer community. They can help you manage both AWS and non-AWS resources such as AWS application resources and non-AWS SaaS software services such as monitoring, team productivity, incident management, or version control management tools. Q: What is a resource schema? In a resource provider, a resource type is expressed using a CloudFormation Resource Schema to define its properties and attributes. This schema is also used to validate the definition of a resource type. Q: How do I develop resource providers or resource types? Use the AWS CloudFormation CLI to build resource providers. You start by defining a simple declarative schema for your resources, which includes permissions required and relationships to other resources. You then use the CloudFormation CLI to generate the scaffolding for resource lifecycle handlers (Create, Read, Update, Delete and List) along with test stubs for unit and integration testing. Q: How do I register a resource provider? You can either use the use the open source AWS CloudFormation CLI or directly call the RegisterType and related Registry APIs that are available via the AWS SDKs and AWS CLI. For more details, visit our documentation. AWS resource providers are available out of the box and do not require any additional registration steps before use. Billing Q: How much does AWS CloudFormation cost? There is no additional charge for using AWS CloudFormation with resource providers in the following namespaces: AWS::*, Alexa::*, and Custom::*. In this case you pay for AWS resources (such as Amazon EC2 instances, Elastic Load Balancing load balancers, etc.) created using AWS CloudFormation as if you created them manually. You only pay for what you use, as you use it; there are no minimum fees and no required upfront commitments. When you use resource providers with AWS CloudFormation outside the namespaces mentioned above, you incur charges per handler operation. Handler operations are create, update, delete, read, or list actions on a resource. For more information, please refer to our pricing page. Q: Will I be charged for resources that were rolled back during a failed stack creation attempt? Yes. Charges for AWS resources created during template instantiation apply irrespective of whether the stack as a whole could be created successfully or not. Limits and Restrictions. Regions and Endpoints. Learn more about AWS CloudFormation Pricing
https://aws.amazon.com/vi/cloudformation/faqs/
CC-MAIN-2020-34
refinedweb
802
56.66
SQLAlchemy 1.0 Documentation Frequently Asked Questions - Frequently Asked Questions -? Project Versions Frequently Asked Questions¶ -? Connections / Engines¶ There are two major causes for this error: 1. The MySQL client closes connections which have been idle for a set period of time, defaulting to eight hours. This can be avoided by using the pool_recycle setting with create_engine(), described at Connection Timeouts. 2. Usage of the MySQLdb DBAPI, or a similar DBAPI, in a non-threadsafe manner, or in an otherwise inappropriate way. The MySQLdb connection object is not threadsafe - this expands out to any SQLAlchemy system that links to a single connection, which includes the ORM Session. For background on how Session should be used in a multithreaded environment, see Is the session thread-safe?. MetaData / Schema¶ My program is hanging when I say table.drop() / metadata.drop_all()¶ This usually corresponds to two conditions: 1. using PostgreSQL, which is really strict about table locks, and 2. you have a connection still open which contains locks on the table and is distinct from the connection being used for the DROP statement. Heres the most minimal version of the pattern: connection = engine.connect() result = connection.execute(mytable.select()) mytable.drop(engine) Above, a connection pool connection is still checked out; furthermore, the result object above also maintains a link to this connection. If “implicit execution” is used, the result will hold this connection opened until the result object is closed or all rows are exhausted. The call to mytable.drop(engine) attempts to emit DROP TABLE on a second connection procured from the Engine which will lock. The solution is to close out all connections before emitting DROP TABLE: connection = engine.connect() result = connection.execute(mytable.select()) # fully read result sets result.fetchall() # close connections connection.close() # now locks are removed mytable.drop(engine) Does SQLAlchemy support ALTER TABLE, CREATE VIEW, CREATE TRIGGER, Schema Upgrade Functionality?¶ General ALTER support isn’t present in SQLAlchemy directly. For special DDL on an ad-hoc basis, the DDL and related constructs can be used. See Customizing DDL for a discussion on this subject. A more comprehensive option is to use schema migration tools, such as Alembic or SQLAlchemy-Migrate; see Altering Schemas through Migrations for discussion on this. How can I sort Table objects in order of their dependency?¶ This is available via the MetaData.sorted_tables function: metadata = MetaData() # ... add Table objects to metadata ti = metadata.sorted_tables: for t in ti: print t How can I get the CREATE TABLE/ DROP TABLE output as a string?¶ Modern SQLAlchemy has clause constructs which represent DDL operations. These can be rendered to strings like any other SQL expression: from sqlalchemy.schema import CreateTable print CreateTable(mytable) To get the string specific to a certain engine: print CreateTable(mytable).compile(engine) There’s also a special form of Engine that can let you dump an entire metadata creation sequence, using this recipe: def dump(sql, *multiparams, **params): print sql.compile(dialect=engine.dialect) engine = create_engine('postgresql://', strategy='mock', executor=dump) metadata.create_all(engine, checkfirst=False) The Alembic tool also supports an “offline” SQL generation mode that renders database migrations as SQL scripts. How can I subclass Table/Column to provide certain behaviors/configurations?¶ Table and Column are not good targets for direct subclassing. However, there are simple ways to get on-construction behaviors using creation functions, and behaviors related to the linkages between schema objects such as constraint conventions or naming conventions using attachment events. An example of many of these techniques can be seen at Naming Conventions.) Why does .col.in_([]) Produce col != col? Why not 1=0?¶ A little introduction to the issue. The IN operator in SQL, given a list of elements to compare against a column, generally does not accept an empty list, that is while it is valid to say: column IN (1, 2, 3) it’s not valid to say: column IN () SQLAlchemy’s Operators.in_() operator, when given an empty list, produces this expression: column != column As of version 0.6, it also produces a warning stating that a less efficient comparison operation will be rendered. This expression is the only one that is both database agnostic and produces correct results. For example, the naive approach of “just evaluate to false, by comparing 1=0 or 1!=1”, does not handle nulls properly. An expression like: NOT column != column will not return a row when “column” is null, but an expression which does not take the column into account: NOT 1=0 will. Closer to the mark is the following CASE expression: CASE WHEN column IS NOT NULL THEN 1=0 ELSE NULL END We don’t use this expression due to its verbosity, and its also not typically accepted by Oracle within a WHERE clause - depending on how you phrase it, you’ll either get “ORA-00905: missing keyword” or “ORA-00920: invalid relational operator”. It’s also still less efficient than just rendering SQL without the clause altogether (or not issuing the SQL at all, if the statement is just a simple search). The best approach therefore is to avoid the usage of IN given an argument list of zero length. Instead, don’t emit the Query in the first place, if no rows should be returned. The warning is best promoted to a full error condition using the Python warnings filter (see). ORM Configuration¶ acquired using such methods.columns to get at the Column objects directly. - Mapper.relationships - namespace of all RelationshipProperty attributes. - Mapper.all_orm_descriptors - namespace of all mapped attributes, plus user-defined attributes defined using systems such as hybrid_property, AssociationProxy and others. - Mapper.columns - A namespace of Column objects and other named SQL expressions associated with the mapping. - Mapper.mapped_table - The Table or other selectable to which this mapper is mapped. - Mapper.local_table - The Table that is “local” to this mapper; this differs from Mapper.mapped_table]) Performance¶ How can I profile a SQLAlchemy powered application?¶ Looking for performance issues typically involves two stratgies. objects. If you’re feeling ambitious, there’s also a more involved example of SQLAlchemy profiling within the SQLAlchemy unit tests in the tests/aaa_profiling section. Tests in this area use decorators that assert a maximum number of method calls being used for particular operations, so that if something inefficient gets checked in, the tests will reveal it (it is important to note that in cPython, function calls have the highest overhead of any operation, and the count of calls is more often than not nearly proportional to time spent). Of note are the the “zoomark” tests which use a fancy “SQL capturing” scheme which cuts out the overhead of the DBAPI from the equation - although that technique isn’t really necessary for garden-variety profiling.. The example below illustrates time-based tests for four different methods of inserting rows, going from the most automated to the least. With cPython 2.7, runtimes observed: classics-MacBook-Pro:sqlalchemy classic$ python test.py SQLAlchemy ORM: Total time for 100000 records 14.3528850079 secs SQLAlchemy ORM pk given: Total time for 100000 records 10.0164160728 secs SQLAlchemy Core: Total time for 100000 records 0.775382995605 secs sqlite3: Total time for 100000 records 0.676795005798 sec We can reduce the time by a factor of three using recent versions of Pypy: classics-MacBook-Pro:sqlalchemy classic$ /usr/local/src/pypy-2.1-beta2-osx64/bin/pypy test.py SQLAlchemy ORM: Total time for 100000 records 5.88369488716 secs SQLAlchemy ORM pk given: Total time for 100000 records 3.52294301987 secs SQLAlchemy Core: Total time for 100000 records 0.613556146622 secs sqlite3: Total time for 100000 records 0.442467927933 range range_core(n=100000): init_sqlalchemy() t0 = time.time() engine.execute( Customer.__table__.insert(), [{"name": 'NAME ' + str(i)} for i in range range_core(100000) test_sqlite3(100000) Sessions / Queries¶ “This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar)¶ This is an error that occurs when a Session.flush() raises an exception, rolls back the transaction, but further commands upon the Session are called without an explicit call to Session.rollback() or Session.close(). It usually corresponds to an application that catches an exception upon Session.flush() or Session.commit() and does not properly handle the exception. For example: from sqlalchemy import create_engine, Column, Integer from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base(create_engine('sqlite://')) class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) Base.metadata.create_all() session = sessionmaker()() # constraint violation session.add_all([Foo(id=1), Foo(id=1)]) try: session.commit() except: # ignore error pass # continue using session without rolling back session.commit() The usage of the Session should fit within a structure similar to this: try: <use session> session.commit() except: session.rollback() raise finally: session.close() # optional, depends on use case Many things can cause a failure within the try/except besides flushes. You should always have some kind of “framing” of your session operations so that connection and transaction resources have a definitive boundary, otherwise your application doesn’t really have its usage of resources under control. This is not to say that you need to put try/except blocks all throughout your application - on the contrary, this would be a terrible idea. You should architect your application such that there is one (or few) point(s) of “framing” around session operations. For a detailed discussion on how to organize usage of the Session, please see When do I construct a Session, when do I commit it, and when do I close it?. But why does flush() insist on issuing a ROLLBACK?¶ It would be great if Session.flush() could partially complete and then not roll back, however this is beyond its current capabilities since its internal bookkeeping would have to be modified such that it can be halted at any time and be exactly consistent with what’s been flushed to the database. While this is theoretically possible, the usefulness of the enhancement is greatly decreased by the fact that many database operations require a ROLLBACK in any case. Postgres in particular has operations which, once failed, the transaction is not allowed to continue: test=> create table foo(id integer primary key); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo" CREATE TABLE test=> begin; BEGIN test=> insert into foo values(1); INSERT 0 1 test=> commit; COMMIT test=> begin; BEGIN test=> insert into foo values(1); ERROR: duplicate key value violates unique constraint "foo_pkey" test=> insert into foo values(2); ERROR: current transaction is aborted, commands ignored until end of transaction block What SQLAlchemy offers that solves both issues is support of SAVEPOINT, via Session.begin_nested(). Using Session.begin_nested(), you can frame an operation that may potentially fail within a transaction, and then “roll back” to the point before its failure while maintaining the enclosing transaction. But why isn’t the one automatic call to ROLLBACK enough? Why must I ROLLBACK again?¶ This is again a matter of the Session providing a consistent interface and refusing to guess about what context its being used. For example, the Session supports “framing” above within multiple levels. Such as, suppose you had a decorator @with_session(), which did this: def with_session(fn): def go(*args, **kw): session.begin(subtransactions=True) try: ret = fn(*args, **kw) session.commit() return ret except: session.rollback() raise return go The above decorator begins a transaction if one does not exist already, and then commits it, if it were the creator. The “subtransactions” flag means that if Session.begin() were already called by an enclosing function, nothing happens except a counter is incremented - this counter is decremented when Session.commit() is called and only when it goes back to zero does the actual COMMIT happen. It allows this usage pattern: @with_session def one(): # do stuff two() @with_session def two(): # etc. one() two() one() can call two(), or two() can be called by itself, and the @with_session decorator ensures the appropriate “framing” - the transaction boundaries stay on the outermost call level. As you can see, if two() calls flush() which throws an exception and then issues a rollback(), there will always be a second rollback() performed by the decorator, and possibly a third corresponding to two levels of decorator. If the flush() pushed the rollback() all the way out to the top of the stack, and then we said that all remaining rollback() calls are moot, there is some silent behavior going on there. A poorly written enclosing method might suppress the exception, and then call commit() assuming nothing is wrong, and then you have a silent failure condition. The main reason people get this error in fact is because they didn’t write clean “framing” code and they would have had other problems down the road. If you think the above use case is a little exotic, the same kind of thing comes into play if you want to SAVEPOINT- you might call begin_nested() several times, and the commit()/rollback() calls each resolve the most recent begin_nested(). The meaning of rollback() or commit() is dependent upon which enclosing block it is called, and you might have any sequence of rollback()/commit() in any order, and its the level of nesting that determines their behavior. In both of the above cases, if flush() broke the nesting of transaction blocks, the behavior is, depending on scenario, anywhere from “magic” to silent failure to blatant interruption of code flow. flush() makes its own “subtransaction”, so that a transaction is started up regardless of the external transactional state, and when complete it calls commit(), or rollback() upon failure - but that rollback() corresponds to its own subtransaction - it doesn’t want to guess how you’d like to handle the external “framing” of the transaction, which could be nested many levels with any combination of subtransactions and real SAVEPOINTs. The job of starting/ending the “frame” is kept consistently with the code external to the flush(), and we made a decision that this was the most consistent approach. How do I make a Query that always adds a certain filter to every query?¶ See the recipe at PreFilteredQuery. I’ve created a mapping against an Outer Join, and while the query returns rows, no objects are returned. Why not?¶ Rows returned by an outer join may contain NULL for part of the primary key, as the primary key is the composite of both tables. The Query object ignores incoming rows that don’t have an acceptable primary key. Based on the setting of the allow_partial_pks flag on mapper(), a primary key is accepted if the value has at least one non-NULL value, or alternatively if the value has no NULL values. See allow_partial_pks at mapper(). I’m using joinedload() or lazy=False to create a JOIN/OUTER JOIN and SQLAlchemy is not constructing the correct query when I try to add a WHERE, ORDER BY, LIMIT, etc. (which relies upon the (OUTER) JOIN)¶ The joins generated by joined eager loading are only used to fully load related collections, and are designed to have no impact on the primary results of the query. Since they are anonymously aliased, they cannot be referenced directly. For detail on this beahvior, see Relationship Loading Techniques. Query has no __len__(), why not?¶ The Python __len__() magic method applied to an object allows the len() builtin to be used to determine the length of the collection. It’s intuitive that a SQL query object would link __len__() to the Query.count() method, which emits a SELECT COUNT. The reason this is not possible is because evaluating the query as a list would incur two SQL calls instead of one: class Iterates(object): def __len__(self): print "LEN!" return 5 def __iter__(self): print "ITER!" return iter([1, 2, 3, 4, 5]) list(Iterates()) output: ITER! LEN! How Do I use Textual SQL with ORM Queries?¶ See: - Using Literal SQL - Ad-hoc textual blocks with Query - Using SQL Expressions with Sessions - Using Session with textual SQL directly. I’m calling Session.delete(myobject) and it isn’t removed from the parent collection!¶ See Deleting from Collections for a description of this behavior. why isn’t my __init__() called when I load objects?¶ See Constructors and Object Initialization for a description of this behavior. how do I use ON DELETE CASCADE with SA’s ORM?¶ SQLAlchemy will always issue UPDATE or DELETE statements for dependent rows which are currently loaded in the Session. For rows which are not loaded, it will by default issue SELECT statements to load those rows and udpate/delete those as well; in other words it assumes there is no ON DELETE CASCADE configured. To configure SQLAlchemy to cooperate with ON DELETE CASCADE, see Using Passive Deletes. I set the “foo_id” attribute on my instance to “7”, but the “foo” attribute is still None - shouldn’t it have loaded Foo with id #7?¶ The ORM is not constructed in such a way as to support immediate population of relationships driven from foreign key attribute changes - instead, it is designed to work the other way around - foreign key attributes are handled by the ORM behind the scenes, the end user sets up object relationships naturally. Therefore, the recommended way to set o.foo is to do just that - set it!: foo = Session.query(Foo).get(7) o.foo = foo Session.commit() Manipulation of foreign key attributes is of course entirely legal. However, setting a foreign-key attribute to a new value currently does not trigger an “expire” event of the relationship() in which it’s involved. This means that for the following sequence: o = Session.query(SomeClass).first() assert o.foo is None # accessing an un-set attribute sets it to None o.foo_id = 7 o.foo is initialized to None when we first accessed it. Setting o.foo_id = 7 will have the value of “7” as pending, but no flush has occurred - so o.foo is still None: # attribute is already set to None, has not been # reconciled with o.foo_id = 7 yet assert o.foo is None For o.foo to load based on the foreign key mutation is usually achieved naturally after the commit, which both flushes the new foreign key value and expires all state: Session.commit() # expires all attributes foo_7 = Session.query(Foo).get(7) assert o.foo is foo_7 # o.foo lazyloads on access A more minimal operation is to expire the attribute individually - this can be performed for any persistent object using Session.expire(): o = Session.query(SomeClass).first() o.foo_id = 7 Session.expire(o, ['foo']) # object must be persistent for this foo_7 = Session.query(Foo).get(7) assert o.foo is foo_7 # o.foo lazyloads on access Note that if the object is not persistent but present in the Session, it’s known as pending. This means the row for the object has not been INSERTed into the database yet. For such an object, setting foo_id does not have meaning until the row is inserted; otherwise there is no row yet: new_obj = SomeClass() new_obj.foo_id = 7 Session.add(new_obj) # accessing an un-set attribute sets it to None assert new_obj.foo is None Session.flush() # emits INSERT # expire this because we already set .foo to None Session.expire(o, ['foo']) assert new_obj.foo is foo_7 # now it loads Attribute loading for non-persistent objects One variant on the “pending” behavior above is if we use the flag load_on_pending on relationship(). When this flag is set, the lazy loader will emit for new_obj.foo before the INSERT proceeds; another variant of this is to use the Session.enable_relationship_loading() method, which can “attach” an object to a Session in such a way that many-to-one relationships load as according to foreign key attributes regardless of the object being in any particular state. Both techniques are not recommended for general use; they were added to suit specific programming scenarios encountered by users which involve the repurposing of the ORM’s usual object states. The recipe ExpireRelationshipOnFKChange features an example using SQLAlchemy events in order to coordinate the setting of foreign key attributes with many-to-one relationships. Is there a way to automagically have only unique keywords (or other kinds of objects) without doing a query for the keyword and getting a reference to the row containing that keyword?¶ When people read the many-to-many example in the docs, they get hit with the fact that if you create the same Keyword twice, it gets put in the DB twice. Which is somewhat inconvenient. This UniqueObject recipe was created to address this issue.
http://docs.sqlalchemy.org/en/latest/faq.html
CC-MAIN-2014-42
refinedweb
3,433
55.95
Dropwizard From the Start — Part 2: Building a UI Using Mustache Dropwizard From the Start — Part 2: Building a UI Using Mustache If you’ve been following along with my first two articles, I am on a journey of discovery through the land of Dropwizard. I’m finding out what all the fuss is about, and whether I can learn to like frameworks again. We had a simple chat system working which was purely JSON on top of REST. The next logical thing is to build a UI. Join the DZone community and get the full member experience.Join For Free If you’ve been following along with my first two articles (here and here), I am on a journey of discovery through the land of Dropwizard. I’m trying to discover what all the fuss is about, and whether I can learn to like frameworks again. We had a simple chat system working which was purely JSON on top of REST. The next logical thing is to build a UI. Along with everything that comes in Dropwizard core (Jetty, Jersey, and Jackson), there’s a whole heap of extra stuff Dropwizard throws in as optional, one of which being the *dropwizard-views* packages. These give the developer access to both Freemarker and Mustache templating engines with a little bit of Dropwizard magic over the top. Mustache I’ve always been a big fan of Handlebars, which is effectively a derivative of Mustache. It’s really simple to use; you simply write plain old HTML, but where you want variables from Java land you simply wrap them in double curly braces. You’re fairly limited to object access and not much more, so the UIs end up clean; no JSP-esque UI logic hell here. The HTML/mustache mashup is a template which is compiled against a Java class, where the knowledge comes from. <html> <head></head> <body> <div class="top"> <div class="user">Logged in as {{currentUser}}</div> </div> </body></html> Compiled against: public class MyView{ public String getCurrentUser() { return “Bobby”; } ] Will result in: <html> <head></head> <body> <div class="top"> <div class="user">Logged in as Bobby</div> </div> </body></html> Easy peasy! Mustache has basic syntax for going through loops and I’ve found it to be simple to use and sufficiently powerful. It’s apparently being used by Twitter according to the Mustache Github page, so it should hopefully be sufficiently performant. Where I’ve been reasonably impressed is the extra value that Dropwizard adds. Normal usage requires you to create a Mustache factory, compile the template and write the data out from it; whilst not particularly onerous, it’s extrenuous boiler plate would be nice to be rid of. Fortunately, Dropwizard takes care of it. By returning a class that extends a Dropwizard View class, it will automatically render the page. I want a single page for my UI: a list of people I’m chatting with on the left and the current chat on the right. This means my view needs a list of all my chats, plus the current chat and the usernames to allow me to submit chats. public class ChatroomView extends View { private final List<ChatView> allChatsForThisUser; private final String currentUser; private final Chat currentChat; private final String otherUser; public ChatroomView(String currentUser, String otherUser, Chat currentChat, List<ChatView> allChatsForThisUser) { super("chat.mustache"); this.currentUser = currentUser; this.otherUser = otherUser; this.currentChat = currentChat; this.allChatsForThisUser = allChatsForThisUser; } public List<ChatView> getChats(){ return allChatsForThisUser; } public Chat getCurrentChat() { return currentChat; } public String getCurrentUser() { return currentUser; } public String getOtherUser() { return otherUser; } } This is a simple POJO. The only interesting parts are “extends View” which we discussed before, and the first line of the constructor. Here, we tell the superclass the name of the template which we wish to compile, in our case chat.mustache. Here’s the full template: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="/assets/css/skeleton.css"/> <link rel="stylesheet" href="/assets/css/main.css"/> </head> <body> <div class="top"> <div class="user">Logged in as {{currentUser}}</div> </div> <div class="container"> <row> <div class = "three columns"> <h1>Chats</h1> <ul> {{#chats}}<li><a href="/chat/{{userOne}}/{{userTwo}}">{{userTwo}}</a></li>{{/chats}} </ul> </div> <div class = "nine columns"> {{#currentChat}} <h1>Chat between {{currentUser}} and {{otherUser}}</h1> {{#chat}} {{.}}<br/> {{/chat}} <br> <form method="post" action="/chat/{{currentUser}}/{{otherUser}}"> <textarea name="message"></textarea> <br/><button>Submit</button> </form> {{/currentChat}} </div> </row> </div> </body> </html> The only new syntax can be seen here: {{#chat}} {{.}}<br/> {{/chat}} Using #chat allows us to loop through all of the objects in the field “chat”. The {{.}} syntax is simply for using “this”; if instead of a String we had a complex object we could just call the fields on that object here. @Path("/chat/{userOne}/{userTwo}") @Produces({MediaType.TEXT_HTML}) public class ChatResource { @GET public ChatroomView chatBetween(@PathParam("userOne") final Optional<String> userOne, @PathParam("userTwo") final Optional<String> userTwo) { By modifying the return type in our ChatroomResource to be our new view, our mustache template is correctly rendered. I had to refactor the code somewhat to get everything working. I’d originally allowed the userOne/userTwo of the chat object to be in any order which reeked havok on the views. As a result, I created a ChatView object which represents each chat from the perspective of the “logged in” user. And for My Next Trick Hopefully, you were screaming “but what about the REST API? You’ve just killed it in favour of your view!” I was certainly concerned, until I discovered a lovely little trick in Dropwizard. It is possible to specify more than one type in the “produces” field. In this case the default is HTML, but if the client specifies an accept header of JSON then Dropwizard will use Jackson to serialise the view. We can have a single API point return HTML or JSON depending on the clients wish! This is so cool. @Path("/chat/{userOne}/{userTwo}") @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) public class ChatResource { Here’s a picture of the call from postman, the exact same URL, just with the JSON request header. At the moment, the result isn’t great (the chat’s returned twice!) but that can be easily optomized. Thoughts and Concerns I must admit that overall I’ve been quite impressed so far. It’s been pretty quick to get going to build an application and for the most part it has all kind of “just worked”. However, I have struggled with poor documentation on this part. Dropwizard refers to the Mustache Java docs, which are really pretty poor at this juncture. There’s literally nothing on the Dropwizard additions to mustache; this makes it near impossible to figure out how to do some of the deeper integrations in the Mustache Java documentation in Dropwizard because it’s been abastracted away. On a simple app like this it’s not been too much of an issue but it would make me nervous going into a bigger application. However, there’s literally nothing tying you to the Dropwizard version. I could easily just use the standard library if it were to become a big problem. Next up for the application is login and persistance. After this, it’ll be a fully functional chat application; it still does full page refresh for each message which isn’t ideal but that’s certainly something to improve. You can view the full code at. Please leave comments in the box, and follow me on Twitter @SambaHK for updates and whimsy. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/dropwizard-from-the-start-part-ii-building-a-ui-us
CC-MAIN-2020-29
refinedweb
1,276
61.87
From: Beman Dawes (bdawes_at_[hidden]) Date: 2002-12-01 20:18:42 At 04:36 PM 12/1/2002, Aleksey Gurtovoy wrote: >Beman Dawes wrote: >> Hum... I'll take your word for it, but to tell the truth I >> have trouble understanding what either ``this->member_name'' >> or `BaseClass::member_name'' adds. > >It makes 'member_name' identifier a dependent name (14.6.2, [temp.dep]), >thus deferring its resolution to the point of instantiation. That was the point I was missing. Thanks to you and Dave for the clarification. I'll read Dave's posting carefully in the morning when my brain is more active. > >> And the format library case >> wasn't a member name at all, it was an enum name, IIRC. > >Looking at the errors that triggered the discussion, they don't seem to be >related to two-phase name lookup at all: > > namespace boost { > namespace io { > enum format_error_bits { bad_format_string_bit = 1, > too_few_args_bit = 2, too_many_args_bit = 4, > out_of_range_bit = 8, > all_error_bits = 255, no_error_bits=0 }; > } // namespace io > > // ... > > template< class Ch, class Tr> > basic_format<Ch,Tr>& basic_format<Ch,Tr> ::clear_bind(int argN) > // cancel the binding of ONE argument, and clear() > { > // .... > if( exceptions() & out_of_range_bit ) > ^^^^^^^^^^^^^^^^ > .... > > } // namespace boost > >'out_of_range_bit' is defined in the namespace 'io', and there is no way it >can be found through a plain 'out_of_range_bit' (not >'io::out_of_range_bit'), two-phase name lookup or not :). That was what I thought, too, yet other compilers seemed to be accepting the code, so I assumed it was also two-phase lookup related. Perhaps the other compilers weren't actual instantiating that code. Anyhow, Samuel has added the io:: qualification and Metrowerks is now passing the tests, and I and other readers have learned a bit more about two-phase lookup. Thanks, --Beman Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2002/12/40545.php
CC-MAIN-2019-22
refinedweb
305
65.52
<Blog x: For the last week I was back in WinForms land... There is nothing making you appreciate the new stuff in WPF more than living without it for a week!!! Let me start by giving you some background... I had to make a fairly simple data logger for a client... the only problem is that I only had WinForms to use... I constantly found myself wondering why the hell thy don't have a content model!!! So, what is this content model and why should I care? In WinForms you have a button... very simple control with a specific purpose... Allow people to press it and perform a action based on this click! As you would expect, the button has a text property. This represents the text on the buttons face... Ok, now I need a picture inside the button... Ok, so lets add a image property... That will work... but what if I need to add a circle to this button... or even better, another button (To create a split button)... now the wheels start coming off!!! Yes, some of this is possible in WinForms, but it just feels like a afterthought! WPF is designed with this type of scenarios in mind! This is were the content model start coming in... Any control derived from ContentControl has a property called Content. Content is of the type object which implies that the content can be of any type... This is huge... You can potentially place anything inside a ContentControl! So, lets look at a few examples, lets create a button <Button /> This just creates a very basic button, lets start slow: <Button Content="Hallo World!" /> As expected, this creates a button with a string inside "Hallo World!". We will come back to this example because their are more underneath the surface... Have a look at the following button <Button> Hallo World </Button> Ok, so this creates exactly the same results as the previous button! What can we deduct from this? We added the content here as if it was the child of the button... how does it know that it is content and not a child? The button's source code possible looks something like this: [ContentProperty("Content")] public class Button : ButtonBase { ... } Ok, so what's next... Let's try adding a visual element as my content <Button> <Ellipse Width="20" Height="20" Fill="Black" /> </Button> This is nice... now I can add shapes to my button... or can I? We have now hit one of the "limitations" of ContentControl... Content can only be a single object! This is easy to bypass... just add a panel and you object as children. Lets try adding 2 circles <Button> <StackPanel> <Ellipse Width="20" Height="20" Fill="Black" /> <Ellipse Width="20" Height="20" Fill="Black" /> </StackPanel> </Button> So now we can add endless objects inside a ContentControl... (Remember that this is not "free" and their is a performance hit if you add to many controls). Lets look at the string example again. We added a object of type string as my content... how did it know how to display it? We will look at the rules of how this gets resolved in more detail later... but for now, all I will say is that if it is not a visual element, then it calls the ToString() of this object to render it! Lets make it a little more complicated, here is my button <Button x: All I did is give my button a name... the next step will happen in the code behind... I created a very simple Person class public class Person { public string Name { get; set; } public string Surname { get; set; } } And then add the following in the Loaded event Person me = new Person() { Name = "Rudi", Surname = "Grobler" }; MyButton.Content = me; What will be displayed now? Same rules still apply... ToString() returned WpfApplication1.Person. Ok, lets override the ToString() public override string ToString() { return Name + " " + Surname; } Now my button shows "Rudi Grobler". Great, so if it is not a visual element, then it uses the ToString() of the object! For what ever reason, I want a circle in between the name and surname (Try this with WinForms?). <Button x: <Button.ContentTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}" /> <Ellipse Width="15" Height="15" Fill="Black" /> <TextBlock Text="{Binding Surname}" /> </StackPanel> </DataTemplate> </Button.ContentTemplate> </Button> WOW!!! Lets break this down... Now the ToString() gets ignored, why? DataTemplate!!! What is a DataTemplate? A data template is a piece of UI that you'd like to apply to a arbitrary .NET object when it is rendered. Ok, what have we learned about the ContentControl so far? 1) If the ContentControl has a DataTemplate defined, use it 2) If the content is a visual element (derived from UIElement), render it using UIElement.OnRender()! 3) DataTemplate with matching DataType found (up the visual tree), use it 4) Use the objects ToString() ContentControl is amazing... So, what else does a ContentControl have? It has a property called HasContent... Why does it have a property called HasContent, if I can just as easily check by using Content == null? This is the WPF way... This allows easily checking for content from XAML... Now you can animate based on if a control has content, etc? What if my Content is a collection of .NET managed objects? Have a look at the ItemsControl... Dr WPF has a excellent series covering the ItemsControl in detail (or has he put it, from A to Z) ItemsControl - 'A' is for Abundance ItemsControl - 'B' is for Bet You Can't Find Them All ItemsControl - 'C' is for Collection ItemsControl- 'D' is for DataTemplate ItemsControl- 'P' is for Panel ItemsControl- 'I' is for Item Container ItemsControl- 'R' is for Rob has a Customer If you need to see the power of the content model, read 'R' is for rob has a Customer and check out the split button he created! You've been kicked (a good thing) - Trackback from DotNetKicks.com I agree the Content Model is simple beautiful Haven't delved into the WPF world yet, though I have played with Silverlight. This is an interesting look at some of the mechanisms involved, thanks. I believe you mean "Why WPF Rocks..." You're basically stating/asking why was the bicycle invented first when a car is vastly superior!?! think evolution and necessity Hi Brent, tnx for the english lesson :) ahura mazda, the idea is actually to highlight were WPF made huge improvements! Your Story is Submitted - Trackback from DotNetShoutout
http://dotnet.org.za/rudi/archive/2008/04/07/why-wpf-rock-the-content-model.aspx
crawl-002
refinedweb
1,086
75.81
Published: 6/3/2011 By: Xianzhong Zhu Contents [hide] 1 Introduction 2 Introduction to Regular Expressions 3 Create a Site Search Module 4 Establishing an Universal Search Entrance 5 Create a Search Results Page 5.1 Design the markup code 5.2 Behind code design 5.3 Write the extension method HighlightKeyword 6 Optimize the In-site Searching Module 6.1 Matching accuracy 6.2 User experience 6.3 Keywords filtering issue and URL routing 7 Summary In the last several parts of this series you leaned the backend and front-end modules of the Q&A sample application, as well as part of SEO related techniques under the ASP.NET 4.0 environment. In this part, we will shift out attention to delve into how to construct the internal searching module, what kinds of techniques you should have to accomplish such a module, and what kinds of SEO optimization actions should be taken. You will see we are going to resort to LINQ to Entities to execute the searching operation. And also, C# Regular Expression will play an important role in optimizing such a module and rendering user-friendly searching results. The sample test environments in this series involve: 1. Windows 7; 2. .NET 4.0; 3. Visual Studio 2010; 4. SQL Server 2008 Express Edition & SQL Server Management Studio Express. Regular expressions are used to find and match strings (of course, can also be used for substitution). Regular expressions provide a powerful, flexible, and efficient way to deal with text. Comprehensive pattern matching notation of regular expressions allows you to quickly analyze large amounts of text to find specific character patterns; extract, edit, replace, or delete text substrings; or add the extracted strings to the collection in order to generate a report. For many applications to deal with strings (such as HTML, log file analysis and HTTP header analysis), regular expressions are an indispensable tool. With the help of regular expressions, you can implement the following features: 1. Test the string model within a given string For example, you can test the input string to see if the phone number pattern or credit card number pattern occurs within a specified string. This is often called data validation. 2. Replace the text You can use a regular expression to identify the specific text in the document, completely remove it or replace it with other text. 3. Extract a substring from a string based on a matching pattern You can use regular expressions to find specific text within a document or an input field. In a certain sense Regular expressions constitutes a language. As a language, the regular expression has its own syntax and words (elements). When the language is integrated into C#, it shows more powerful features. C# provides the Regex class (defined in the namespace System.Text.RegularExpressions) to represent an immutable regular expression. The Regex class provides plenty of methods associated with regular expressions match, substitution, and verification. Due to space limit and delving into it will be far from our main topic, you can refer to MSDN and the famous regular expressions tutorial site to find out details. On the bases of the questions and answers modules established previously, let's now create an independent search module for the Q&A sample application. On the whole, the searching module consists of the following crucial areas and technical points: Note that the query method that is described in this article is still based on LINQ to Entities leveraged before. Next, we will first set up the fundamentals of the searching module, and then we will explore the related local optimization policies. Generally speaking, the search entry can be placed in a special page, or in a master page of the global Web site or even in a local module. In our case, we will build the search portal on the master page of the Q&A module. Now look at the search entry located inside the master page Site.Master. Figure 1 illustrates the design-time screenshot. Note our interested point currently concentrates upon the searching entrance at the upper right corner. As for another searching entrance at the lower part we'll delve into it in a future article particular at the buffering support and related optimization for the searching functionality. Below indicates the main markup code associated with the basic searching support inside the master page. For simplicity, we've not utilized tips to show more friendly prompt info at the textbox. In fact, there are numerous existing solutions for this; you can search it through Internet or implement your own. Let's next continue to look at the behind coding related to the button Button1. Here we use Server.UrlEncode to encode the content in the TextBox control txtKeyword. In this way, when passing it as the URL parameter we can achieve better compatibility while not have side effect upon the server URL resolve. The searching bar provides basic function, passing the searching parameter to the search result page leaving it to be responsible for related query and output, rather than do this within a PostBack request of the master page. Such a decision will result in the following advantages: Server.UrlEncode txtKeyword (1) Separation of logic Not implementing complex logic in such non-functional pages as the master page or search page will optimize logic, so that special pages do special things. (2) Easier access In the above code, directly jumping to the search results page and providing the "kw" parameter for URL can make the URL be directly and repeatedly visited. In this way, the user can bookmark this URL, so that the next time he can directly access the results list that complies with the same search conditions. Users can also spread the URL, so that other visitors directly access to the results list, without having to re-enter data to search. You will not enjoy this if you use the PostBack logic to make direct output. (3) Facilitate the migration and upgrade Passing the parameter independently is equivalent to building up an interface, so you can always pass parameters to the query module to achieve different query results. This is also a common practice in distributed systems - although the users access the same page from the same server the background processing server may be on another server, when this server can only accept a parameter and returns a corresponding result. Now that we've implemented the searching entrance and set up a way to passing parameters, it is time for us to create another new page to show the searching result. First of all, let's look at the key markup code associated with the page SearchResult.aspx (within the master page Site.Master), as follows. Here, a Repeater control is used to show all the questions related info. The most important part should be the HyperLink control embedded in the ItemTemplate template. As designed, we use URL routing technique to navigate the current user to the page Question.aspx that displays the detailed info associated with the current question. And also, we use the extension method HighlightKeyword to highlight the keyword in the question title. HighlightKeyword Next, let's go to look at the behind C# code. Here is the main code of the Page_Load event handler for the file SearchResult.aspx.cs. Page_Load The general logic above is not difficult to understand. First, use Page.RouteData.Values to obtain the passed keyword. Then, construct a complex LINQ to Entities statement to grab the question data that meet the specified conditions. As pointed out in the previous articles, such inquire solution may result in low efficiency. Cute readers can consider using stored procedures inside the database to improve the solution. At last, we bind the data to the Repeater control. That's all. Page.RouteData.Values In a more user-friendly search result page, it is better to highlight the user query keywords. As a simple approach, you can use the following way: However, there are two main disadvantages in this solution: Replace To overcome the above shortcomings, we'd better use the above-covered regular expressions. This is achieved in an extension method called HighlightKeyword in the public static class Common. Extension method is a new feature introduced since C# 3.0. The method HighlightKeywords above is just such one, as an extension method for the string type. For more details about extension method, please refer to MSDN; we'll omit the detailed introduction. HighlightKeywords As for the above method, we'll introduce a little more to let readers gain a better understanding: (1) string{0}</font></strong>". string{0}</font></strong Using this statement we define the highlighted string format. In this case, we make them red. {0} represents a placeholder of the keyword, to help to generate the complete regular expression related string. (2) string expr = @"(?<!{0})(?<kw>{0})"; string expr = @"(?<!{0})(?<kw>{0})"; This statement is used to define the regular expression string. The character @ can help to bypass some "\" related escapes, but not to omit the internal escape symbol inside a regular expression. {0} bears the same meaning as above. Using the above regular expression, two identical characters can not be close together. In addition, kw represents the name of the group (an important element associated with regular expressions). Up till now, a basic internal searching module has been finished. Till now, we've finished setting up a fundamental internal searching module. During the whole process of the implementation, some basic ideas have been shown in building up an in-site search module. However, some of the policies taken for now are now robust. The things mainly focus upon the several aspects below: As for the searching efficiency, we'll dwell upon it in the next caching topic in this series. Now, let's look at the rest points mentioned above. In the previous section, we've achieved the target of highlighting the keywords in the searching result page. It seems pretty beautiful, doesn't it? However, there are big loopholes in such simple regular expressions, one of which is matching accuracy. Next, let's consider a concrete example. For example, if the user is searching the keyword 'long', then he will find in the matched questions, such as "long long ago", multiple keywords close together will all be highlighted. This is not what the user wants. For the application, it is not wrong to highlight all keywords, such as "long", using the regular expressions. However, for the user, it seems that he just enters the keywords "long long". This case requires improving the wording of the regular expression to make the matched keywords discontinuous. To solve the above problem, you need to fall back on the atomic zero-width assertion in regular expressions. Table 1 shows the commonly-used atomic zero-width assertion symbols. Assertion Explanations Examples ^ Matches the position at the start of the searched string. If the m (multiline search) character is included with the flags, ^ m (multiline search) character is included with the flags, ^ also matches the position before \n or \r. \d{3}$ matches 3 numeric digits at the end of the searched string. \A Match must appear at the beginning of the string \Z Match must appear at the end of the string or before the newline \n at the end of the string \z Match must appear at the end of the string \G Match must appear in the place where the last match ends \b Matches a word boundary; that is, the position between a word and a space. er\b matches the "er" in "never" but not the "er" in "verb". \B Matches a word non-boundary. er\B matches the "er" in "verb" but not the "er" in "never". Let's now return to the above topic. We should modify the extension method HighlightKeyword in the file common.cs, like the following (note the bold part): Now, with the initial regular expression (?<kw>{0}) prefixed with (?<!{0}), the same contents close together will no more exist. (?<kw>{0}) (?<!{0 First, the character @ indicates that the string following it is a verbatim string. Note that the character @ only applies for constant string (for instance a file path). Second, a string starting with @ can span several lines, so that writing, in the .cs file, JavaScript or SQL script becomes more convenient. Refer to the following: @ Third, in the C# specification, the character @ can be used as the first character of an identifier (class name, variable name, method name, etc.) to allow a reserved keyword in C# as a custom identifier. Refer to the following: Note that although @ appears in the identifier, but it cannot be part of the identifier itself. Therefore, in the above example, we define a class named class, which contains a static method named static and a parameter called bool. In addition, with the symbol @ positioned before a string within a pair of double quotes some of the escape symbols can be omitted, as used in the extension method HighlightKeyword. HighlightKeyword As far as the user experience is concerned in the present searching module, there are still plenty of aspects to improve, such as: Of course, besides the above two points, there are still many areas required to improve. But since these two points are consistent with the general user's habits and representative, we'll only focus upon them and give corresponding solutions. 1. Keywords remaining Since when we implemented the searching function we used the method Response.Redirect() to jump to other page, as well as passing the related parameters, the ViewState cannot hold the entered keyword on the master page. The reason is during the course of the new GET request the textbox for the keyword in the master page will be cleared up. So, at this time, a same keyword requires to be passed to the master page and make the keyword related textbox visible, so that when the current user views the result page he can also see the keyword remain at the textbox. How can we achieve this effect? Response.Redirect() Generally, you use the following code, i.e. in the master page of the search results page via the FindControl() method, to locate the keyword input box related server control and set its Text property: FindControl() Text However, this method has a most significant drawback: strongly coupling the user control ID in the master page with the content page, which not only results in the efficiency issue but makes the ID attribute of the keyword entry box server control in the master page can not be easily changed, so that it is very detrimental to maintenance. To solve this problem, you can, in the master page, set the access level of the control txtKeyword to public: txtKeyword And also, in the content page use strong cast for Master to cast the Master type to the type of the current master page and to get from this type the target server control, and at last set the value of the server control's property: On the surface, this approach seems to be a good solution to overcome the drawbacks of using the FindControl() method. But, at the time of solving this problem, another new problem arises. That is, if specified in the page SearchResult.aspx another master page, you need to modify the type at all places where the same master page is referenced, which in turn has strengthened the coupling between the background .cs code and the front end. Another problem with this approach is to make the protected property of the txtKeyword server control changed to public itself is an unsafe practice, which makes txtKeyword accessible outside the Master page. So, how to achieve the targets of not only to meet the above requirements, but also to decouple the relationship between them? To overcome this knot, it is necessary to introduce a new thing, <% @ MasterType%>, and define a property for the master page. <% @ MasterType As the name implies, <% @ MasterType%> is the type of master page, set in an aspx page, and with the position same as <% @ Page%>, generally placed in front of the entire page. MasterType has a VirtualPath attribute, with which you can specify the type of master page. In actual use, however, you only need to specify the master page's address, the same setting as the MasterPageFile property of <% @ Page%>. <% @ MasterType%> <% @ Page MasterType VirtualPath MasterPageFile Here, we use <% @ MasterType%> in the page SearchResult.aspx to define the master page type: Thus, the type of Master in the page SearchResult.aspx is that of the file Site.Master, whose public methods can be easily visited. However, the "public" here is not the public of the control txtKeyword, but for it to create a new public accessor. In the Site.Master file add the following code: public In this way, we can from the page SearchResult.aspx visit the Keyword property of the file Site.Master and set it value. The related code is given below. Keyword Next, let's discuss another user experience related issue – keyword highlight. 2. Keywords highlight When the user from the search results page enters into the details page, if keyword highlighting feature can also be provided for the details page, this will help users to see key words within the shortest time to obtain the desired information. The highlighting feature for the details page is same as highlighting the keyword, decoding the keyword parameter of URL to obtain the initial keyword and then invoke the extension method HighlightKeyword to mark the specified contents. The detailed steps are shown below. (1) In the page Question.aspx.cs, add the property KeyWord: KeyWord (2) In the Page_Load event method add the following statement to set the KeyWord: (3) Before using the preceding Master.Keyword = KeyWord, as with the page SearchResult.aspx, you specify the master type for the page Question.aspx: Master.Keyword = KeyWord (4) Modify the method LoadInfo() called in the Page_Load event method of the page Question.aspx, so that the highlighting keywords can be applied to the specified area: LoadInfo() (5) Besides the question content and the best answer, if you also want to highlight the contents in other answers, then you can modify the code in the Repeater control in the page Question.aspx: Keyword filter in the search engine query is extremely important, because some important keywords may be involved in a database query and regular expression matching, which may affect the accuracy of inquiries or matching, so that application security and stability may be seriously affected. Take our internal search engine for the Q&A module as an example. If you enter special characters, such as "?", "/", "&", an HTTP 404 error will be thrown out by the system. In another word, URL routing does not allow such symbols as parameters passed to a URL. Now, let's look at our coding for the above case. In the file Site.Master.cs: According to MSDN, the UrlEncode() URL encoding ensures that all browsers will correctly transmit text in URL strings. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces might be truncated or corrupted by some browsers. As a result, these characters must be encoded in tags or in query strings where the strings can be re-sent by a browser in a request string.' That is, the first statement is valid and allowed in general code. But, as soon as the second statement is executed, the exception like that in Figure 2 will be thrown out. So, we can say, the ASP.NET 4.0 URL routing does not allow the above special characters as parameters passed into a URL. UrlEncode() In addition, such an ugly HTTP 404 Error page as given in Figure 2 is unfriendly. Readers can create your own special exception thrown page to handle the similar things in your real scenarios. Finally, in a real project, SQL inject is another serious issue to consider. Since this is beyond the range of this article, we'll no more detail into it. Well, till now, we've succeeded in building up a basic and still elementary in-site searching engine for the Q&A sample application. As you've seen, we've only implemented basic functionalities and provided limited optimization policies for the module. There are still more deserved to be researched into in a real project. In the next and the last article, we'll explore the possible buffering policy in constructing an internal search engine for the Q&A sample application.
http://dotnetslackers.com/articles/PrintArticle.aspx?ArticleId=634
CC-MAIN-2014-42
refinedweb
3,432
62.27
Reading A Text File Line By Line In Java With Example In this post, I am going to give you Java code snippet which will read a text file line by line. In this Java tutorial, I am going to use the BufferedReader Java class. It is going to be an easy tutorial. Reading a text file line by line using Java Programming language is quite easy. Below is the given code which will do the task: At first, suppose our text file is exampletextfile.txt. Below is the given code which will read this text file: package test; import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.io.FileReader; public class ReadTextFileLineByLine { public static void main(String[] args) { try { File file = new File("exampletextfile.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); stringBuffer.append("\n"); } fileReader.close(); System.out.println("Contents of file:"); System.out.println(stringBuffer.toString()); } catch (IOException e) { e.printStackTrace(); } } } In the above code will read the exampletextfile.txt file using FileReader. The BufferedReader read the file line by line and each line is appended as StringBuffer. It is followed by a linefeed. To test the code create a text file and add the path in this code. When you run the Java program, you will see the text appearing line by line as it is in the text file.
https://www.codespeedy.com/reading-a-text-file-line-by-line-in-java-with-example/
CC-MAIN-2020-24
refinedweb
246
59.9
[ ] Oleksandr Shevchenko commented on HADOOP-15725: ----------------------------------------------- Thank you [~stevel@apache.org] . {quote} 1. FS.deleteOnExist() Calls FileSystem.delete(), so has exactly the same permissions as the delete() call for that FS instance. {quote} In this case not exactly the same. Let me explain. When we call FileSystem.delete() we check permissions for a user who call delete() method. When we call FS.deleteOnExist() from user Alice we do not check Alice's permissions for this file. Later when we call FS.close() (or JVM is shutdown) by user Bob we call delete for all files in deleteOnExit list and check Bob's permissions for each file (but Alice marked this files for deletion). {quote} 2. therefore you cannot do more in deleteOnExit that you can from exactly the same FS instance through FileSystem.delete() {quote} It's a problem. We can do more that FileSystem.delete() call from another user if we marked files for deletion. I think it's not correct behavior: 1. Create FS behalf of user Bob. 2. Mark some file for delete behalf of user Alice (Alice do not have enough permissions to delete this file) 3. Close FS behalf of user Bob. 4. The file will be deleted behalf of user Bob. Correct me if I missed something. Or if something is not clear, please tell me and I will provide better clarification or some another example. > FileSystem.deleteOnExit should check user permissions > ----------------------------------------------------- > > Key: HADOOP-15725 > URL: > Project: Hadoop Common > Issue Type: Bug > Reporter: Oleksandr Shevchenko > Priority: Major > Labels: Security > Attachments: deleteOnExitReproduce > > > For now, we able to add any file to FileSystem deleteOnExit list. It leads to security problems. Some user (Intruder) can get file system instance which was created by another user (Owner) and mark any files to delete even if "Intruder" doesn't have any access to this files. Later when "Owner" invoke close method (or JVM is shut down since we have ShutdownHook which able to close all file systems) marked files will be deleted successfully since deleting was do behalf of "Owner" (or behalf of a user who ran a program). > I attached the patch [^deleteOnExitReproduce] which reproduces this possibility and also I able to reproduce it on a cluster with both Local and Distributed file systems: > {code:java} > public class Main { > public static void main(String[] args) throws Exception { > final FileSystem fs; > Configuration conf = new Configuration(); > conf.set("fs.default.name", "hdfs://node:9000"); > conf.set("fs.hdfs.impl", > org.apache.hadoop.hdfs.DistributedFileSystem.class.getName() > ); > fs = FileSystem.get(conf); > System.out.println(fs); > Path f = new Path("/user/root/testfile"); > System.out.println(f); > UserGroupInformation hive = UserGroupInformation.createRemoteUser("hive"); > hive.doAs((PrivilegedExceptionAction<Boolean>) () -> fs.deleteOnExit(f)); > fs.close(); > } > {code} > Result: > {noformat} > root@node:/# hadoop fs -put testfile /user/root > root@node:/# hadoop fs -chmod 700 /user/root/testfile > root@node:/# hadoop fs -ls /user/root > Found 1 items > -rw------- 1 root supergroup 0 2018-09-06 18:07 /user/root/testfile > root@node:/# java -jar testDeleteOther.jar > log4j:WARN No appenders could be found for logger (org.apache.hadoop.conf.Configuration.deprecation). > log4j:WARN Please initialize the log4j system properly. > log4j:WARN See for more info. > DFS[DFSClient[clientName=DFSClient_NONMAPREDUCE_309539034_1, ugi=root (auth:SIMPLE)]] > /user/root/testfile > [] > root@node:/# hadoop fs -ls /user/root > root@node:/# > {noformat} > We should add a check user permissions before mark a file to delete. > Could someone evaluate this? And if no one objects I would like to start working on this. > Thanks a lot for any comments. -- This message was sent by Atlassian JIRA (v7.6.3#76005) --------------------------------------------------------------------- To unsubscribe, e-mail: common-issues-unsubscribe@hadoop.apache.org For additional commands, e-mail: common-issues-help@hadoop.apache.org
http://mail-archives.apache.org/mod_mbox/hadoop-common-issues/201809.mbox/%3CJIRA.13183472.1536257748000.37711.1536586620235@Atlassian.JIRA%3E
CC-MAIN-2018-47
refinedweb
616
50.53
From my understanding of STL, list iterators are supposed to remain valid after a splice operation, however I seem to be getting a problem when I use an iterator to splice one object from list A to list B. The iterator seems to have been invalidated by the STL implementation. If I then try to use the same iterator to splice the object back from list B to list A, "bad things" happen (assertion fail on a debug build, worse on a release build). Here is a simple test case: #include <list> #include <assert.h> typedef std::list<int> IntList; extern "C" int main(int argc, char *argv[]) { IntList list1, list2; IntList::iterator iter = list1.insert(list1.end(), 42); list2.splice(list2.end(), list1, iter); list1.splice(list1.end(), list2, iter); assert(list1.size() == 1); assert(list2.empty()); assert(*(list1.begin()) == 42); return 0; } This code builds and appears to run fine using GCC, but not with Visual Studio 2008 (the second splice operation fails an internal assertion). Am I missing something fundamental here or is this a problem with VC++? Peter I am not sure, but I think the result of the second splice operation is undefined. According to the standard, the splice operation: Invalidates only the iterators and references to the spliced element So, I read that to mean that the first splice operation would invalidate the iterator (iter) , which you use in the second splice operation. I could be wrong ... I am not a language expert on these types of matters. I suspect you are correct, at least from what I can tell tracing through VC++'s STL list source. The problem is relatively easily fixed/worked around by reassigning the iterator to list2.end() and decrementing it after the first splice, but one line of code is usually preferable to three View Tag Cloud Forum Rules
http://forums.codeguru.com/showthread.php?492774-Are-std-list-iterators-broken-in-VC-2008
CC-MAIN-2014-35
refinedweb
310
63.8
I am trying to persist the data of my pods on GKE (like a docker volume). I came across two methods and I don’t know which is the go to method. using jcsFuse. using persistent volume and persistent volume claims. Which is the method thata will allow me to mount my pods to google cloud .. Category : google-kubernetes-engine I’m trying to set up a task in Airflow that creates a pod in Google Kubernetes from a Docker image in Registry. The task fails and returns: Pod Launching failed: Pod took too long to start Which does not say much. In a similar question, someone suggested adding a tag to the image version when .. Am bit confused with the terms Interoperability vs portability in container world. Containers are designed to be portable to run the application on any environment but then does it also solve the problem of interoperability? I guess, I do not understand what does interoperable really means but does the OCI specs solve the problem of .. I have a Kubernetes cluster. Inside my cluster is a Django application which needs to connect to my Kubernetes cluster on GKE. Upon my Django start up (inside my Dockerfile), I authenticate with Google Cloud by using: gcloud auth activate-service-account $GKE_SERVICE_ACCOUNT_NAME –key-file=$GOOGLE_APPLICATION_CREDENTIALS gcloud config set project $GKE_PROJECT_NAME gcloud container clusters get-credentials $GKE_CLUSTER_NAME –zone $GKE_ZONE I .. I am trying out to have a volume mount on Kubernetes. Currently I have a Docker image which I run like: docker run –mount type=bind,source="$(pwd)"<host_dir>,target=<docker_dir> container To have this run on Google Kubernetes cluster, I have: Create a Google Compute Disk Created a persistent volume which refers to the disk: kind: PersistentVolume … namespace: default .. I have deployed a pool of self hosted GitHub runners as pods to my kubernetes cluster. Some of our pipelines contain jobs which run container actions. Is it possible to run those jobs in this type of runner? Docker in Docker is configured in the deployment, and I can build docker images and push them .. I’m working on a machine learning application in python that will be contained in a docker on a kubernetes cluster. In this implementation I’ll be using Google Cloud Platform. A user will access the endpoint with a post command sending in the data they want to test against the model. The data could come in .. I build a go program which displays all the constraint violations running in the cluster. I build it as a image and run it as pod. But constraints which running in my cluster is violating my pod. Iam not able to create a pod. How can create a pod that displays the constraint violation without .. I need to create additional cluster in minikube. I searched for a while I haven’t got any resource on this.How to create a cluster in minikube? Source: Docker.. I build a image for a golang app which should all the constraint violations in the cluster. When I tried to run this Iam getting this error 2021/07/30 03:17:27 unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined 2021/07/30 03:17:27 err: unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined 2021/07/30 ..
https://dockerquestions.com/category/google-kubernetes-engine/page/2/
CC-MAIN-2021-43
refinedweb
555
63.8
java.lang.Object org.netlib.lapack.DLAEBZorg.netlib.lapack.DLAEBZ public class DLAEBZ DLAEBZ is a simplified interface to the JLAPACK routine dlaeb. * * Arguments * ========= * * IJOB (input) (input) (input) INTEGER * The dimension n of the tridiagonal matrix T. It must be at * least 1. * * MMAX (input) INTEGER * The maximum number of intervals. If more than MMAX intervals * are generated, then DLAEBZ will quit with INFO=MMAX+1. * * MINP (input) INTEGER * The initial number of intervals. It may not be greater than * MMAX. * * NBMIN (input) INTEGER * The smallest number of intervals that should be processed * using a vector loop. If zero, then only the scalar loop * will be used. * * ABSTOL (input) DOUBLE PRECISION * The minimum (absolute) width of an interval. When an * interval is narrower than ABSTOL, or than RELTOL times the * larger (in magnitude) endpoint, then it is considered to be * sufficiently small, i.e., converged. This must be at least * zero. * * RELTOL (input) (input) DOUBLE PRECISION * The minimum absolute value of a "pivot" in the Sturm * sequence loop. This *must* be at least max |e(j)**2| * * safe_min and at least safe_min, where safe_min is at least * the smallest number that can divide one without overflow. * * D (input) DOUBLE PRECISION array, dimension (N) * The diagonal elements of the tridiagonal matrix T. * * E (input) DOUBLE PRECISION array, dimension (N) * The offdiagonal elements of the tridiagonal matrix T in * positions 1 through N-1. E(N) is arbitrary. * * E2 (input) DOUBLE PRECISION array, dimension (N) * The squares of the offdiagonal elements of the tridiagonal * matrix T. E2(N) is ignored. * * NVAL (input/output) (input/output) (input/output) DOUBLE PRECISION array, dimension (MMAX) * If IJOB=1, ignored. * If IJOB=2, workspace. * If IJOB=3, then on input C(j) should be initialized to the * first search point in the binary search. * * MOUT (output) INTEGER * If IJOB=1, the number of eigenvalues in the intervals. * If IJOB=2 or 3, the number of intervals output. * If IJOB=3, MOUT will equal MINP. * * NAB (input/output) (workspace) DOUBLE PRECISION array, dimension (MMAX) * Workspace. * * IWORK (workspace) INTEGER array, dimension (MMAX) * Workspace. * * INFO (output) INTEGER * = 0: All intervals converged. * = 1--MMAX: The last INFO intervals did not converge. * = MMAX+1: More than MMAX intervals were generated. * *. * * ===================================================================== * * .. Parameters .. public DLAEBZ() public static void DLAEBZ(int ijob, int nitmax, int n, int mmax, int minp, int nbmin, double abstol, double reltol, double pivmin, double[] d, double[] e, double[] e2, int[] nval, double[][] ab, double[] c, intW mout, int[][] nab, double[] work, int[] iwork, intW info)
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/DLAEBZ.html
CC-MAIN-2017-51
refinedweb
416
50.33
Here's a summary of the current state of the Linux Driver coresubsystem, as of 2.6.23-rc8.If the information in here is incorrect, or anyone knows of anyoutstanding issues not listed here, please let me know.List of outstanding regressions from 2.6.22: - none known.List of outstanding regressions from older kernel versions: - none known.There are no currently open Driver core or sysfs bugs in bugzilla.Future patches that are currently in my quilt tree (as found at) for the Driver core subsystem are as follows. All of these will besubmitted for inclusion into 2.6.24, except as noted. The diffstat ofthese patches is included at the bottom of this message for those thatare interested. - HOWTO ja_JP updates - metric boatload of changes and tweaks to sysfs from Tejun. These clean up the internal usage and implementation of sysfs, and split sysfs from the kobject model a lot, fixing a lot of problems along the way. I can't thank him enough for this work. - cleaned up the usage of struct subsystem some more by removing some functions that are not needed, or only used by the driver core. Details on the api changes are below - cleaned up the usage of the kobject->name field and removed it entirely. This saves us some size on every kobject which really adds up on those s390 31 bit boxes with 20,000 different block devices. - uevent environment variable handling has been made simpler, and now hopefully, almost impossible to get wrong. Previously we were forcing every subsystem to open-code a lot of this logic. Thanks to Kay for this work. - global list of sysdev_drivers is removed, as no one was using it at all. - the number of legacy ptys can now be dynamically specified on the kernel command line, allowing people who refuse to fix their old applications to be able to still run on newer distros that want to limit this number at build time. - dmi sysfs code cleanups and fixes - block devices are moved from /sys/block to /sys/class/block. This patch has been hanging around for almost a year now, and hopefully we have worked out all of the kinks and userspace boot breakages. If anyone has any problems with this, please let me and Kay know about it. I'm hesitant to include it in 2.6.24 as it has recently changed and needs more testing. Maybe it will go into 2.6.25. Oh, udev has been able to handle this for over a year, so there should not be any problems with distros that are still supported. It can also be turned off with the CONFIG_SYSFS_DEPRECATED build option for older distros. - new debugfs functions for people who like hex numbers - platform devices now have the "platform:" alias added to their modalias to fix the recursive modprobe loops that Red Hat, OLPC, SuSE, and Debian have reported in the current code. - some struct class_device to struct device conversions were done for video and some various char drivers. More of these are on the way. - cdev kobject name cleanups. The kobject name of a cdev does not do anything, so it should not be set. - firmware collision fix between i2c and i2c-dev. - uevent files for bus and driver have been added. SuSE has shipped this for quite some time now. - if CONFIG_HOTPLUG is not enabled, some more space is saved in the uevent code. - the path to the uevent helper program (traditionally /sbin/hotplug) can be specified in the kernel config. This keeps the kernel from having to call a program that is not present 300+ times before init starts up, speeding up boot time in theory.New driver core api changes for 2.6.24: - debugfs_create_x8(), debugfs_create_x16(), and debugfs_create_x32() have been added - struct kobject.name field has been removed. Use kobject_set_name() and kobject_name() to set and get the name. - uevent callbacks in the driver core and for kobjects have been changed from: int (*uevent)(struct device *dev, char **envp, int num_envp, char *buffer, int buffer_size); to: int (*uevent)(struct device *dev, struct kobj_uevent_env *env); and struct kobj_uevent_env has been created to make it simpler to create environment variables for uevents. - struct platform_device.id has changed from an u32 to an int. - the following functions have been removed either entirely or from the global namespace: get_bus() put_bus() kset_set_kset_s() subsys_get() subsys_put() subsys_set_kset() subsystem_init() All documentation and in-kernel users have been cleaned up. There really wasn't many, if any users of these calls.No known at this time, changes to the sysfs userspace visable structurewill happen in 2.6.24.thanks,greg k-h----------------------------Diffstat of the current driver-2.6 quilt queue: Documentation/ja_JP/HOWTO | 84 - Documentation/kernel-parameters.txt | 4 Documentation/kobject.txt | 21 arch/i386/kernel/traps.c | 1 arch/ia64/sn/kernel/tiocx.c | 3 arch/powerpc/kernel/of_device.c | 37 arch/powerpc/kernel/vio.c | 16 arch/powerpc/platforms/ps3/system-bus.c | 9 arch/x86_64/kernel/traps.c | 1 block/bsg.c | 5 block/elevator.c | 2 block/genhd.c | 446 ++--- block/ll_rw_blk.c | 6 drivers/acpi/bus.c | 2 drivers/acpi/scan.c | 16 drivers/acpi/video.c | 4 drivers/amba/bus.c | 9 drivers/base/Kconfig | 8 drivers/base/base.h | 2 drivers/base/bus.c | 116 - drivers/base/class.c | 52 drivers/base/core.c | 124 - drivers/base/firmware_class.c | 14 drivers/base/memory.c | 3 drivers/base/platform.c | 28 drivers/base/power/power.h | 6 drivers/base/power/resume.c | 2 drivers/base/power/suspend.c | 2 drivers/base/sys.c | 73 drivers/block/aoe/aoeblk.c | 51 drivers/block/nbd.c | 15 drivers/char/Kconfig | 10 drivers/char/Makefile | 1 drivers/char/dsp56k.c | 4 drivers/char/ip2/ip2main.c | 12 drivers/char/ipmi/ipmi_devintf.c | 6 drivers/char/istallion.c | 8 drivers/char/lp.c | 5 drivers/char/nozomi.c | 2348 ++++++++++++++++++++++++++++ drivers/char/pcmcia/cm4000_cs.c | 5 drivers/char/pcmcia/cm4040_cs.c | 5 drivers/char/pty.c | 9 drivers/char/raw.c | 5 drivers/char/snsc.c | 3 drivers/char/stallion.c | 7 drivers/char/tipar.c | 6 drivers/char/viotape.c | 10 drivers/cpufreq/cpufreq.c | 2 drivers/edac/edac_mc_sysfs.c | 3 drivers/eisa/eisa-bus.c | 9 drivers/firewire/fw-device.c | 11 drivers/firmware/dmi-id.c | 60 drivers/i2c/i2c-core.c | 8 drivers/ide/ide-probe.c | 2 drivers/ide/ide.c | 15 drivers/ieee1394/nodemgr.c | 17 drivers/infiniband/core/sysfs.c | 9 drivers/input/input.c | 62 drivers/input/misc/pcspkr.c | 1 drivers/input/serio/serio.c | 11 drivers/md/dm.c | 2 drivers/md/md.c | 11 drivers/media/dvb/dvb-core/dvbdev.c | 5 drivers/media/video/pvrusb2/pvrusb2-sysfs.c | 4 drivers/misc/tifm_core.c | 9 drivers/mmc/core/bus.c | 11 drivers/net/ibmveth.c | 2 drivers/pci/hotplug.c | 28 drivers/pci/hotplug/pci_hotplug_core.c | 60 drivers/pci/hotplug/rpadlpar_sysfs.c | 6 drivers/pci/pci-driver.c | 3 drivers/pci/pci.h | 3 drivers/pci/setup-irq.c | 2 drivers/pcmcia/cs.c | 10 drivers/pcmcia/ds.c | 26 drivers/pcmcia/pxa2xx_mainstone.c | 2 drivers/pcmcia/pxa2xx_sharpsl.c | 2 drivers/power/power_supply.h | 3 drivers/power/power_supply_sysfs.c | 17 drivers/s390/cio/ccwgroup.c | 3 drivers/s390/cio/device.c | 25 drivers/s390/crypto/ap_bus.c | 14 drivers/scsi/scsi_sysfs.c | 9 drivers/spi/spi.c | 7 drivers/usb/core/devio.c | 6 drivers/usb/core/driver.c | 29 drivers/usb/core/message.c | 28 drivers/video/output.c | 29 drivers/w1/w1.c | 18 fs/block_dev.c | 8 fs/debugfs/file.c | 36 fs/dlm/lockspace.c | 2 fs/gfs2/locking/dlm/sysfs.c | 2 fs/gfs2/sys.c | 2 fs/ocfs2/cluster/masklog.c | 3 fs/partitions/check.c | 328 +-- fs/sysfs/bin.c | 30 fs/sysfs/dir.c | 806 ++------- fs/sysfs/file.c | 262 ++- fs/sysfs/group.c | 2 fs/sysfs/inode.c | 109 - fs/sysfs/mount.c | 18 fs/sysfs/symlink.c | 26 fs/sysfs/sysfs.h | 191 +- include/asm-powerpc/of_device.h | 2 include/linux/debugfs.h | 27 include/linux/device.h | 17 include/linux/genhd.h | 29 include/linux/init.h | 1 include/linux/kobject.h | 86 - include/linux/platform_device.h | 7 include/linux/sysfs.h | 168 -- include/linux/tty.h | 1 include/linux/video_output.h | 4 init/do_mounts.c | 108 - init/main.c | 9 lib/Makefile | 3 lib/kobject.c | 195 +- lib/kobject_uevent.c | 216 +- net/atm/atm_sysfs.c | 7 net/bridge/br_sysfs_br.c | 2 net/core/net-sysfs.c | 14 net/wireless/sysfs.c | 3 sound/aoa/soundbus/core.c | 33 124 files changed, 4226 insertions(+), 2721 deletions(-)-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/9/26/355
CC-MAIN-2014-10
refinedweb
1,471
57.03
Hi, I can't even get the first part right! After sourcing the SetPyRosettaEnvironment.sh script and starting ipython, I try: from rosetta import * I get: ImportError Traceback (most recent call last) /home/parcej/ in () /usr/local/PyRosetta-Release1.0-r33175.linux.32Bit/rosetta/__init__.py in () 12 warnings.filterwarnings("ignore", "to-Python converter for .+ already registered; second conversion method ignored.", RuntimeWarning, "^rosetta\\.") 13 ---> 14 import utility, core 15 16 import rosetta.utility /usr/local/PyRosetta-Release1.0-r33175.linux.32Bit/rosetta/utility/__init__.py in () ----> 1 from _rosetta_utility import * ImportError: libpython2.5.so.1.0: cannot open shared object file: No such file or directory Can anyone explain why I am an idiot aand getting this? cheers David Install Python 2.5. If you are using Ubuntu, or something similar, a quick dive into the Debian Package Manager will get you set up. Make sure that the defaults are set if your using something different. This should take care of the problem.....
https://www.rosettacommons.org/node/1761
CC-MAIN-2020-50
refinedweb
163
52.87
3.2. Converting a Jupyter notebook to other formats with nbconvert A Jupyter notebook is saved in a JSON text file. This file contains the entire contents of the notebook: text, code, and outputs. The matplotlib figures are encoded as base64 strings within the notebooks, resulting in standalone, but sometimes big, notebook files. JSON is a human-readable, text-based, open standard format that can represent structured data. Although derived from JavaScript, it is language independent. Its syntax bears some resemblance with Python dictionaries. JSON can be parsed in many languages including JavaScript and Python (using the jsonmodule in Python's standard library). nbconvert () is a tool that can convert notebooks to other formats: raw text, Markdown, HTML, LaTeX/PDF, and even slides with the reveal.js library. You will find more information about the different supported formats on the nbconvert documentation. One typically uses the nbformat () library to manipulate a notebook. However, in this recipe, we will see how to manipulate the contents of a notebook (which is just a plain text JSON file) directly with Python, and how to convert it to other formats with nbconvert. Getting ready You need to install pandoc, available at. This tool is used to convert markup files to various formats. On Ubuntu, type sudo apt-get install pandoc in a terminal. To convert a notebook to PDF, you need a LaTeX distribution, which you can download and install at. How to do it... 1. Let's download and open the test notebook. A notebook is just a plain text file (JSON): import io import requests url = ('' 'cookbook-2nd-data/blob/master/' 'test.ipynb?raw=true') contents = requests.get(url).text print(len(contents)) 3857 2. Here is an excerpt of the test.ipynb file: print(contents[:345] + '...' + contents[-33:]) { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# First chapter" ] }, { "cell_type": "markdown", "metadata": { "my_field": [ "value1", "2405" ] }, "source": [ "Let's write some *rich* **text** with [links]() and lists:\n", "\n", "* item1...rmat": 4, "nbformat_minor": 4 } 3. Now that we have loaded the notebook in a string, let's parse it with the json module as follows: import json nb = json.loads(contents) 4. Let's have a look at the keys in the notebook dictionary: print(nb.keys()) print('nbformat %d.%d' % (nb['nbformat'], nb['nbformat_minor'])) dict_keys(['cells', 'metadata', 'nbformat', 'nbformat_minor']) nbformat 4.4 5. Each cell has a type, optional metadata, some contents (text or code), possibly one or several outputs, and other information. Let's look at a Markdown cell and a code cell: nb['cells'][1] {'cell_type': 'markdown', 'metadata': {'my_field': ['value1', '2405']}, 'source': ["Let's write some *rich* **text** with [links]() and lists:\n", '\n', '* item1\n', '* item2\n', ' 1. subitem\n', ' 2. subitem\n', '* item3']} nb['cells'][2] {'cell_type': 'code', 'execution_count': 1, 'metadata': {}, 'outputs': [{'data': {'image/png': 'iVBOR...QmCC\n', 'text/plain': ['<matplotlib Figure at ...>']}, 'metadata': {}, 'output_type': 'display_data'}], 'source': ['import numpy as np\n', 'import matplotlib.pyplot as plt\n', '%matplotlib inline\n', 'plt.figure(figsize=(2,2));\n', "plt.imshow(np.random.rand(10,10), interpolation='none');\n", "plt.axis('off');\n", 'plt.tight_layout();']} 6. Once parsed, the notebook is represented as a Python dictionary. Manipulating it is therefore quite convenient in Python. Here, we count the number of Markdown and code cells as follows: cells = nb['cells'] nm = len([cell for cell in cells if cell['cell_type'] == 'markdown']) nc = len([cell for cell in cells if cell['cell_type'] == 'code']) print((f"There are {nm} Markdown cells and " f"{nc} code cells.")) There are 2 Markdown cells and 1 code cells. 7. Let's have a closer look at the image output of the cell with the matplotlib figure: cells[2]['outputs'][0]['data'] {'image/png': 'iVBOR...QmCC\n', 'text/plain': ['<matplotlib.figure.Figure at ...>']} In general, there can be zero, one, or multiple outputs. Additionally, each output can have multiple representations. Here, the matplotlib figure has a PNG representation (the base64-encoded image) and a text representation (the internal representation of the figure). 8. Now, we convert our text notebook to HTML using nbconvert: # We write the notebook to a file on disk. with open('test.ipynb', 'w') as f: f.write(contents) !jupyter nbconvert --to html test.ipynb [NbConvertApp] Converting notebook test.ipynb to html [NbConvertApp] Writing 253784 bytes to test.html 9. Let's display this document in an <iframe> (a small window showing an external HTML document within the notebook): from IPython.display import IFrame IFrame('test.html', 600, 200) 10. We can also convert the notebook to LaTeX and PDF. In order to specify the title and author of the document, we need to extend the default LaTeX template. First, we create a file called temp.tplx that extends the default article.tplx template provided by nbconvert. We specify the contents of the author and title blocks as follows: %%writefile temp.tplx ((*- extends 'article.tplx' -*)) ((* block author *)) \author{Cyrille Rossant} ((* endblock author *)) ((* block title *)) \title{My document} ((* endblock title *)) Writing temp.tplx 11. Then, we can run nbconvert by specifying our custom template as follows: %%bash jupyter nbconvert --to pdf --template temp test.ipynb [NbConvertApp] Converting notebook test.ipynb to pdf [NbConvertApp] Support files will be in test_files/ [NbConvertApp] Making directory test_files [NbConvertApp] Writing 16695 bytes to notebook.tex [NbConvertApp] Building PDF [NbConvertApp] Running xelatex 3 times: ['xelatex', 'notebook.tex'] [NbConvertApp] Running bibtex 1 time: ['bibtex', 'notebook'] [NbConvertApp] PDF successfully created [NbConvertApp] Writing 16147 bytes to test.pdf We used nbconvert to convert the notebook to LaTeX, and pdflatex (coming with our LaTeX distribution) to compile the LaTeX document to PDF. The following screenshot shows the PDF version of the notebook: How it works... As we have seen in this recipe, an .ipynb file contains a structured representation of the notebook. This JSON file can be easily parsed and manipulated in Python and other languages. However, it is better practice to use the nbformat package to manipulate a notebook. The internal JSON format may change, whereas the nbformat API is not expected to change. nbconvert is a tool for converting a notebook to another format. The conversion can be customized in several ways. Here, we extended an existing template using jinja2, a templating package (see). There's more... There is a free online service, nbviewer, that lets us render Jupyter notebooks in HTML dynamically in the cloud. The idea is that we provide to nbviewer a URL to a raw notebook (in JSON), and we get a rendered HTML output. The main page of nbviewer () contains a few examples. This service is maintained by the Jupyter developers and is hosted on Rackspace (). GitHub automatically renders Jupyter notebooks stored in repositories. binder, available at, allows one to turn a GitHub repository into a collection of interactive notebooks in the cloud. The service is free and the code is open source, so that anyone can provide their own binder service. Here are some more references: - Documentation of nbconvert, at - RISE, create interactive slideshows out of Jupyter notebooks, at
https://ipython-books.github.io/32-converting-a-jupyter-notebook-to-other-formats-with-nbconvert/
CC-MAIN-2019-09
refinedweb
1,159
58.79
Difference between revisions of "Control Systems Library for Python" Revision as of 19:19, 10 October: - 10 Oct 09: Release of control-0.1.tar.gz. Support block diagram algebra on SISO transfer functions plus Nyquist and Bode plots for state space and transfer function objects. Very rough. - 30 May 09: Test release of control-0.1.tar.gz just to see if the pieces are there Architecture notes The current plan for the library is to implement single input, single output (SISO) transfer functions based on the signal.lti class in scipy, but use a separate class structure for state space objects, which will support multi-input, multi-output (MIMO) systems. There are a couple of reasons for this choice: - The current LTI support in scipy only allows single input, multiple output systems. Hence it will not be possible to share any MIMO functionality with the signal library. Since there are very few uses of SIMO systems in controls, only SISO systems will be supported using the signal.lti object structure. - As a first cut, I plan to focus on state-space computations and so it makes sense to go ahead and put MIMO functionality here for now. At a later date, it may make sense to add MIMO transfer functions (creating a new class).. Also requires the main/unstable tree. - Install ipython - interactive python interface. For python 2.5, I had to use the main/unstable tree. Small snippet of code for testing if everything is installed from scipy import * from matlibplot import * a = zeros(1000) a[:100]=1 b = fft(a) plot(abs(b)) show() # Not needed if you use ipython -pylab python-control Standard python package installation: python setup.py install To see if things are working, you can run the script secord-matlab.py (using ipython -pylab). It should generate a step repsonse, Bode plot and Nyquist plot for a simple second order linear system.: 10 Oct 09: release 0.2 for people to play with - First cut implementation of transfer function operations, including composition and frequency domain plots - Working on state space representation, including conversion and mixed operations with transfer functions plus frequency domain plots. Only SISO operations for now, and things aren't very complete yet. RMM: 28 May 09: release 0.1 as a demo - Updated to build off of signal.lti object structure (allows easy step responses) - Put together an example + setup script, etc; available as control-0.1.tar.gz
https://murray.cds.caltech.edu/index.php?title=Control_Systems_Library_for_Python&diff=prev&oldid=10004
CC-MAIN-2022-33
refinedweb
410
56.25
ok so i am making an RPG game. I am in the process of rewriting the ENTIRE game using allegro and a simple tile set that i have made myself. but every time i as for help people always tell me one of two things with my program. 1:they tell me that i need to use structures for my inventory/banking system 2:they tell me to take the map arrays out of my program and put them in their own separate files I know more or less how to use a struct but i have no idea how to use it for the purpose that i want. People dont have to tell me that this is ugly I realize its a terrible god aweful way to make an inventory/banking system. but it was what i knew how to do.believe me i have worked on this for a very long time and I dont know how to change it to be more efficient. so could someone please help me out. i know most people hate it when people ask for exactly how to do it. but that is pretty much what im asking for at this point, but please explain it to me in great detail if you can. You can find the function that actually allows you to mine and get ore at: 1555you can find the inventory storing at: 801you can find the ore banking at: 5152 ok my computer is being extremely slow at the moment and wont upload my attachment so you can find it here on google sites: Thank you all for the help in advance. i really appreciate it. so i am working on the menu screen right now and this is what i have so far My first suggestion is to break your file apart. Don't EVER be afraid of splitting a single large file into smaller parts. It makes the individual parts easier to read. It lets you know when things are too tightly coupled (things that rely on each other "too much"). It helps you avoid distraction. My second suggestion: Instead of telling us the line numbers you need advice with, specify the name of the function you need help on. Line 1555: void Start_Mining()Line 801: void Items_List()Line 5152: (no method; just an if() block) My third suggestion: Within your Bank_Action() function, you have long if() blocks. Break those out into their own functions. I'd love to see this 3300-line function broken down to something a little more manageable: Now within Bank_Prompt_To_Deposit(), you have its own if() blocks: You'd do the same for all the rest of the stuff. Last of all, I'm not exactly sure what question you're asking. ...please explain it to me in great detail if you can... What did you want explained? I made a VR game! Something that would shorten your level select code would be a function pointer array. Then all you would need to do is index the array to run the function to select the level. Example : But what you really want is probably to load each level from a file. nvm, can. @OnlineCop Wow. yeah i did not think about that. It would take care of not knowing how to use structs. i would still have to use that big long ugly list everything out but it would be so much easier just to list it once in its own function. thanks a bunch. I think that two things will help this code: the use of struct or class, and replacing redundant code with functions. Many things can be simplified, like when you have text that is identical in all places except maybe the monster name or the amount of damage taken. One example is void Monster_1(): You can convert this into a simple function that you can reuse multiple times: As you can see, the text is almost the same for each battle, the logic is nearly the same, and you can simply pass in parameters to change the parts that should differ. Next, use of struct or class. For C++, they are identical except that the former makes everything public unless you specify otherwise, and the latter makes everything private unless you specify (respectively). Two perfect candidates for a struct are monsters and the player. This is the general structure of the Player. It doesn't contain any data (yet). It just specifies that anything that gets defined as a Player will have a Name, will have Health and Attack/Defence attributes, and so forth. You create an instance of the player (which will contain values for all the attributes) like: S_Player player; Now, you pass around the player and it's much easier to understand whether "Health" belongs to monster.Health or player.Health. If you're struggling to understand any of these, ask. Yeah I get both of those just fine and will for sure be adding them into my current remaking of the project. Someone along the line of that console based game told me that I should make the inventory into I think they said boolean structure. And I was like... what? And so I didn't implant that. I tried looking it up and stuff but I just could not wrap my mind around any way to take a structure such as tuna fish; and tuna.amount; and use that in my inventory system any different then how I am already using my inventory system.couldn't quite figure out how a boolean would go in there to make it different. So where I have those big long if statements where I list everysingle item in the game and repeat for every single item in the game.am I able to pass something like this: If(tuna + Items list <= BankSpace)store the item of so much amount; I'm on my phone at the moment because I couldn't sleep so I don't really remember how that one went exactly. But is that possible to pass all the items through a function like that in an if statement? so I don't have to type so much? Because that was by far the worst part of typing that code and why I stopped working on it where i did. Thanks a lot for all the help you guys. Yes, it's actually a good idea to pass things through functions for that reason. I suggest that you create an enumeration: Then you create an array: int All_Ores[Number_Of_Ores]; Now instead of keeping track of individual ores, you can specify exactly ONE array, index any of the individual ores whenever you want, and counting up the total ores is as simple as iterating over the array: int Total_Ore_Count = 0; for (int i = 0; i < Number_Of_Ores; i++) { Total_Ore_Count += All_Ores[i]; } cout << "You have " << Total_Ore_Count << " ores in your inventory."; You're also able to update only the ore you care about: All_Ores[Mithril_Ore] += 5; If you do that with all your other items as well (one for fish types, one for wood types), then you can get rid of that long if() block and condense it down to only a handful of lines. Thanks a bunch. i more or less get how to use enum but i think i could use that one. can i have an enum within an enum for example enum AllItems{enum AllOres{copper, tin, so on, number of ore};enum AllFish{Trout, tuna, so on, number of fish};number of total items};/////and also could you please help me figure this out?what i am doing is simply just getting the map to change by changing the Level X and Y value in the code itself. but when i change it like this:fromx and y = 0tox = 1y = 0 nothing happens. it still only displays the first map. but when i get rid of the else and have a double if statement then the opposite happens. only the second map is drawn to the screen. i am doing basically the same type of code i used for my character movement in the console to move between the maps. and will have a copy of the map arrays that is left blank except for the added in character and npc. this way i can manipulate on top of the drawn map without having to redraw it. and also the only way i know how to do collision detection. void LevelSelect(){ int LevelSelectArray LevelX; int LevelY; bool FirstTime = true; if(FirstTime) { LevelX = 0; LevelY = 0; FirstTime = false; } if(ArrayLevelSelect[LevelX][LevelY] = 1) { Level1(); } else if(ArrayLevelSelect[LevelX][LevelY] = 2) { Level2(); }}//for the example the only difference is the 5 and the 10void Level1(){ int Level[5][5] = { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 5, 1}, {1, 1, 1, 1, 1} }; memcpy(Map, Level, sizeof(Level));}void Level2(){ int Level[5][5] = { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 10, 1}, {1, 1, 1, 1, 1} }; memcpy(Map, Level, sizeof(Level));} Nope. Enums are not nest they are not nestable. but what if i did something like this? enum all ore{copper, number of ores} enum all fish{tuna, number of fish} enum all items{Number of ores, number of fish} You can probably do that. though the last enum may not be needed (I'm not sure of the purpose for that). Just note that each enum starts from 0 if you don't give it a starting value. The last enum is not needed: correct. HOWEVER, it just "happens" to be the total number of all the items in the enum, so you don't have to try to determine the enum's size at runtime (or remember all the places that you hardcoded the size) in case you need to add any more enum values. Logically, you want to separate your "fish" from your "ores". Wood doesn't feed you, so won't make sense to have inside of a massive enum or array that contains food-based items. In the same vein, weapons aren't armor. It makes a LOT more sense to me to have multiple for() loops, one after the other, than to have some massive array of "everything in the game". My mind just doesn't work like that. if(ArrayLevelSelect[LevelX][LevelY] = 1) You are assigning the value of 1 into ArrayLevelSelect[LevelX][LevelY] here. You probably meant == (equality). Next, onto the subject of your maps. I have always been of the mindset that all levels in a map should potentially be different sizes: the memory can be allocated when you need it, and freed when you're done with it. Some maps are the "interiors" of a large house, so they can be smaller. Other maps are vast oceans with a special hidden island right in the middle of them, and can be much larger. When you create a level, there should be a class that is specifically dedicated to all aspects of its generation and tear-down. You should pass in the level number you want loaded, and get a level back. You should pretend that you have NO idea what's going on "behind the curtain" when you request a level from it. This class might have the array in memory. It might load it in from a file. It might parse a Tiled-generated XML file. That's the point: it should be a mystery to everything else so you can change it at any time in the future, and as long as "give me level X" always returns a predictable map structure, how it works should always be a black box. Last of all, DON'T (did you see all the emphasis I put there?) create function calls for levels and things that "will come". Don't copy-and-paste 70 "placeholder" levels when you really only have about 7-8 truly defined. Don't do placeholder fish/wood/weapons/armor. Don't create "dummy" monsters that you'll revisit "someday". It might make you much less overwhelmed if you drop your file down from the nearly 10,000 lines to about 5,000. Strip away ALL pre-"defined" stuff: get rid of levels 9-70. Get rid of all enemies but two: the rat, and maybe the spider. Get rid of all types of fish. You can leave some of the fish/wood/monster "types" in comments somewhere so you remember them later, but get them out of your current codebase. Once you have all that, post your new source file results, and we'll move on to breaking them apart into individual files. Your Monsters should be in one or more files (either a massive monster.cpp file, or individual monster_rat.cpp/monster_spider.cpp files). Your Items should be in one or more files (items.cpp or item_wood.cpp/item_fish.cpp, etc.). Etcetera, etcetera. OnlineCop, while I agree that separating the item types could be more logical, its a lot more work to manage. Using a single item namespace allows for more efficient loading and saving as you don't have to figure out the category of the item first, and no item ids will ever overlap. I think that the superfluous enum in Tomasu view was this: enum all items{Number of ores, number of fish} The "last item in an enum is the one that enumerates the enum itself" is quite handy It is unlikely that Google shares your distaste for capitalism. - DerezoIf one had the eternity of time, one would do things later. - Johan Halmén I think that the superfluous enum in Tomasu view was this: Not only is it superfluous, it also won't work as intended, since it will give the number of ores as 0, the number of fish as 1, etc... Well in case it is strongly typed I guess ti would be only superfluous, but of course in this case......er now that I come to think of it, would it be even possible? The names should clash as multiple definition? (too rusty to remember ) Thomas, while I agree with this, I'm trying to work with his code on his programming level. If I were talking to LennyLen, Arthur or Trent, I'd be suggesting more advanced methods. I feel that these topics wouldn't be appropriate for where he's at now, so I'm doing my best to suggest things that will help him get this project far enough along that he can see some significant success. I honestly think throwing more code at the problem just makes it harder an item is an item, no matter the category. I think that is pretty darn simple Oh. wow. duh. haha == i know that. thats a silly mistake. ok so my maps work well now and i have loaded 2 in.I have also drawn in my player in a layer on top of the tilemap like this: 1 wall 2 grass 0 player 1111112221122211222111111 1111110221122211222111111 in the second array the only thing that gets drawn is the player and everything else is blank. i did this so the player can move freely ontop of the map without changing the map itself. so a couple of things. first of all, I know i am going to get crap for having all those huge arrays in my program itself. i get it. they should be in different files. and i am also seeing the result of it when the game is loading in the maps. it takes a minute. and this is only 2 maps! but i dont know how to use an array in a txt file like that. i have tried but i only know how to do simple variables and store them in an array using fstream. so if someone could help me out with that i would be grateful. and also, i am trying to figure out how to at this time make the player move. I am going for the same type of movement i have in my console game that i will repost. but i am pretty sure i will have to make the game redraw every time and i thought i had that working but it doesnt work so i will post my current project aswell and a final question comes when i create my inventory equipment and my incomplete date time thing. when you create them by pressing the "buttons" on the toolbar display it takes a couple of clicks before the new display shows up. and at line 373 of Game() i thought that would close the window. but for some reason it doesnt and i dont know why./////for the console game go to Line 1164 GameMechanics() to see how the player moves when down is pressed for the Allegro 5 game go to line 470 PlayerMovement() to see how i thought the player should move when down is pressed.just above there at 444 of Game() is where i draw the two tilemapsand PlayerMovement() is passed through Game() at line 321//////Thank you all so much for the help!
https://www.allegro.cc/forums/thread/614751/1006538
CC-MAIN-2018-05
refinedweb
2,883
78.08
PinchHandler QML Type Handler for pinch gestures. More... Properties - active : bool - activeScale : real - centroid : QtQuick::HandlerPoint - maximumRotation : real - maximumScale : real - minimumRotation : real - minimumScale : real - minimumTouchPoints : int - rotation : real - scale : real - translation : QVector2D - xAxis - xAxis.minimum : real - xAxis.maximum : real - xAxis.enabled : bool - yAxis - yAxis.minimum : real - yAxis.maximum : real - yAxis.enabled : bool Detailed Description PinchHandler is a handler that interprets a multi-finger gesture to interactively rotate, zoom, and drag an Item. Like other Input Handlers, by default it is fully functional, and manipulates its target, which is the Item within which it is declared. import QtQuick 2.12.12 Item { width: 640 height: 480 Rectangle { id: map color: "aqua" width: 400 height: 300 } PinchHandler { target: map } } A third way to use it is to set target to null and react to property changes in some other way: import QtQuick 2.12. The scale factor while the pinch gesture is being performed. It is 1.0 when the gesture begins, increases as the touchpoints are spread apart, and decreases as the touchpoints are brought together. If target is not null, its scale will be automatically multiplied by this value. Otherwise, bindings can be used to do arbitrary things with this value. The pinch begins when this number of fingers are pressed. Until then, PinchHandler tracks the positions of any pressed fingers, but if it's an insufficient number, it does not scale or rotate its target, and the active property will remain false. The scale factor that will automatically be set on the target if it is not null. Otherwise, bindings can be used to do arbitrary things with this value. While the pinch gesture is being performed, it is continuously multiplied by activeScale; after the gesture ends, it stays the same; and when the next pinch gesture begins, it begins to be multiplied by activeScale.
https://doc.qt.io/archives/qt-5.13/qml-qtquick-pinchhandler.html
CC-MAIN-2021-43
refinedweb
306
57.27
inet6_option_space() Determine how much space an IPv6 hop-by-hop or destination option requires Synopsis: #include <netinet/in.h> int inet6_option_space(int nbytes); Since: BlackBerry 10.0.0 Arguments: - nbytes - The size of the structure that defines the option. It includes any padding bytes at the beginning (the value y in the alignment term xn + y, the type byte), the length byte, and the option data. Description: This inet6_option_space() function returns the number of bytes required to hold an option when it's stored as ancillary data, including the cmsghdr structure at the beginning, and any padding at the end (to make its size a multiple of 8 bytes). When multiple options are stored in a single ancillary data object, this function overestimates the amount of space required by the size of N-1 cmsghdr structures, where N is the number of options to be stored in the object. This is of little consequence, since it's assumed that most hop-by-hop option and destination option headers carry only one option (see Appendix B of RFC 2460). Based on: - W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February 1998. Contains examples. - S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC 2460, December 1998. Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/i/inet6_option_space.html
CC-MAIN-2015-40
refinedweb
232
56.76
0 I want to connect the sensor max30100 to the Raspberry Pi board.I think everything is accurate.When I run the code, the red light flashes.I activated I2C.max30100 device address 0x57 is detected. When I put my hand on the sensor, I get the following error. Error: max30100 got exception [errno 121] remote i/o error I use the source code below. import os import sys import time import max30100 def main(): try: mx30 = max30100.MAX30100() mx30.set_mode(max30100.MODE_SPO2) # mx30.reset() # time.sleep(1) # mx30.startup() # time.sleep(1) i = 0 while i < 30: mx30.set_mode(max30100.MODE_HR) mx30.read_sensor() # # The latest values are now available via .ir and .red # print("HeartRate sensor .ir: {} and .red: {}".format(mx30.ir, mx30.red)) # time.sleep(2) mx30 = max30100.MAX30100() mx30.reinit() mx30.set_mode(max30100.MODE_SPO2) # time.sleep(1) mx30.read_sensor() # The latest values are now available via .ir and .red print("HRate sensor .ir: {} and SpO2 .red: {}".format(mx30.ir, mx30.red)) # temp = mx30.get_temperature() # print("Temperature {}\n".format(temp)) mx30.reset() time.sleep(1) i = i + 1 mx30.reset() # mx30.shutdown() except Exception as e: print("Max30100 got exception {}".format(e)) if __name__ == "__main__": main() connection PINS GPIO and sensor max30100 (3.3V -VIN) (I2C SDA1 - SDA) (I2C SCL1 - SCL) (PIN7 - INT ) (GND - GND) Can anyone help me to fix this issue? New contributor - (1) [errno 121] remote i/o error usually means the following: (a) data transmission error, because wires too long, speed too high, impedance overloaded (too many i2c devices on the same bus exceeding 400pF limit) (2) workarounds include (i) remove other devices to other I2C buses (for R4, you have many buses to use), (ii) lower speed to 50k or even 10k, to see if problem disappeared. (3) i2cdetect -y 1 only pings (read something, no guarantee can read-after-write), refactoring wiring, say star to daisy chain topology, to reduce capacitance, (4) Avoid interrupt in prelimin test. Cheers. – tlfong01 37 mins ago - One more trick to reduce overloading I2C bus: REMOVE ALL PULLUPs on the modules (Rpi I2C pins also have 1k8 strong pullup). – tlfong01 35 mins ago - PS – I am using the following references: (1) “MAX30100 Pulse Oximeter and Heart-Rate Sensor IC for Wearable Health datasheet- Maxim”: datasheets.maximintegrated.com/en/ds/MAX30100.pdf, (2) “AliExpress MAX30102 heart rate sensor / blood oxygen sensor MAX30100 heart rate sensor pulse oximeter – US$1.65”: fr.aliexpress.com/item/…, – tlfong01 25 mins ago - (3) “AliExpress OxyMeter Catalog”: aliexpress.com/popular/pulse-oximeter-sensor.html. (4) I am assuming you are using the Ref 2 cheap toy which is coronaVirus friendly. Please let me know otherwise:) – tlfong01 24 mins ago - If your are using whilemind/MAX30100u’s test_max30100.py, you can add debug print statement. Or you can try to read-after-write the ConfigReg at address 0x06. You can also try your luck on other python max30100 python/C libraries: (1) “mfitzp/max30100 – A Python lib for MAX30100 HR/Oximetry sensor”: github.com/mfitzp/max30100, (2) “kontakt/MAX30100 – Lib Maxim MAX30100 pulse oximetry chip”: github.com/kontakt/MAX30100, (3) “whilemind/MAX30100u – max30100 heart rate and oxygen sensor driver in python”: github.com/whilemind/MAX30100u. Good luck cheers. – tlfong01 1 min ago Edit .END Categories: Uncategorized
https://tlfong01.blog/2020/05/01/max30100-notes/
CC-MAIN-2020-40
refinedweb
542
67.55
Opened 10 years ago Closed 7 years ago #11421 closed New feature (fixed) Django should not silently ignore AttributeErrors raised in functions called by template Description Consider atemplate {{ obj.some_function }} where obj's some_function exists but raises an AttributeError because of a bug in the function's code. Django silently ignores the error and displays an empty string instead of a traceback, which could save much time when debugging. Probably this beahaviour is because Django returns silently if we call an attribute that does not exist. But ideally it should only fail silently if the function does not exist, not if it raises an AttributeError. Therefore Django should first check using getattr() if the function exists and THEN call it, and not catch AttributeError. Attachments (1) Change History (9) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by comment:3 Changed 10 years ago by comment:4 Changed 10 years ago by I created this patch based on 1.2 pre-alpha SVN-11617 Before this patch, inside _resolve_lookup(), it lump together AttributeErrors you get when doing getattr(current, bit) with AttributeErrors you get within current=current() when we in fact should treat them as two different errors. Django templates fail silently, by definition, on lookups that as in "it doesn't exist" but allows errors within propagate once found. The patch still doesn't solve the problem with TypeErrors. Next patch maybe or a separate ticket. comment:5 Changed 10 years ago by Changed 10 years ago by comment:6 Changed 8 years ago by comment:7 Changed 8 years ago by comment:8 Changed 7 years ago by This is fixed in trunk. Test 1 In a view, define: def foo(): raise AttributeError and put foo in the context. In a template, render: {{ foo }} With DEBUG = True you get the debug page. Test 2 In a view, define: class MyObj(object): def foo(self): raise AttributeError obj = MyObj() and put obj in the context. In a template, render: {{ obj.foo }} With DEBUG = True you get the debug page. Same applies for TypeError.
https://code.djangoproject.com/ticket/11421
CC-MAIN-2019-22
refinedweb
349
61.46
uFire_PAR_Sensor (community library) Summary Measure photosynthetically active radiation (PAR). An I2C sensor to measure PAR in μmol/m²/s. Example Build Testing Device OS Version: This table is generated from an automated build. Success only indicates that the code compiled successfully. Library Read Me This content is provided by the library maintainer and has not been validated or approved. Photosynthetically Active Radiation Sensor - Spectral range: 400~700nm - Accuracy: ±5% - Range: 0 - 2500 μmol/m²/s - Response time: < 1 second - Interface: I2C - Voltage range: 3.3 - 5 V What it is A PAR sensor in a waterproof aluminum enclosure with a 1.5m length of cable. The sensor comes pre-calibrated and doesn't require any subsequent recalibration. The device uses the Qwiic Connect System for wiring, it's an easy-to-use, polarized, push-to-fit connector. No more mistaken connections or soldering header pins. It comes with a small tripod and bubble level for easy deployment. and rust library is available for the Raspberry Pi. #include <uFire_PAR.h> uFire_PAR par; par.measurePAR(); Buy it Visit ufire.co and buy a board and probe. Browse Library Files
https://docs.particle.io/reference/device-os/libraries/u/uFire_PAR_Sensor/
CC-MAIN-2022-27
refinedweb
187
52.87
Few days ago I had a presentation in the Warsaw .NET Group about PDB files. To make the slideshow more attractive (or rather original:)) I decided to replace the PowerPoint with something more connected with the subject, such as… the Visual Studio debugger. The only question was how to actually achieve this. The idea grew in my head after reading a brilliant Mike Stall’s post about debugging dynamically generated code. Mike shows in it how to emit sequence points for a text file of your choice and so bind this file with the generated MSIL. If done correctly, the debugger will load the text file, allowing you to step through its content and at the same time execute the emitted MSIL. So what if we could use the presentation table of contents as our source file and for each title (line of the table of contents) emit MSIL which will present a corresponding slide in the console window? This will actually make the debugger play the role of the PowerPoint:) Prepare the content Let’s start from a table of contents for a hypothetical 3-slides presentation: Welcome 1. Slide1 1.1 Slide1.1 2. Slide2 Thank you Save this content as a toc.txt file – this will be our source file. Now let’s prepare slides. You may create a sub-directory slides or even create a separate directories for each group of slides – as you will shortly see there is no restriction here. In our case let’s stay with the one-directory-for-all approach. Let’s now assume that we want some contents to be presented for slides entitled: Welcome, 1.1 Slide1.1 ,2. Slide2 and Thank you (we omit 1. Slide1 by purpose). As mentioned previously the slides will be presented on the console so we may safely store their contents in text files named adequately: welcome.txt, slide1.1.txt and slide2.txt. Example content for a welcome.txt might be as follows: SAMPLE PRESENTATION =================== Sebastian Solnica Now we need to prepare a mapping file that will map the slide title with its corresponding content. Create a new text file and fill it with the following text: Welcome slides\welcome.txt 1.1 Slide1.1 slides\slide1.1.txt 2. Slide2 slides\slide2.txt Thank you thank-you.txt Each indented line stores a path to the content of the slide with the title above it. The titles must be the same as in the toc.txt file and the file paths must be valid (however as you can see not all titles need to be mapped). Create the presentation compiler Having the presentation content ready we now need to create an exe file that will be run by the debugger. I suppose that the easiest approach is to use classes from the System.Reflection.Emit namespace. The pseudo code for the compiler (or rather emitter) will be as follows: var asm = new DynamicAssembly() MakeDebuggable(asm) var mappingsContent = ReadFile(toc_slides.txt) var mappings = StoreMappingsInDictionary(mappingsContent) // slide title -> slide file for each slideTitle in GetContent(toc.txt) { if (mappings.Contains(slideTitle)) { EmitMsilCodeThatWillReadAndPrintTheSlide(mappings[slideTitle]); MarkSequencePoint(currentLineNum); // binds a line of the source code with the emitted MSIL } } SaveAssembly(asm) I will now explain few methods that occur in the code above that might have confused you (the C# source code that implements the above logic can be downloaded from here). MakeDebuggable is responsible for adding a DebuggableAttribute to the assembly. This attribute informs the JIT compiler that it should produce assembly code that will be debuggable (more here). To make the debugging process possible we also need to create a PDB file that will store the debug information for our module. ModuleBuilder contains a special method called DefineDocument that will do this for us. Here’s a C# code that implements all the logic described: Type daType = typeof(DebuggableAttribute); ConstructorInfo daCtor = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) }); CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] { DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default }); assemblyBuilder.SetCustomAttribute(daBuilder); ModuleBuilder module = assemblyBuilder.DefineDynamicModule(outputFileName, true); // <-- pass 'true' to track debug info. // Tell Emit about the source file that we want to associate this with. ISymbolDocumentWriter doc = module.DefineDocument(tableOfContentsPath, Guid.Empty, Guid.Empty, Guid.Empty); EmitMsilCodeThatWillReadAndPrintTheSlide emits MSIL that will open the slide file, read it at once and print the content to the console. Ildasm the code below and you will get it:) (or check emitReadAndPrintSlideMethod in Program.cs from the slide compiler source code): using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))) { Console.Clear(); Console.Write(reader.ReadToEnd()); } To make the assembly smaller you may consider putting this logic in a separate method and emit just calls to this method with adequate parameters (this is what I do in the sample code). For each slide printed we need to inform the debugger which line of the source code (or table of contents in our case:)) should be highlighted. For this purpose we use MarkSequencePoint method of the ILGenerator instance: ilGenerator.MarkSequencePoint(doc, currentLineNum, 1, currentLineNum, 100); To make the debugging even more feasible I emit System.Diagnostics.Debugger.Break() call after the first sequence point (so even when starting with F5 the debugger should stop on the first slide). Compile and show:) By now we should have the presentation compiler and the presentation content (table of contents, slide files and slide title <-> slide file mapping file) ready. So it’s time to compile it and debug it:) If you are using my compiler run the following in the command window: SlideCompiler.exe -files toc_slides.txt -o toc.exe toc.txt This should produce a toc.exe file (and toc.pdb) that you can now open in Visual Studio (File->Open->Project/Solution…). After pressing F5 you should see something like: By pressing F11 or F10 you may advance the slides. To move back just select the line before the slide you want to show, press Ctrl+Shift+F10 and then F10. You may also place breakpoints on your slides:) The code (and the sample presentation as well as my symbol presentation from WG.NET) can be found on my blog samples site. Have fun and surprise you listeners on your next presentation! 🙂 Sebastian, the presentation was great and the slide compiler rocks! 🙂 Thanks Michał 🙂 really nice:) Thanks 🙂 Make a slide show
https://lowleveldesign.org/2011/11/20/slideshow-in-debugger/
CC-MAIN-2020-40
refinedweb
1,061
56.35
open my project in MonoDevelop (MonoTouch project), select to stop on all exceptions except System.Threading.ThreadAbortException, but when I run the project it still stops on ThreadAbortExceptions. Which version of MonoDevelop is this? Do you have a test case? I'm not able to reproduce this in MonoDevelop 2.6RC2 (you can download RC1 from - running that should prompt to update to RC2 which wasn't pushed to the download site because RC2 is only available for Mac), but I might be (probably am) doing something wrong. I wrote up a simple test iPhone program which calls Thread.CurrentThread.Abort(). If MonoDevelop's Run -> Exceptions... -> "Stop on Exceptions" list includes ThreadAbortException, then MD stops on that ex, otherwise it doesn't and the app just goes down right after it launches. Try the other way - add every exception except ThreadAbortException and see if it stops - in my case it does. I will try it with RC2 and MonoTouch 4.1 and see if it still happens to me. Aha, yep, now I can reproduce. The problem is that System.Exception is the base exception type for all other exceptions, so if you add that type to the list of types to stop for, it will implicitly also stop for System.Threading.ThreadAbortException I suppose we should keep this open as a "feature request" to make this a little more obvious (don't feel bad, it wasn't immediately obvious to me either). Perhaps moving base exception types to the "stop on these exceptions" list should pull over all their subclasses as well? That might be enough to make things a little clearer and is the simplest solution I can think of. Is it not possible to exclude it if it really is a ThreadAbortException even though it's also a System.Exception? I mean... I might want to stop on other System.Exception exceptions, but not on a ThreadAbortException. I think there really needs to be check on the specific exception, and if you don't want to stop on that, don't stop. If I select to stop on "System.Exception" I personally wouldn't expect it to stop on ThreadAbordException, even though it's a subclass. Well, I can see why you'd expect it to work that way, because that's how VS works. And, as you say, there may be cases where you want to catch an exact exception type and not its subclasses. However, the way SDB does it has a couple of advantages - it's the way that C# "catch" works, and it allows you to catch exceptions when you don't know the exact subclass. Ideally we could find a way to support both, but that UI for that would be challenging... Sorry Michael - what's SDB? Not familiar with that and the acronym doesn't ring a bell. If the UI was a tree view, it could be done. Checking "System.Exception" would catch all below it (would automatically turn them on) but you can then selectively turn off individual types. Or conversly, you can turn on individual types. Thinking about it, I think that's how VS.Net does it. Sorry, I forgot the acronym wasn't well-known outside the Mono debugger/runtime community. SDB is the Mono Soft Debugger, which lives inside the Mono runtime. MonoDevelop send commands to it over TCP. I don't recall offhand whether the catchpoint requests that MD sends to SDB have an option for subclasses or not - if not, this request would require changes in the runtime. I checked VS, it has a treeview organized by namespace, not inheritance. But your suggestion makes more sense. We could also use a button to allow adding unknown exceptions by name, like VS has. Ah, on second thoughts, that's not true, we could eliminate it client-side like we do for conditional breakpoints - i.e. when it breaks, evaluate conditions, and if it doesn't satify the conditions, carry on without actually showing it in the UI. On that note, conditional catchpoints would be pretty neat, maybe the "add custom exception" button could add those instead of just adding an exception name? Oops, meant *implement* it client-side. Okay, this is starting to sound more doable. Maybe I can hold onto this bug after all. *** Bug 5565 has been marked as a duplicate of this bug. *** Tracking bug #15541. Fixed with 15541.
https://bugzilla.xamarin.com/20/204/bug.html
CC-MAIN-2021-25
refinedweb
738
74.49
. For information about plugins for testing plugin services, see the Plugins for Testing Plugin Services section of the MySQL Server Doxygen documentation, available at.: locking_service: A service that implements locks with three attributes: Lock namespace, lock name, and lock mode. This locking interface is accessible at two levels: 1) At the SQL level, as a set of user-defined functions that map onto calls to the service routines; 2) As a C language interface, callable as a plugin service from server plugins or user-defined functions. For more information, see The Locking Service._keyring: A service for keyring storage, accessible at two levels: 1) At the SQL level, as a set of user-defined functions that map onto calls to the service routines; 2) As a C language interface, callable as a plugin service from server plugins or user-defined functions. For more information, see The Keyring Service. mysql_password_policy: A service for password validation and strength checking. mysql_string: A service for string manipulation."); Some services for plugins may be provided by plugins and thus are available only if the service-providing plugin is loaded. Any MySQL component that uses such a service should check whether the service is available.})
https://dev.mysql.com/doc/extending-mysql/5.7/en/services-for-plugins.html
CC-MAIN-2021-10
refinedweb
199
51.89
Transcript of Remarks by Jim Allchin, Group Vice President, Platforms Professional Developers Conference 2003 Los Angeles, California October 27, 2003 JIM ALLCHIN: So what do you think of "Longhorn?" Huh? (Cheers, applause.) You want to know how to do some of that stuff? That's what my talk is about. And we're going to start with this eye chart. (Laughter.) This is going to be up on right after my talk. It's also going to be on MSDN. Now, during the next four days you're going to have an opportunity -- talking with some of the best architects -- to drill down in all the boxes on this slide, and there's more besides what I showed here. What I'm going to do is just focus on the four areas that Bill already mentioned. I'm going to talk about the fundamentals of "Avalon," "WinFS" and "Indigo," and we're going to do what I call a lap around "Longhorn" to get you sort of in the roadmap about all how those pieces fit together. And then during the rest of the conference you're going to be able to drill down into those. Now, if you have all this great functionality you need a way to be able to interface into it, and we call that WinFX TM . And what is WinFX? It. Actually, every time that a new extension is put into the system, it's reviewed by a set of system architects and then it's usability tested by a set of developers. We think we're doing a good job. We're going to be interested in what you provide to us as feedback about this. Of course, another thing that we wanted to do was increase the capability of what you're able to do in your code. And at least for me, the number of lines of code that I can write is about the same; actually in my case a little bit less than what I used to do. But in the last ten years, I don't think the productivity in terms of number of lines of code has really gone up that much. So what can you do about it? Well, I have a saying. The best line of code that you do is the one that you don't have to do. And what we're trying to do in WinFX is bring up that capability so things like add ref and release you don't have to think about, so you can make your code more resilient and write your code faster. Lastly, in this next step in WinFX, we're trying to continue on our commitment to compatibility. So if you have a Win32 bit app or you have a .NET Framework app and you want to start taking advantage of some of the extensions that we have in WinFX, you'll be able to do it in a fairly straight ahead way. Now, I believe in your bags you will have gotten this chart. This is the namespace chart. And I encourage you to study it because it will help you understand, especially using Visual Studio, but help you understand how the namespaces fit together from all the areas that I'm about to talk about. So now what I want to do is start the lap. In the fundamentals area, even though we didn't really show any of it in Hillel's demo -- he basically just showed a top-level view -- "Longhorn" is really about fundamentals as much as about any of the other areas that we're trying to move ahead. Today, it's still too easy for a driver to confuse other drivers or confuse the operating system, it's still too easy for applications to confuse other applications, and we're spending time trying to create more firewalls, more sandboxing between these applications and drivers so that you have a more resilient environment. So the big challenge today: deployment, huge challenge, huge. It's probably the number one I hear following security. And it's not just when you deploy your app, it's how you service your app after the fact through patching or whatever. And then there's this incredible growing security burden. It's not only in our code, it's in your code and it's not just looking at the code that's been done today, it's the new changes dealing with Digital Rights Management, because authors are going to want to get compensated as this new evolving world that everything moves to a digital form, they're going to want to be able to ensure that we're doing the right thing. We need people to be able to trust their computers and trust their content. Last, performance is a continual problem. Today we don't take advantage of the GPU, except in certain games, and just basically because of memory leaks and the like it's very easy to have a system that is running for a long period of time to degrade in performance. Those are some of the challenges that we're trying to address in "Longhorn." And how are we doing it? Well, I'm going to talk about each of those areas very quickly. In terms of deployment and servicing, we have a technology that we call "Click Once," and Click Once is the ability to just do an xcopy -- the equivalent of an xcopy -- to a machine, and you've installed it, very easy to get an app there, very easy to deinstall an app. No reboots: I'm on a campaign to get rid of reboots, not only in our code but in any of the code -- (applause) -- any of your code. So we have new servicing APIs that we're putting into the system to be able to tell applications you have a new set of capabilities that you need to integrate in and at the appropriate time you should shut down and take up -- shut down that part of your app and bring in the new piece. This is also true of the operating system. We've made a lot of progress in Windows XP and Windows 2003, but we need to do a lot more. And I could go on and on. Migration, going from one machine to another, today it's a weekend of work if you're at home. We'll have migration from machine to machine or migration that goes on the same machine, upgrades, it's the same code. And we're not talking about hours; we're going to get it down to where it's in the minutes range. We're not going to demonstrate that today but that's the progress, and I think it's actually in some of the bits that you'll be getting today. Reliability: I talked about it. Built into "Longhorn" will be essentially a flight data recorder. It's going to be able to trace, on all the time, and if your application has a problem, you'll be able to back up and see what happened, true for the operating system as well. Another area in here that I'm particularly excited about is driver verification. I really want us to take the next step and be able to put an analysis on a driver to ensure that the driver, before you even go through an operational mode of stress testing, you know that the thing is correct. I could go on about other improvements in that space. Performance: We have improvements going on in the paging system, something called "Super Fetch." Now, what's Super Fetch? Super Fetch is the idea that we can look at what's going on in a system and in a much smarter, semantic, heuristic way, determine what you're going to need again in the future. And Super Fetch is dramatic in terms of its performance improvements. We're adding a lot of code in "Longhorn" and we're going to be able to hold performance, once we work through all the other problems that we've got to work through by the time we ship it, we're going to hopefully hold about the performance we've got today by the fact that we'll have the capabilities such as Super Fetch. Glitch free: We want to be able to manage a media stream while other things are going on in the system. If you want to do some of the beautiful stuff you just saw, you need a glitch free environment, full GPU exploitation. The last area in fundamentals I wanted to mention is about security. And frankly, Bill brought up just some of the things that we're doing in SP2 in the near term. In "Longhorn," we're going much farther. We're going to basically soup to nuts [address security] from the entire lifecycle of when you're writing applications: When the system boots, starting, running, communicating securely, building and then staying secure. So we're spending a lot of time thinking about the fundamentals and going back and seeing what we can do to improve them. There are a couple I'll highlight here. You really need to be able to communicate effectively between nodes and between people, and do it in a secure fashion. We've spent a lot of time in the Web services area and with protocol specifications such as WS Security. We will continue to ensure that those capabilities are built into the system so you, as an application developer, you don't have to think about and worry about whether or not your communication is secure. Another area I wanted to highlight and Bill highlighted a little bit is the way we're trying to work with hardware in a deeper way. The NGSCB, this wonderful acronym that we have, used to be called "Palladium," we're working with the hardware vendors to be able to create a system so that we can boot and ensure that we're booting securely and that we can create shadowed memory where code can execute but you can't debug it. You can if you actually needed to debug it, but in the running case, the idea is that it's in a curtained memory, which means that it will be very, very hard to penetrate that. Another case in hardware, we're adding no execute capability to pages in the system. And by that I mean today's 32-bit processors, until recently, have not had any way in order to lock a page and say there's no execute here. And so with heap data it could always be corrupted; we'll have a solution to that with the no execute flag as we work with the hardware vendors. There's a lot that we're doing in this space. There's a lot of talk at this conference. I encourage you to go to those sessions and learn how you can write the most secure apps that you can. So next part of the lap, presentation. Now, today there's basically two models. There's the Windows app and then there's the Web app and both have great characteristics. If you want to have great interactivity, great performance, if you want to have offline capabilities, if you want to integrate in with things like the Start menu, a Windows app is the perfect thing to do. Of course, there are a few downsides to that. If you want to have a great Web app, there are great things that you can get out of that. You get, for example, text free flowing very easily, you get easy deployment and, of course, you can't put a Windows app in your browser favorites; in other words, it's designed in two separate worlds. What do we think people want? We think they want one world. And it's been a long path for us to get here, but we're incredibly excited that we think that we're on a path to solve these problems. Now, you saw some of the demonstrations that Hillel did. Those are some of the screen shots from that. What we're doing in "Avalon" is creating a unified presentation model for Windows apps, for Web apps and for media and animation type applications. This is a big step forward. We're going to take the best of both worlds and create one programming model that you can count on. Another huge innovation in "Avalon" is a vector-based compositioning engine. Now today, there isn't a single system for hardware drivers. There's a 2-D one and a 3-D one. In "Longhorn," there's just one, there's just one driver model that you can get access to, whether it be the text, media, any of the capabilities that you might have had to switch before. You get better performance, because you don't have to switch between the pipelines, between the 2-D and the 3-D. And this compositing engine works not just as you saw earlier, not just between an app with the alpha blending that you saw in the transparent Windows, not just an app in the operative system, but even between apps, because of this cross-process compositing engine. And it's vector-based. Any of you who have tried to play with a high density screen size in there, or becoming higher density, you'll know that if you did a bitmap-oriented font or bitmap-oriented icons and the like, it basically just doesn't work. So this is all vector-based, which, of course, is also faster. Another area where we're making a huge step forward in "Avalon," from our perspective, is native input for a variety of new input needs. You've seen Media Center -- very cool little guide with a remote control -- you can get native input into "Avalon" from the remote control. How about ink? One standard API for getting ink in. And even speech, you'll be able to have one interface into the system. Now, as you look across here in this diagram, you can see that we're going to let "Avalon" come in through documents UI or media, with a common form. And then, as you can see, it gets down to a direct 3-D graphic box that you can see there on your right. Now, the last innovation that we're doing, we think, is huge. It's moving to the declarative programming. Now, each time, through the ages, as we've moved from assembly language to C to VB, we've made steps up in the capability of what you can do. So the declarative of this is better in a variety of ways. And we are introducing a code name, "XAML," as part of our work in "Longhorn," and it's a new markup language that lets you have the ability to build a Windows app in a declarative way. And, of course, we all know that the declarative things are typically easier to read, learn and write. We also have the ability with this declarative language to separate the coding from the content. And to have some of the rich experiences that we all are used to now on the Web, you really have to have incredible designers in addition to incredible programmers. Today, it's sort of all mixed up together. And what XAML does is give us an ability to separate what's called "code behind" from the designers. And so, you can have collaboration between those designers and the developers. And, as I mentioned, it's very easy for tools to generate as well as consume declarative text. So on the screen, it shows you what a button would be in XAML. Now, the cool thing is that you can use any C OS language as well to generate that same button. So these three snippets of code generate the same type of button, a huge step forward. So with that, I want to get down a little bit more, the next level down in the system, and have Don Box and Chris Anderson, Windows architects, come out and do a little programming in "Avalon"." Chris, Don? CHRIS ANDERSON: Thanks, Jim. Hillel got to show you a great preview of what "Longhorn's" going to be like to use it, what it's going to be like for IT professionals and consumers. Well, Don and I, we get to show you what it's going to be like to develop it, what the code's going to look like. So, of course, everything starts in a console, right? (Applause.) All right, Don. Let's start a C# file. We're going to start coding our application in C#. (Laughter, applause.) Don -- Don, you use EMACs? DON BOX: Yes. All right. Remember, Chris, the premise here is we're walking up to a vanilla "Longhorn" box, we're looking at what's on everybody's box. I go to my mom's house, I want to hack. CHRIS ANDERSON: OK, so we're at your mom's house. DON BOX: And naturally, my mom, the only app she will have installed is EMAC. (Laughter.) CHRIS ANDERSON: So this is all I have to rely on. DON BOX: Wow. I don't want to be on your Christmas list. CHRIS ANDERSON: OK, so we start with some using statements. All the APIs, all the functionality you've seen in "Longhorn" today are exposed through a simple set of managed APIs. We're going to import the system namespace, the MS "Avalon" Windows, and Windowsdotcontrols namespace. We're going to create a namespace. I'm sure you guys are all pretty familiar; we're going to keep going here. Create a class -- we're going to derive this class from Windows. Windows is the base type for all the top-level frames in "Avalon"." There's already people critiquing your coding, Don. It's sad. DON BOX: There's already what? CHRIS ANDERSON: People critiquing you. So we're going to create a main -- (audience member, off mike) DON BOX: Ah, ah, I hear them. Hold on. CHRIS ANDERSON: Thank you. We have a solution. We have solved this technical problem. Good? (Applause.) CHRIS ANDERSON: Hold on -- I have one better. DON BOX: Watch this. Font, lock, mode -- CHRIS ANDERSON: Get rid of that nasty color-coding. DON BOX: Excellent. CHRIS ANDERSON: The contrast is really a local thing for me. People in the back, they don't want to see all that fancy color stuff, because they want to see true systems programming. OK, we have a main. Inside of our main we're going to create a new application. OK, new, My Window. We're going to create this. Now, this is actually instantiated in a class. The key thing to remember here is in "Longhorn," this isn't creating some wrapper that's underneath the covers calling create Window. This is actually instantiating the real code that is going to execute this app. We're going to set some properties -- text, invisible. Like our forefathers, we are making the default visibility of all Windows to be invisible. We're going to run -- and Don, I think I need to make you flash back to history. You remember COM -- DON BOX: Yes. CHRIS ANDERSON: OK, if you remember COM, I'd like you to put SPH right on the main, proving developer continuity on the platform. Yes, that's why we did it: developer continuity. DON BOX: Great. CHRIS ANDERSON: All right, so let's go to console. We're going to compile this now. We're going to invoke the C# compiler. Now remember, Don said this is only the software on his mom's machine. The C# compiler is now included in the default Windows client installation. (applause) CHRIS ANDERSON: Going to include a bunch of new DLLs, make it a Windows executable, and compile. DON BOX: Just a warning: don't be alarmed; it's fine. My mom's got these crazy environment variables on her box. I never know what she's doing. CHRIS ANDERSON: You've got to talk to her. DON BOX: Yeah. CHRIS ANDERSON: OK, let's run the app. DON BOX: This is it -- drum roll. CHRIS ANDERSON: OK, it's the first "Longhorn" application compiled at the PDC. You'll notice it is not gray. It is now white. That is our improvement. Hold on -- hold on. DON BOX: Oh, my goodness. Look at all the stuff you can do with this app. This is that "Avalon" thing you guys have been spending like three years on, right? CHRIS ANDERSON: Yeah, it's that "Avalon" -- yeah, thanks Don, thanks. DON BOX: All right. CHRIS ANDERSON: Just wait. All right, so that command line's not going to satisfy us for the rest of this conference, and we really need to make an improvement here. In "Longhorn," we're introducing a new build system, a unified build system that unifies Visual Studio, the platform, and the SDK with a single build format. It's included in the box. It will ship in every "Longhorn" machine. So, Don -- DON BOX: So my mom does not have to suffer the tedium of running this command line. CHRIS ANDERSON: Correct, yeah. It's another consumer -- a home feature. So let's create a project file. MS Build projects are, of course, XML-based. We're going to start with a project tag that consists of three main types of tags: properties, tasks and items. We're going to set some properties. Specifically, we want to have, you know, C# as our language, because we're not going to go change the code right now. We're going to say the target name, give it, you know, whatever random names Don feels like today. Vanilla, this is great. We'll do chocolate later, but we weren't quite ready for that. In our items, we're going to include all the C# projects -- all the C# files, rather. Excellent. Flight in -- very tough, very tough. Import -- so now, we need to get all the tasks. We have properties and items to find, and we're going to get all of our tasks from the Windows application dot target file, which is kind of the default for everyone. I think we're good. It looks great. Let's try for the console. Oh, we don't need that anymore. Instead, I type "MS Build" -- CHRIS ANDERSON: And what we've done is we've produced a lot more console output. We're trying to increase the amount of console output in this build. So, Don, let's run the next app. Well, actually, I could run it -- there's insects here. There's a bug in our demo already. Look at that. DON BOX: Oh! CHRIS ANDERSON: You know, as a hardcore EMACs user, there's something I've always wanted, which is that thing that you Visual Studio guys have -- what is it -- where you hit the F5 key. DON BOX: I love F5. CHRIS ANDERSON: I think I can get that. I think this is an enabling technology here. If I set this to Build, Run -- DON BOX: That's not going to work. CHRIS ANDERSON: That won't work? DON BOX: Try it. Let's see. CHRIS ANDERSON: I think it will work. DON BOX: We're trying -- you know, F5 and EMACs wasn't the top priority here, so -- CHRIS ANDERSON: This is the second "Longhorn" app of the conference. (Applause.) And oddly, it still looks like a boring white window. DON BOX: Yes. But wait until we add some more angle brackets. (Laughter.) CHRIS ANDERSON: OK, so -- all right. Jim talked about that great new declarative programming language, that higher level of distraction over, you know, the vanilla C# -- or, well, really Vanilla C# now. So what we'd like to do, I want to take that C# file and convert it into XAML. So, Don, maestro, if you would please: a new XAML file. So in XAML, the syntax is relatively straightforward. The root tag is the class you want to derive from. We're going to include the XML namespace, which, by the end of this conference, you will all have memorized. It is schemas.Microsoft.com2003XAML. We will repeat over and over again. We're going to include the definition namespace. This let's us do directives to the language compiler. So we're going to use that same class name in the same namespace as the code behind file -- excellent. So what we're really doing is we have two source files now that are going to generate -- we're defining the type, we're splitting the definition across two files. CHRIS ANDERSON: So that means down here, I have to go and say "correct." DON BOX: This is a new "Whidbey" feature, actually. CHRIS ANDERSON: Yes. DON BOX: Where you're able to have, in C# have multiple source files contribute to the same class. In this case, we're using a markup file as one of our sources. So let's move those property sets out of, you know, that rather old school C# and into the new revolution that is XAML. CHRIS ANDERSON: Let's move this code into the 21st century. DON BOX: Wow. CHRIS ANDERSON: You can't use semicolons in the 21st century? DON BOX: No, we don't need them anymore. We have angle brackets. CHRIS ANDERSON: Wow. (Laughter.) Great, all right. So the last thing we need to do, we need to tell the project system that we want to compile that. So let's go and open the project file, and we're going to say that we want to include, as pages, all the XAML files -- that's XAML, Don. CHRIS ANDERSON: Yeah. DON BOX: OK, so -- Web build? Did you change the -- is anyone going to know? CHRIS ANDERSON: No, no, no -- no one will know that it's XAML. Hold on -- don't look away, look away. DON BOX: That was not the third act. Wait for it. Go to the XAML file. Yes -- oh, this is going to be much better. This will be exciting. And we build and run. Hello, world, from XAML. (Laughter, applause.) What happens is as we ran the build system it took the XAML and it converted it into code and resources and it took the C# file and put those together as we compiled. Now, alas, that is still but a mere reflection of what we want. Will I ever come back to the source code or now am I like just XML-boy? CHRIS ANDERSON: Don, you've always been XML-boy. DON BOX: Yes. (Scattered cheer.) We have one other XML-boy in the audience. Excellent, excellent. (Laughter.) CHRIS ANDERSON: A true believer if ever there was one. DON BOX: Let's add some content. So create a closed window tag and inside of here we want to include a text box and some buttons. CHRIS ANDERSON: While I drink. CHRIS ANDERSON: We're going to set the width and height. You remember Jim talked about those high dpi monitors? In Windows, we're going to natively support physical measurements, inches, points, pixels. Don, your code is so clean. We run Office, it's beautiful. Don, you are a guru, and everyone can see our patented "jello" button effect as he clicks. Yes, you get that for free. But, Don, your app is sitting there, you're poking the app and it's not giving anything back. You're getting nothing back. It's not an interaction, it's not a dialogue between the software and the human. So, we want to add an event handler. So if you use ASP.NET, this should come as no surprise. We should also declare the event handlers in the markup. So, we're going to add an ID to the text box, and we can programmatically access it, and we're going to have a quick handler. Your names are poetic. I'm a code poet. Excellent, fabulous. So, we create our event handler object, and take the click event art, and we decided here we're just going to be a little mundane, we'll get to the exciting stuff in a moment. We're going to show a message box. The message box shows, and we're going to access Bob, Bob, text. The text box was a variable called Bob, and it has a property called text. Shall we, let's do it. So, we build, we run, we see a window. Type the text, we have interactivity, it's a message box, it will get better, don't worry. We have our code and markup separated. We're able to out of the box. The developer experience on the platform has a simple to program declarative markup. We have this new build system. But the next thing we want to get into is the app looks pitiful. Hillel is actually in the back crying, I can see him from here. So, let's go in and add a little more polish to this. We're going to put a text box. Jim talked about this unification of UI, documents, and media, and here you can see that we can put rich text right in the middle of our UI flow. In addition, all of "Avalon" supports a composeable layout model, so we're creating a text panel, and that's going to be laid out inside of the window. I'm able to embed really interesting text. See, we should have rehearsed more of the text Don was going to type. We're going to put that in, we're going to build, we're going to run. We see text. No we don't actually, I can barely see the text. They don't see the text. Well, I can see it down here. Let's make this a little bigger, let's make it so everyone can see it. "Longhorn" and "Avalon" has this great vector-based drawing system, and maybe when Jim was saying that you kind of said, 'So what, you know, vectors are all new fangled, they're for games, or whatever. I like my bitmaps.' But, alas, bit maps don't scale very well. So, in "Longhorn" we're moving to this composeable vector-based graphics system, and so we're just going to scale this up, right there. And that's going to just zoom the whole UI. Let's bring it up. We've failed. Gone. We've failed for the first time in front of this audience. DON BOX: Our code has failed, how about that. Would that be better? CHRIS ANDERSON: That would be much better. I think the compiler will also like that much better. But what we saw was compile time error checking. That was a feature demonstration. DON BOX: Did you see that build thing where they did the Behind the Technology? DON BOX: You know the characteristic parts of those videos, I think we can actually capture that in "Avalon," you have behind the technology. So, if I do this, I think that will get us to look more or less like those interview shots, like with Puff Daddy, P. Diddy, Sean Coombs. CHRIS ANDERSON: Excellent, much better. DON BOX: Does the text box still work? CHRIS ANDERSON: Of course it does. DON BOX: Don't try this at home. CHRIS ANDERSON: So, we've seen text, we've seen graphics, we've seen the rotation and the scale. But the last thing we talked about was media, the ability to integrate media into your application. DON BOX: There's no blinking lights yet. Which is a cool Altair inside thing with the blinking lights. CHRIS ANDERSON: Bingo. OK, but we want to do a little more modern version of the Altair. So what we want to do is, let's add a video into our application. So, in Hillel's demo, you saw how he was able to zoom into that video and it was really easy from a user standpoint. But how hard is that from a developer standpoint? If you tried this before, of course, you know that you need DirectX, and you probably need Windows Media Player, and implement maybe two or three hundred interfaces to try to host it. But here, we've gotten all that down to one single tag with a lot of attributes on it. So, we set the width, we set the height, tell it to stretch, and we repeat for a really long time, and we set the source. The last thing we're going to do, we're going to layer the video behind the text. We want to show a really great integration where they're seamless. So, we're going to have this canvas, and now we should be able to build and run. And let's see, what does the future hold? Clouds. (Applause.) DON BOX: Now that I have these new-found graphical skills, I right now feel like I should critique this the way many of us critique other artwork produced by Microsoft, I think it's a little harsh, a little Fisher Price, if you will, too much primary color, not enough subtlety. We need more pastels. CHRIS ANDERSON: OK, let's go for pastels. DON BOX: The future is not harsh and Lego-like, it's more pastels and friendly. CHRIS ANDERSON: So, in here what we're going to do is, we're going to set the opacity on the video, every element supports opacity. The entire "Avalon" composition system is built from the ground up with the ability to apply a transform, an opacity transform, effectively, to everything. In addition, every color reference, you remember the RGB, but it was always short of a quad, you always added that fourth bit. We found a use for that bit. And we've packed in alpha into that. So, every place you use a color, you can specify an opacity. DON BOX: Which is the left most thing. CHRIS ANDERSON: The left most. Let's go. Video, notice it's playing behind the text box. And it's stretching, and we can type, and the button actually works, all of this running at the video refresh frame rate doing real-time alpha composition. In the bits, this is running, by the way, in the directly on the video card. We've moved all of that processing directly onto the GPU, so it's consuming very few cycles. So, and this is also running on just the vanilla PDC bits. Eventually, at some point, who knows when, in the future, you'll actually be able to reproduce this exercise themselves. What we've seen is a great vector-based compiling engine with composition, media, UI and documents all running together that even Don can write a great looking application on, even you. With that, I think we should turn it back to Jim. DON BOX: We've gone way too long without a senior executive on the stage. CHRIS ANDERSON: We need a senior executive. IS there a senior executive in the house? Excellent. JIM ALLCHIN: As I said earlier, no tradeoffs. You can see even though these aren't some of our best graphic designers here, that you really don't have to have tradeoffs like you've had in the past. I want to move into storage, the next piece of our wraparound "Longhorn." Today, data is generally trapped inside the application. What's happened is the managed aspects of the data are often put, not only because there has to be a separate storage, but they are wired into the procedure code that's inside the application. What does this mean? Well, in some cases, it's not a big deal because you really don't need to export it. If you really want to export it and let other people take advantage of it, the fact is the schema isn't visible, meaning that other applications can't go and add interesting value to it. We also find that developers have to tool their own store all the time, because the file system today does stream. It does stream really well. But you might want to have very small items that you manipulate. So we find application developers creating their own stores to try to manage their particular data. We also find that relationships can often be buried, and if I say something like let's do a meeting, you know immediately that there's going to be an agenda, maybe not at Microsoft, but in most companies. But there's going to be and agenda, and you want to know when is the time of the meeting is going to be, and who it is going to be with, so you know all that. And so you want the systems to understand those links and be able to present them. So, if I say 'Bill Gates,' or 'William Gates,' you know that I'm talking about the same person. Systems could have better semantic knowledge to make those links very visible. And the last area that we think is a huge challenge, and you've already seen demonstrated how we're addressing it, is that if you want to have separate views today in the system, you have to create your own folders. If you have photos sorted by date, 2001, 2002, 2003, and you can work on it that way and it's great. But now let's suppose that you want to look at your photos based on perhaps a vacation that you went on, you have to go in and physically reorganize. There's no logical versus physical separation. On this screen, it shows little people, little funny people, representing that today contacts are sort of buried in a whole bunch of different places. When you put an author on a document, is that the same name space of contacts as in the Instant Messaging system? Is that the same one that's in e-mail? So we think that's a problem, because we think that if you have APIs that expose that and let you manipulate it, you could do a lot of cool things. So, what we're trying to do in "WinFS" is do a couple of things. First, schematize the data, and provide a great store that you could use if you decide to. They're really two separate concepts. We think that moving ahead in schema is going to be a great step whether that data is, in our case, in Active Directory or someplace else. And we also think that store will let you do very exciting applications. So we have an extensible XML schema. We have a set built into the system, things like people, user, infrastructure, and you can add extensibility into those XML schemas for those particular ones. For example, if you have a specific attribute that you want to add on to a user, then you could do that. You can also, you notice on the far right, that you can add your own huge new data type. So, your applications can install the schema, and then your applications take advantage of it. We have logical views, which gives you this separation between the physical and the logical views, so you can look at the data in lots of interesting ways. Programmatic relationship: again, you've already seen the things that we're doing in Hillel's demo, and the app where it let us look at the different data, the linkages between them, and you can program those so that you can surface them through a variety and number of applications. Synchronization is today extremely difficult, whether it's PC to PC or PC to a Web Service, or PC to a device, and so we spent a great deal of time. If you store your data in "WinFS," we'll be able to move it around in a consistent way between the devices without you having to do a significant amount of work. Lastly, when data changes today, you can get things like an "on change notify," you know something changed, but then you have to go grapple to figure out what in the world happened. There's something called Information Agent that will let you run specific pieces of code when things happen. If I get an e-mail from somebody that's really important, I could have an Information Agent rule that looks at that and says, ah, it's from such-and-such a person, I want to go ahead and send me an IM that goes to my phone. In terms of the general architecture, some of the things I want to highlight on this chart, and hopefully you can see this one, is that there's lots of different programming interfaces that you can come into "WinFS" with. You can come into it through objects, you can come into it through a SQL. You can come into it through an XML interface. There's a whole set of services being provided by the system, such as synchronization, I've already mentioned, an information agent, built in schemas, and then beneath it there's a data model that lets us build up these great schemas above it, things like items, relationships, and extensions. This is built on a transactive NTFS system, so the streams that you have in "WinFS" are actually stored in NTFS. Of course, "WinFS" itself is stored as a stream in NTFS. So there's a very good synergy between these. So with that I want to ask Chris and Don to continue on, and take us around the lap with "WinFS." CHRIS ANDERSON: Actually, Jim, I have this is my first PDC since joining the firm. And I sat up there all these years, and this is like my seventh of eighth PDC in my life, and I've always wondered why doesn't the executive write some code. And I think it would be nothing would please me more, I'd be honored if you wouldn't mind being my code monkey for this leg of the lap. JIM ALLCHIN: It depends, do you have like a good editor in here? CHRIS ANDERSON: Well, as you know, we have EMACs, if you were watching back stage, we have god's editor, I think. JIM ALLCHIN: How about VI? CHRIS ANDERSON: Let's see what we have. Why don't you bring up the editor of your choice. Windows is a big tent, we love everybody here, so you use what you want to use. We're going to edit vanilla.tf, which was the source file we were just working on. Now, you'll notice that, unlike EMACs, VI doesn't retain the font setting. And they want at least that, that's good. So you just told us about "WinFS", I'd like to see some "WinFS" coding. The first thing we're going to need to do is, why don't we talk about how people work. Right, we saw there's this unification of people in the store, why don't we bring up a contact ticket dialogue and see what that looks like. So replace my message box, which it looks like you've already done, and make yourself a contact ticker dialogue. So a contact ticker dialogue, give it a variable name, whatever you feel like, equals new contact ticker dialogue. Great. And we're going to need to set up properties so that the dialogue knows that we're looking for contacts explicitly. So why don't we go ahead and say dialogue that was a request property, request properties property request. JIM ALLCHIN: I think it's property request. CHRIS ANDERSON: Excellent, we agree, you lose. JIM ALLCHIN: I could be wrong. I just work here. CHRIS ANDERSON: Type what you will, we'll work it out. JIM ALLCHIN: The compiler will probably help with that. CHRIS ANDERSON: And we need to set the property type. Just because, the contact ticker has all that great functionality, you can select multiple items, you can say addresses, or e-mail names, or properties, anything. DON BOX: Chris, you're sugar coating it, it's a very verbose API that we have to code around. CHRIS ANDERSON: Contact properties dot contact, that I am certain in the fullness of time this line of code will become unnecessary. For now, this is a real bit, so we have to DON BOX: We know, it's a couple of words. CHRIS ANDERSON: Unlike "Avalon," where everything is perfect. JIM ALLCHIN: Guys, move on. DON BOX: So, Jim would you go ahead and show the dialogue, to do a show dialogue, which will do a modal dialogue on this sucker, pass your object reference there, compare to dialogue result dot OK. If and only if this works, what we want to do is grab the selected contacts, which is a property on the dialogue JIM ALLCHIN: Is that the thing you call BOB? DON BOX: Yes, the edit control is BOB, of course. We've been trying to teach Don Hungarian, but he just refuses to learn. CHRIS ANDERSON: Yes, I thought now that Charles isn't with the company anymore we could pick our own variable names. DON BOX: So, selected contacts zero, dot contact, dot display name, dot value, dot string, dot text. I'm sorry. I got a little carried away. That's looking pretty good, do we have enough close curlies there? JIM ALLCHIN: One more. DON BOX: I think you've got the exact right numbers. Now, hold on Jim, let me channel a much younger Don before I became enlightened, will you hit escape, colon, W. Is that it? JIM ALLCHIN: Yes. DON BOX: Sweet. JIM ALLCHIN: These young people. DON BOX: Can we go back to the shell? Now, I don't know if you noticed, what I did when I wrote the original make for the project file, I went ahead and put the build run in the target. So we now have F5 for both EMACs and VI. So if you want to just write MS build, and go ahead and click the button. DON BOX: Fantastic. So why don't we go ahead and find in contacts. These are real bits, remember that. I picked Mr. Anderson. Great, fantastic. OK, VI boy, let's see what else you can do with this thing. Let's see how this VI works with XML, a more modern syntax. So why don't you crank open the vanilla. So what we're going to do is add some more user interface goop at the bottom of this form. So after that go ahead and put in a line break, so that we get a visual CHRIS ANDERSON: Because we want to make it look better. DON BOX: We want to make it look better. Let's see, let's get a button and a list box. So, a button, we're going to have an event handler, which is going to be the button event handler is click equals whatever, search. CHRIS ANDERSON: Good name. JIM ALLCHIN: Like that? CHRIS ANDERSON: Yes, I like that. DON BOX: And close angle bracket. CHRIS ANDERSON: Yours are actually a little better than Don's, they actually have good variable names, you code a little better. You've been doing this longer. DON BOX: He's more experienced, he's more seasoned, as we say. JIM ALLCHIN: We call it old. DON BOX: And let's go ahead and drop a list box in here, and we're going to give it a programmatic variable, so capital ID equals the variable name of your choice. You're not going to say LB list, in honor of Charles. And you're going to need to make that a string with quotes. Result list, and you're going to get all visual fancy with this VI thing, fine, you go girlfriend, whatever you want. That's amazing. And why don't we put in a dummy item in there, so that it comes up looking fairly reasonable, because as it turns out if we don't, it's the size of the content, and we get a very tiny list box. Close that sucker out. Looking beautiful, close off the list box. What do you think of this XML stuff? JIM ALLCHIN: I don't think it's going to blow over. DON BOX: You don't think it's going to blow over? JIM ALLCHIN: I think it's here to stay. DON BOX: You think it's here to stay. I'll quote you on that one. CHRIS ANDERSON: That makes Don happy, we can keep him employed now. DON BOX: That was actually one of my review goals. CHRIS ANDERSON: That XAML looks as good as XAML can possibly look. Why don't we go ahead and go back to our source file, and DON BOX: Just give me a second. Did you overwrite our vanilla? CHRIS ANDERSON: No, I think it's just ul, again, the French spelling. So as I recall, in the button you declared an event handler called search, so would you mind writing a new event handler next to DON BOX: I think we should get that "WinFS" namespace in there, right? JIM ALLCHIN: I think so, too. DON BOX: So let me put something about storage, because that's not core enough for us. CHRIS ANDERSON: That is truly the core of the core. DON BOX: Uber core. CHRIS ANDERSON: We were going to have core.ex, but we decided we'll wait until next version. DON BOX: It didn't make the LAPI design timeline. CHRIS ANDERSON: So go ahead and write us an event handler search object, sender, click event DON BOX: Jim knows the guidelines, it's sender, E. CHRIS ANDERSON: OK. Great. And what we're going to do is issue a query. So there are some documents on this machine I'd like to see what we've got available. So to make a query in "WinFS," the most important thing we need is this thing called an item context, which is really a query scope. Because the query might take a few moments, just a few, let's clear out the list box so the users knows what's going on. And now we're going to declare an item context, C, and we're going to get it by saying item context dot open. So this is kind of the master control object from which we're going to issue all our queries. So now that we've got this, we're going to issue our careers are looking shorter and shorter. So when we issue the query, because we're in CLR land, where things are very productive and developer friendly, the query is going to return a collection. So we'll do a for-each, and we're going to get back documents. This is a strongly typed object, right? CHRIS ANDERSON: Yes, it is. DON BOX: So we've schematized all that common data stuff, all the everyday information. So we'll do a C dot find all, type of document, that's exactly the number of CHRIS ANDERSON: One more, I think one more will do it. DON BOX: I like that number. So let's get a block of code after. So for each one of these guys what we're going to do is create a new list box item, so we say result list dot item, dot add. There we go. And the title of the document will come from D, and there's a property called title, and we're cooking with gas there, you can close off another curly brace, and that VI is just an amazing tool. So why don't we go back to the shell and do a built. So there's our new button and our list box. JIM ALLCHIN: Should I push it? DON BOX: Again, it's thinking. JIM ALLCHIN: What do you think? DON BOX: Now, Jim I noticed that we got everything. In fact, we got so much everything we got two of everything, it was so happy to cough up these items. Is there anyway we can pare this down without going through like four loops, trimming these things out? I remember from SQL it was always better if you get the engine to do JIM ALLCHIN: Yes, in fact, this is about as inefficient as you can do it, because we're dragging everything we can, and then we could do a compare if we wanted to. Maybe we should just let the engine do the search. DON BOX: I would love to see us do that. I think we should let the engine do the search. CHRIS ANDERSON: So let's go to our find all, find all is overloaded, the first version that we used simply takes a type predicate, which says, 'Find all things in this store that are affiliated with this type, and the type we used was documents.' What we're going to do now is put in a predicate, which allows us to actually reason about, and express constraints against the schema of what is stored in the store. So the second parameter to find all is going to be a query string, and author's dot display name equals Mr. Anderson, looks good. And if you can put a comma right after type of document. JIM ALLCHIN: Of course. DON BOX: The dreaded line wrap. CHRIS ANDERSON: That insert JIM ALLCHIN: I did, I did. CHRIS ANDERSON: So that's looking as good as it can possibly look. Why don't we go back, save it out, go to the shell, dare we? Hit the search button, and I'll bet we get a few less files this time. JIM ALLCHIN: How about that? Great. (Applause.) CHRIS ANDERSON: Jim, before we move onto the next part, I don't know if you watched that video with the Halo stuff, with the red and blue and all that, one of the challenges of PDC is to get a vice president, even better a Group Vice President, such as yourself, to say developer 37 times. Would you please say developer 37 times? (Laughter.) JIM ALLCHIN: Developer 37 times. (Laughter, applause.) CHRIS ANDERSON: Thank you. JIM ALLCHIN: Oh, gosh, what can I say. OK, well on to the next part of the lap around, which is about communication. And I think we've made a bit step ahead in Web services. We've spent a lot of time working with the industry to come up with the protocols, but if you really want to have a Web service today, you're going to have to do a lot of work. It's a lot more just coding up some simple SOAP messages. You need security, you need to handle things like transactioning, guarantee that you can handle the resiliency and the recovery. You need to be able to handle the trust issues of security to cross boundaries between companies. You have a decision to make: Are you going to do objects? And there's some advantages there or there's some disadvantages. Are you going to do services? And there's some advantages and disadvantages there. How are you going to deal with the fact that you might want to do this little peer thing that you saw here but you also might want to do this cross-company or cross just your enterprise? So there's a lot of code you have to do if you want it to take place today. So what we're doing in "Indigo" is creating a subsystem that you can access that does everything for you. It starts by addressing the basics, so that you can do transacted messages in a reliable way, that you've got security built in it, you've got heterogeneous interoperability also built in it; the messaging capabilities, so that you can do just very, very simple things like send a message, or you can get down really low level and dirty and be able to play with exactly how the sequencing is to work. Now, there are programming models that extend the existing models that you are used to, whether it be what's available in COM+ or the like, so it naturally fits into all of those environments. And the bottom line is that this simplifies the building of services in a fairly dramatic way. And if you can see -- this picture of course is not quite as big from the architecture -- but from the top, we start off and we have facilities for you to create services so you don't have to do much thinking. You can either do a lot in declarative statements to let you build these services. If you go to the next level down in the architecture, there are connectors and channels for you to import for you to be able to fine-tune the way you want the system to operate. Finally, beneath that you have a variety of hosting environments that you can have these applications run in. You could have them run in a Web context, you could have them run as an NT service, you could have them run in DLL host in the COM+ world, so there's a lot of different ways that you can have your application and still be able to service the messages, and not handle all the issues that you typically would have to about scheduling threads and synchronization characteristics. So that's what "Indigo" is about. And, with that, I think I want to cover one more thing before I have these guys come back up here. We talk about "Indigo" for communications. There's also a collaboration piece that we put underneath the "Indigo" name. And today in the collaboration space, there are way too many contacts for you to deal with them if you want to have an RTC communication. It's just tremendously confusing. There's no single API for really doing the peer-to-peer or enterprise level environment that you want when you set up an app to do to real time. And today you can't get any of our UI to really integrate in with your application. Let's suppose you want to do a video call inside your application. There aren't any controls that we're making available for you. So that's a big problem. And then the problem of apps and firewalls, both enterprise and then with the home, block so much of communication that you are really stuck with some hard problems if you want to have a guaranteed, end-to-end real-time communications environment. So what we are trying to do in this space is create a single namespace and environment for contacts so that you can find the contact and you can get the presence -- presence meaning is the person there right now? And in "Longhorn," as you'll see in the bit, that there is a single concept of contacts that everyone is using, whether real-time or things like e-mail. We are adding controls so that you can get the capabilities for doing collaboration up into your app without you doing all the code, single platform, peer-to-peer and enterprise. And it's easy to traverse namespaces, even the peer-to-peer ones that are being dynamic. And if you move from a peer-to-peer into the enterprise, then that still works with the same APIs that would have worked on a simple code. And now -- now back to you, John and Chris. (Applause.) DON BOX: Thank you, Jim. (Applause.) So I've decided this time maybe I'd have someone a little less seasoned, who I could push around a little bit more. So Chris, would you mind coding? CHRIS ANDERSON: I'd love to. DON BOX: And I don't even want to think about what text editor you're going to use. So what we are going to do now is take our program, which is a fairly lonely program -- it's a program that just sits all by itself -- and what we are going to do is allow it to reach out to other programs that are running out in the world. So what I want to do is let's go ahead and do some blog work, right? So you know the PDC bloggers, .NET, everybody is into Web logs now. I know your simplegeek.com is becoming a cottage industry, generating three or four times your salary. CHRIS ANDERSON: Click through. DON BOX: Click through. CHRIS ANDERSON: Google click through. DON BOX: So why don't we go ahead and add some blogging capabilities using "Indigo" with this little program. So what we are going to do is, would you mind opening the XAML file, because we're going to have to set up a little bit of user interface? So what I'd like you to do is after -- or before actually -- I don't care where you put it -- I'm going to need three edit controls, so three text boxes and a button. So that looks like as good a place as any. So I'd like a text box -- ID equals -- we're going to put the title of our blog entry here. CHRIS ANDERSON: Title you said? Is that close enough to Hungarian? DON BOX: Yeah, good point. And do you want to make the width 100 percent? CHRIS ANDERSON: Yes, Don, you've been listening when I've been talking, haven't you. DON BOX: Did you just say something? What's interesting is that was actually spontaneous when I did that -- shocking. Yet it got no laughs. CHRIS ANDERSON: Don't try, don't try. So go ahead and mark up these variables. So we've got three variables. And you might want to put a little label there so that other users who come along -- DON BOX: Usability. CHRIS ANDERSON: Programs that other people use are often more useful than programs that only you use. DON BOX: Put a line break at the end. Oh, my goodness, where's your black beret in Macintosh? Great work on -- CHRIS ANDERSON: And we need a button. We need a button. DON BOX: A button? CHRIS ANDERSON: That will actually invoke the blogging code that we are going to write in "Indigo." So we have a button, invokes the blogging code. Fine, close off that tag. And go ahead and put a click handler in there. Blog it, then copy. So we've done all the XAML work, and now what we need to do is go over to our program and write some "Indigo" code. So the first thing we are going to do is get the event handler in place. And the event handler looks astonishingly similar to every other event handler. If anyone in the audience would like to help out, you can -- DON BOX: Great, we're auditioning later. CHRIS ANDERSON: And what we are going to do is bring in system.message box, which is the namespace for "Indigo," and we are going to take the three edit controls, bundle them into a data structure and send them over through a SOAP message to my blog. DON BOX: A data structure? CHRIS ANDERSON: We call those classes. Is that what you're -- DON BOX: Fine. So public class item, and I need three public fields of type string, title -- CHRIS ANDERSON: Wait, wait, title? I'm guessing, description? DON BOX: You are so good. CHRIS ANDERSON: Yes, content, fantastic. So we've got a data structure, also known as a class, that we are going to work with. We quickly marshal that off of the form into the -- DON BOX: Now, I really should be using data binding. There are some people backstage who are going to yell at me because I'm not. CHRIS ANDERSON: That's okay. DON BOX: There's great data binding -- I'm just letting you guys know. CHRIS ANDERSON: Yeah, yeah, plug away. DON BOX: My monitor has gone blank. That's not very fun. I.description equals the title. -- CHRIS ANDERSON: Actually it would be the description. DON BOX: The description.text. Thank you, Chris. CHRIS ANDERSON: It's harder to read when I have to look down at that -- DON BOX: Great. So while Chris fills this up, this thing we're going to do next, which is actually the important "Indigo" piece -- this was actually just a bunch of bootstrapping code so we could get our app to work. What we are going to do now is declare a port. A port is the central focal point in the API for "Indigo." A port is also a great kind of wine. DON BOX: And the port is the way messages come into and leave a given app domain. And so I've got my port set up. What I'm going to do now is create a channel. Actually, I'm going to do a port.open -- so P.open. CHRIS ANDERSON: I think we should also close it at some point. DON BOX: Yes, let's close it. CHRIS ANDERSON: Practicing good coding practices. DON BOX: Good for you. CHRIS ANDERSON: You taught me well. DON BOX: Yes, thanks. Yes. So what we are going to do now is create a channel. So "Indigo" is all about ports, which are these places in network place, and channels, which are these little IO devices we use to get messages into and out of a port. So we are going to need a send channel, and we're going to call "p.createsendchannel." And open-paren, new-URI -colon, HTTP colon, whack-whack,, whack team, whack ebox, whack Indiepost.asp. Cool. Close, close, close, semi-colon. And now we've got a channel. So we are ready. We are poised to get the message out to the server. CHRIS ANDERSON: I'm poised. DON BOX: Yes, you are poised. What we are going to do now is create a new message -- so we are going to create a message object, M equals new message. We are going to give it an action URI -- and get ready for this -- UUID, colon, 0002, 0812-0000-0000-C000-000000000046. CHRIS ANDERSON: So you made that up off the top of your head? DON BOX: No, my friends on the Excel team really wanted to see their name in lights. (Laughter.) So, go ahead and pass "I" as the body of the message. So we are basically creating an in-memory SOAP envelope. CHRIS ANDERSON: Did you pass "I" as the second parameter? Oh, that was just too fast for me. DON BOX: So we've got a channel, we've got a message. If only we could -- actually show me what you want to type. CHRIS ANDERSON: You know, I just want to introduce somebody. I really want that to be the code that I have to type. DON BOX: Yes, and of course this is real bits. This is not the final product. There is a grotesque line of code I need to type. I would like everyone to look down or away from the screen while Chris types this. (Laughter.) Look away. This will not be in the final product. It is a horrible hack, M-doting coding equals new system.text encoding. And by the way, this has got nothing to do with system.text. This has to do with the way our plumbing dispatches messages. And system.text.encoding.UTAF8, close paren, semi-colon. Do not do diddly-squat. Go to my blog, go to the shelf -- go to our -- no, no, not there. Get rid of that. What are you? Got to the shell that we've got. Please do a start,, and fine. So let's go take a look at my blog. This is just a blog which any of you folks in the room can -- CHRIS ANDERSON: You have a Sunday PDC post-world? DON BOX: This is the thing I blogged at 3:00 a.m. this morning, before I went to bed. And what I'd like to do is blog something new. So why don't you go ahead and build and run and our app. And this is builds, F5 for visual slick edit as well. That M is billed as very enabling. CHRIS ANDERSON: You know, I'm sorry, Don is -- or Jim has been sending me mail all day about this, and so I have got to fix it. So we -- DON BOX: Great. So Chris is going to tweak the UI a little bit. There we go. For "Indigo" we want things to look perfect. CHRIS ANDERSON: Yes, there we go. DON BOX: Great. So why don't you go ahead and exercise your creativity. You have wanton access to my blog. Please be gentle with her. "Chris is the best demo god in the world." Yeah. "I only wish I could be that cool." You're right, Chris, I do. Now, before you hit the button, moment of silence, a hush -- a hush falls across the room. Go ahead and hit it. I don't want to think about the number of moving parts in this demonstration -- across the Internet. While this button remains depressed a moment or two, it's sad -- oh, it came back. Why don't you go hit refresh on your Web browser? (Applause.) That was great, Chris. So we've seen a classic scenario where there's some service running on the Internet, we've got security built in, we're using "Indigo," we're doing the dance. I think "Indigo" is actually a lot more interesting than just talking to things that are Web sites. What I'd like to do now is to use that same technology to build some funky UI that will make me feel better about "Avalon." CHRIS ANDERSON: Excellent. I like to think you'd feel better about "Avalon." DON BOX: And, you know, I've noticed something about you. We've been spending time together recently, and I've noticed that you have tendencies which you're fighting -- (laughter) -- that you have been somewhat in denial for the past few years. And I think today is the day we come to terms. And it's often -- you know, you -- CHRIS ANDERSON: No, no, don't say it. They can't handle it. DON BOX: Yes. I think the next piece of code should be written using the language you really know in your heart of hearts you want to use, the language that you knew from the age of five you were attracted to, even though you couldn't explain it. (Laughter.) (Applause.) So what Chris is going to do is create a tile. A tile is one of those fancy gadgets over on the left-hand side of the shelf. And we have got a new tile project -- have you already created the project? CHRIS ANDERSON: It's done. DON BOX: Great. So we are going to create a tile project. What we are going to do is comment out the text of the tile, and you might want to bump up the font size. CHRIS ANDERSON: Hey, this is way better than those tech centers we've been using. There's Intellisense and save incompletions. DON BOX: There might be something there. CHRIS ANDERSON: There's something to this Visual Studio thing. DON BOX: There might be a future in this VS thing. (Applause.) And give it a variable. Great. OK, fine, be creative, whatever. Fantastic. Chop, chop, chop. Take me to the code. OK, fantastic. What we are going to do is write a service. We are going to write an "Indigo" service that runs inside this task bar. And to do that, we are going to write a new class inside of our class that we have got here already. We are going to bring up a system-up message box of course. CHRIS ANDERSON: I like system-up message. It's one of my new favorite namespaces. DON BOX: I know it is. So go ahead and declare a new class, so public class My Service. And it is going to inherit from synch message handler, which is a type-in message box. And, oh, wow, look at that. CHRIS ANDERSON: In the body. DON BOX: Oh, that's excellent. CHRIS ANDERSON: I actually am pretty attracted to this language. It's pretty cute. It's -- CHRIS ANDERSON: I like it. DON BOX: I wonder if I could do both. So, why don't we go ahead and what we are going to do is this message is going to be a little bit simpler than the message we used before. We're just going to put a string in the body. So declare string. And I want you to go ahead and crack that out as a message. So even though the message in that is in XML, is 100 percent SOAP conformant, what are we going to do is just program against it as if it's an object, and then it's easier in this case. So we do a message.content.getobject. This gives me a reference to the content. I then ask it to be coerced to string, and then there's some VB magic syntax to make the cast work. CHRIS ANDERSON: It's a cast. DON BOX: Yes, welcome to the new world. CHRIS ANDERSON: I am getting used to it rapidly. DON BOX: Fantastic. Now, we've got the string. Again, this is one of these -- the code I would like to write. Actually, first we've got a new class. That class doesn't have any reference to the foreground. So why don't we declare a field of type tile foreground, and we'll set that up later on. We don't have to worry about that yet. What we really want to do is the tile.thetext. CHRIS ANDERSON: That's statement completion against the mark-up as well, so we haven't built -- thought we had -- well, I did built it actually. DON BOX: Great. Cool. And what we are going to do -- what we want to do is just assign it F. Now, this is the ideal world we wish we lived in. Today what we are going to have to do to get this to work is a little magic. So what we are going to do is put that code into a function that takes an object as a parameter and returns an object as a result, and we're also going to have to -- CHRIS ANDERSON: Do we have to return null or nothing or -- DON BOX: We do. Or we don't? CHRIS ANDERSON: VB takes care of that for us. DON BOX: OK, great. So is that all you need to do in the function? CHRIS ANDERSON: We need to cast the string. DON BOX: So we'll pass the string in through that parameter. Fantastic. CHRIS ANDERSON: I need to remember to put commas in the right place. DON BOX: Yeah, great. Fantastic. And so now, what we need to do is this is again a line of code -- don't take too seriously, but it's needed to make this demo work against the live bits. So look away from the screen. We're going to call context.begininvoke. What this does is it takes the context in our thread, which is not the user interface thread. This is a service in "Indigo" that the incoming message will be dispatched on an arbitrary thread. What we need to do in this build of "Longhorn" is flip from that arbitrary thread to the thread that has user interface access. And to do that we do context.begininvoke, passing it to delegates of the code we actually want to run. CHRIS ANDERSON: So this is also VB doing multi-threaded programming with method type, talking to "Indigo" across any protocol? DON BOX: Yeah, yeah. CHRIS ANDERSON: That's pretty good too. DON BOX: Fantastic. CHRIS ANDERSON: Great service. DON BOX: That code is looking good. CHRIS ANDERSON: It is. DON BOX: Did we give it a good name? CHRIS ANDERSON: We gave it the name of My Service, which I think is a great name. DON BOX: Great. Let's go ahead and wire it up. So what we are going to do is create a new port. This is "Indigo." So we create a port -- that's where all life begins in "Indigo." And this time what we are going to do is pass a constructor, which is the URI that we are going to listen on. And I don't really want this thing to be accessible across the Internet. I only want it to be accessible on my local box. So "Indigo" ships with a variety of transports. One of them has the MS.SOAP -- or cope -- dot-Xproc -- CHRIS ANDERSON: And you were complaining about the other APIs? DON BOX: Yeah, I know -- colon, and then put in an identifier of your choice here. One -- an identifier, great. So we've got our port. Before we open the port, we need to wire up our service as a receive channel or on a receive channel, so go ahead and say P-dot -- make your service, initialize it, and then go ahead and go port.P.receivechannel.handler equals S and now release the hounds. Do a P.open and at this point all kinds of stuff's going to happen in my app. CHRIS ANDERSON: Oh, but watch this. Everyone pay close attention here. I'm going to now install the tile. Let's hope I get the right one. So, inside the build environment, I have Visual Studio automatically register that with the side bar so I didn't have to do anything extra. DON BOX: That's a very nice productivity enhancement. CHRIS ANDERSON: It's a productivity enhancer. DON BOX: Yes, great. (Applause.) CHRIS ANDERSON: So, why don't we go modify our client to take advantage of this? So, we'll just use the existing XAML -- this is the last piece of code we're going to write, so we're just going to ripping -- DON BOX: Oh, I'm just going to start tearing this apart. CHRIS ANDERSON: Yeah, get rid of that stuff. That looks -- oh, change the URI to point to the real one that we just typed in, which is MS.SOAP.XPROC, an identifier, very good. We'll be living with that identifier for awhile. DON BOX: Can we actually use the same UUID? CHRIS ANDERSON: No, actually I'd like you to change the first eight digits very quickly. DON BOX: OK, first eight digits. CHRIS ANDERSON: 00000000, eight zeros, great. DON BOX: This is in honor of the tune do, like an I unknown. CHRIS ANDERSON: And pass a string, which we'll get from the bob.text. And, nuke that onerous, horrible line. DON BOX: Gone. CHRIS ANDERSON: You're cooking with gas, dude. DON BOX: Fabulous. CHRIS ANDERSON: Please go build. Have we had any demos tank, that just didn't work at all? DON BOX: Not so anyone would know. (Laughter) CHRIS ANDERSON: So I think, since this is our last demonstration it would be okay if it tanked. DON BOX: OK CHRIS ANDERSON: If it doesn't work -- DON BOX: So we'll set expectations low and then if it works -- CHRIS ANDERSON: You almost need accepting of that. So in the pink box type something. Yeah, of course, literal boy. And then go ahead and say push me on. Actually I'm going to hit the invoke blogging code. DON BOX: Oh, is that where we are? CHRIS ANDERSON: Ah, argument null exception. I know what the failure is. I knew about this one before, and I have failed you, Don. I have caused the only demo to tank. I've always wondered what it would be like to have your demo fail in front of, you know, 7,000 or however many of thousands of people are here and now I truly know. DON BOX: So, you're going to fix it in real time. CHRIS ANDERSON: I am going to fix it in real time. So the error, for those of you who would like to know, is that I am still woefully inadequate in my ability to use my language that I love truly and I miss, yes, pass the data to the background thread. DON BOX: Ah. It's all about data. So you still haven't come to terms. You were conflicted. CHRIS ANDERSON: Great. OK, chow, chow, let's make this one happen in a successful way. OK. Or I could say that was my attempt to show people that -- all right -- it's not coming up. DON BOX: Really. CHRIS ANDERSON: And, I know why. You see we have this -- remember this (in-proc ?), the ports, right, so we have a port that's dangling and you never want to have a dangling port. But because we have that dangling port I'm going to make a minor little change. DON BOX: Ah. CHRIS ANDERSON: And we're going to fix this. I can recover because I've paid attention in school and I know how to make this work. So what happened was the -- something wedged, we left a transport port open. So we need to go change the identifier. This is why the tool bar, the task bar was glowing. DON BOX: OK, so we have our hole of PDC. CHRIS ANDERSON: It showed. DON BOX: Now, Chris, just do it. CHRIS ANDERSON: OK. Please work. Yes. (Applause) DON BOX: My brother, my brother. So that didn't use IIS, nothing. CHRIS ANDERSON: No IIS, no nothing, very fast, very light weight, very cheap. DON BOX: Great. This feels like a reasonable time, Jim. Thanks for having us. JIM ALLCHIN: Thank you. And not too bad for whippersnappers, huh? (Applause) Well, I've got a hard decision to make. We've got some incredible demos that we're about to go into, but we've already kept you here a long time. Would you just like to stand for a few minutes or keep going? AUDIENCE: Demo, demos! JIM ALLCHIN: OK, we're going on. The next thing that we are going to cover is how apps can take advantage of the great system you just saw and we have been out working with a set of partners, both from the commercial side, corporate developers and Web developers to see how they might take advantage of some of the great stuff that you're seeing. So, we're going to have Adobe, Merck and Amazon come up and show. We're going to show what they're working on and the first demo is going to be from Adobe and you know they're a premier graphic design company and most people aren't building in notepad by EMAC slick edit; they have to use something very, very high end and I think Greg Gilley is here with his team and is going to come out and give us a little demonstration on how they are going to take advantage of Longhorn. Hey, Greg. (Applause) GREG GILLEY: So, I assume everybody's familiar with PhotoShop, right? So Adobe does also had professional video tools. One of them is Adobe AfterEffects. AfterEffects is used for motion graphics, compositing and special effects that gets used in films and commercials and things like that, anyplace that you really want to add sizzle to your presentation. So, let me run a real quick video here to show you an example of some of the things that AfterEffects can do. (Video segment.) So, pretty cool stuff. And, as we've been talking with Microsoft and as they were showing us some of the capabilities of "Avalon," the "WinFS" stuff, we were thinking what if you could use a tool like this to design your user interface for your application. So we decided we would sit down and try and see what we could do. So, we got Len who's a UI designer and Chris, who's our coder. They're going to come out and show you a little example of what might be possible. LEN: All right, thanks, Greg. Say, as a designer sitting down to build a new application for Windows today, if I wanted to find a UI, I have very few options. The way it is today is I sit down with a static image editing program, maybe like PhotoShop, and I create a bitmap of what I want to produce. It's a really manual process. I take that bitmap and the first thing I do is print it out and hand it to my friend Chris. And as a developer, he's going to sit down and try to recreate what I've done. In an ideal world, I'd like to be able to use the tools that I know how to use as a designer, like After Effects from Adobe. And what your seeing on the screen here is AfterEffects 6.0 with a program that we've written that exports to XAML. So, what I've got here on the screen is actually some UI, which we use AfterEffects for, like Greg showed you, to build motion graphics and special effects. So what you can see, this is sort of a motion graphic effect like you'd see for a stock check on an evening news program, right, showing stock data coming in, except you'll notice it's not complete. What it is actually is not just a video that I'm saving out, but a template for a UI. The way I might do this in today's world is to build a video, put the data in there as a fixed value and then just save it out to something like Windows Media format. Now, once that's done it sticks, I can't change it. What I've done here is created the charts, the animation. I put in some parameters here for Chris to use later. And now I can save this as instead of a video that's fixed in time, I can save it as a piece of UI and give it to Chris and he can go do something like bind it to a Web service to get real time data. So what I want to do is save that, go over to export, export it to XAML, put it in a directory where Chris can pick it up. Going to go ahead and write over this. And now that it's done, Chris can take over and add some logic to this and build some code on top of my UI. So let's see what you can do, Chris. CHRIS: Thank you, Len. So, the first thing as a developer, Len and I spoke, and we decided on a class name. And I went ahead and I build a project. You can see that I had a dummy file, or a XAML file that Len has created in AfterEffects and delivered to me. The first thing I'm going to do is load in his files and rebuild the application that I was working on just to make sure that Len gave me what we discussed. As you can see here, it's up, the animation loads, it looks beautiful, the fidelity is almost exactly what you have in After Effects, except for some of the metadata that Len had in there, which soon I'll be binding to a Web service. Additionally, you can see some elements that I added across the bottom, there's a portfolio and a news button and a little text edit field for symbol look up. So, let's go ahead and add some event handlers, but I'll actually bind this to the Web service and make this animation dynamic and interactive. The first one we're going to add is just a loaded handler. I've already gone ahead and written some of the code to handle this, but that will go ahead and bind this to the Web service and get the data dynamically. The second one I'm going to add is an on-selection change handler for the list box. And what this will do is this will allow us to handle changes in the list box and repopulate the data from the Web service. So, I'm go ahead and send this again. Once again this is just XAML that I got for Len. I did not have to go into Notepad and re-edit this. You can see now we have data that we've pulled from the Web Service running live on this machine. This is stock data (Applause.) Pretty cool, huh? And, in addition to that, you have this lit box down here where you can select different ones, and once again the animation starts over, and you can see more data has been pulled off the server. But this is still XAML. So not only did I not have to code the XAML, which I'm very happy about it, but I get to take advantage of the properties inherent in XAML such as the fact that it's resolution independent, it's vector based. I can lay it back out and it has relayout built into it for me automatically. So regardless of what this runs on, by Len and I working together we created this excellent UI and I didn't have to code any XAML. LEN: Wow, that's impressive. (Applause) CHRIS: So you can see that's a great example of the kind of user interfaces that you can create inside "Avalon" and the nice thing is there wasn't any EMAC involved. (Laughter) And, if I could make one final plea, so I know there's a lot of desktop app guys out there and I know you guys probably already have UI designers that help you with this, but for you enterprise app guys, could you please hire UI designers to take advantage of some of these new capabilities. Thank you. (Applause.) JIM ALLCHIN: "Avalon." It's fabulous. The problem that often happens today that prevents a huge step up in the productivity is the fact that doing things across organizations and with different systems that exist in different organizations, it's virtually impossible. So if you really want to have a huge jump for any of the business apps you really have to do something that's sort of different. And, we have Merck here who's going to give you an idea of how they're approaching a big jump ahead using Indigo. So Jim Karkanias is here I think with his team and is going to give you an idea of what his group is going to be able to do. JIM KARKANIAS: It's good to be here. (Applause) Well, as you've heard, I'm Jim Karkanias. I head operations for part of Merck, and what operations means is we basically solve problems that we encounter in the business of clinical trials. Now, you may know already that clinical trials is a complex business, complex for a lot of reasons. Some of the inherent reasons are that it's research and discovering the unknown is sort of inherently a difficult task, as you can understand. But there are others factors that contribute to this. For example, clinical trials, just one clinical trial, one piece of a clinical trial, would involve as many people as would fill this room, so you can imagine how many interactions you need to take into account. As a developer, if you're going to build a system to handle that or an application to handle that, you can appreciate that that's a challenging task, so how might you approach that. We're going to suggest that information management is a key here, and focusing on the information itself from a supply chain standpoint and working it into the workflow of the folks involved -- the patients in the trials, the physicians taking care of those patients, the regulatory agencies, the hospitals that are involved -- allowing them to work in a way that's natural for them and allows us to collect the data at the same time is a much easier way to implement such a system. So obviously "Indigo" is an opportunity to connect all these things together and we'll show you what we mean by that. I thought we'd take the opportunity to put together a demo that talks about a hypothetical clinical trial. This will be an allergy study and we'll just show you a few of the participants that would normally be encountered in such a thing. This is Rich Gleeson, who's going to be playing the part of a physician taking care of patients in the trial, Jim King, who will be playing the part of a clinical monitor managing the data in the trial and, Jim, if you wouldn't mind being the patient in the trial. JIM KING: I'm still breathing. JIM KARKANIAS: OK, great. We'll get you set up and come back to you. So let's talk about how you might deploy a system. I just finished telling you that we don't think that you can achieve a solution here by approaching it from a classical direction, so how do you even get the software to the people that need to use it, and we'll show you that. I'll turn it over to Rich, who will walk us through one-click install. RICH GLEESON: Great. So, the first step as the physician for this trial is I need to get the software installed onto my desktop. And we're going to do the one-click "Longhorn" deployment. I'm going to click on My Studies site initiation, and this is going to pull down the client to my desktop. So now instead of the old world of just having a Web page I have a full rich client that is going to allow me to participate with this trial. Now, the next step is I need to add a patient to my study, I need to add Jim here, so I'm going to Select Patient. And you're going see the "Longhorn" contact picker, but customized for my application. So this is showing me my contacts that qualified for the study, of which I've got Jim. So using the "Longhorn" identity system, I have this contact and I can trust that I know who he is, and I'm going to add him to my study. I've got a lock showing I've got a trust. I also have a pathway for data to Jim. So let's see how he's doing. Let's check his real-time readings. I should start taking data from him. There you go. RICH GLEESON: Thank goodness. (Laughter.) So that's pretty cool. What you're seeing here is real-time data coming from Jim. He's holding a device here, as you can see. This is a measurement device from QRS Diagnostics, and it connects to an iPAQ. And you remember I said let's try and create an environment that allows the patient or the participants in the trial to work in the way that is natural to them. This is an allergy trial, so we need to collect data on pulse, oxygenation, respiratory function. And we could ask Jim to go to a hospital or schedule a visit with a physician, but instead allow him to work at home, for example, and collect data on his terms. This is wirelessly communicating with a PC. It could be in his own. The data is traversing Net gateways, a whole host of intermediate servers, making it in real time to the physician's office. And the applications developed along the way don't need to know the details of that and "Indigo" helps to bridge that environment. So the data is looking pretty good. On these screens here you should be seeing the real-time data. Let's create an anomaly that we need to handle. So, Jim, if you wouldn't mind, just take a shallow breath into that tube. And I'll explain that, of course, Merck needs to make sure that we understand what's going on at all times in our trial to maintain maximum safety and efficacy of our product. So the physician is being notified of an anomalous event and he's going to start a collaboration session with Merck to talk about this data. And you'll see how "Indigo" bridges a disconnected environment in that case. I'll turn it over to Jim King, who will walk us through that. JIM KING: Thanks, Jim. As Jim said, I'm playing the part of the Merck clinical monitor, so I'm going to receive notification that you just saw pop up on the screen there. And that's in a position indicating that there's something to investigate. So I'm going to go ahead and look at he's sending me data. Let's see what we're actually looking for. We're going to go to real time. And remember, when data was sent, I wasn't connected. Now I'm looking for that cue to respond and feed me all that data. You see it all catching up here, and I didn't have to do anything but go ahead and click on it. Thank you. (Applause.) Also, there's an anomaly noted here, so clearly that's what he wants to look at. So we're going to go ahead and do a little bit more work. And again, we're going to make use of some of the features that are available here; specifically "Avalon" for the visualization and then we're going to use "Indigo" again to make another Web services call and really do some more drilling into this. You see, there's three patients here who look like they share the same anomaly. You've got a threshold here that they all fall below. So we're going to drill into these three patients. And I'm going to use a Web Service call out to MapPoint to pull all this together. So I've got data coming from many different places, from the patient to the physician, back into my office. And right off the bat, I'm able to draw an initial conclusion by looking at the geographic proximity of these three patients. They're all in a cluster here. And MapPoint allowed me to do that. But that doesn't tell me enough, so we're going to drill into it a little bit more and overlay the pollen count or for all of us maybe smoke would be a little bit more appropriate with everything we're dealing with. But we're going to overlay the pollen count. We'll see what happens. Almost immediately, you see that everybody's in the pollen zone who had the anomalous event. So we can draw an initial conclusion. To make it more compelling and understand if there's a temporal aspect here let's roll back the block and again we're going to use the feature of "Avalon." Notice the alpha blending of the overlay and the data binding we're able to do as I roll this back. That's pretty powerful stuff right there. So we roll it back. We're able to draw an initial conclusion, and say that it looks like the data that was sent to me indicates that the anomalies are definitely pollen-related, and I can collaborate with a physician on that information. JIM KARKANIAS: Thanks a lot, Jim. That's awesome. (Applause.) So you can see -- let's review what we've seen here. We have a multitude of systems involved, connected here, all with applications written, without regard to the infrastructure. "Indigo" helps to map all that together. We're getting the right information to the right people in the right time frame. And we are working with the IT barriers that are created as a function of all the different systems that are in existence as a result of this large population that we have to deal with in clinical trials, much like what other large businesses are faced with in today's world. So we encourage you to talk with us more about this. There's a booth to visit, the "Indigo" booth, and a partner pavilion. But now Don Box will be talking about the code and walking us through some of that. Thanks a lot. (Applause.) JIM ALLCHIN: Thank you. Well, we're going to have Don come out. He's back there someplace. He's just going to give you a little bit -- a snippet of exactly how the "Indigo" code worked. DON BOX: Thanks, Jim. Let's take a look at this machine here. Let me minimize all these fancy windows. Here's some code. What I'd like to do is take a quick glance at the code that made that Merck program work. I'm going to open up a simple C# file, which is already written. This uses "Indigo," as we said already. This one actually uses a different part of "Indigo" than we used in the lab. In the lab, we were programming at the low-level messaging layer. This uses a more higher-order-of-service model. And notice that we simply write a class. We mark it with Dialogue Port Type. What Dialogue Port Type says is I expect arbitrary messages to come in and go out; it's not a strict request reply disciple. And notice also that I was able to annotate methods with a variety of attributes to control what the contract was between the service and consumer. And in this case, not only was I able to control the shape of the messages and the message exchange pattern, but I was also able to declaratively say, 'Here are the security requirements I need' -- in this case, pointing to a blob of config XML, which controls the concrete details of the security, as well as a logical role name, which I'm going to use for standard authorization of incoming messages. JIM ALLCHIN: You did it all with just those few lines of code? DON BOX: Yeah, with just those few lines of code. JIM ALLCHIN: Fantastic. Thanks. DON BOX: Thanks. (Applause.) JIM ALLCHIN: So you've now seen two of the demonstrations. I want to do another one with Amazon that ties it all together. And this will show what can be done in an application using "Avalon," how it can be used and store information in "WinFS" and get new views out of that, and then finally, how to use "Indigo" for the Web services. Al Vermeulen is here from Amazon. Al, you want to come out and show us cool stuff? Great. AL VERMEU: All right. Thanks, Jim. (Applause.) Hi. How are you all doing? Are you starting to see kind of the possibilities of what you'll be able to build with "Longhorn" and "Avalon" and "Indigo" and these things? Are you starting to kind of get excited about this stuff? (Applause.) Or are you just at the point now where you've had a couple of cups of coffee and some water and been sitting there for three years? And the reason I ask if you're getting excited about what it is I'm doing here, is that we got together with some folks from Microsoft and some folks from Amazon -- oh, I don't know, maybe a month or so ago -- just to talk a little bit about what we're doing at our respective companies. The Microsoft folks, they told us about "Longhorn," a lot of the things that we're seeing here. And at Amazon, we told them about our Web services strategy. And our Web services strategy is really pretty simple. What it really comes down to is take all of the elements of our e-commerce platform that you all know and love through interacting with our Web site. I assume everybody here is boxed up on Amazon.com. If you haven't, we run this Web site. You can go there and buy stuff. I encourage you to go for it. Our Web services strategy is to take all of that functionality, all of that data, all the algorithms that we've developed over the last several years, and expose them to applications via Web services. That's it -- pretty simple, pretty straightforward. When we got together with the Microsoft people, we started thinking, "Well, how is it that we can create innovative new things using "Avalon" and "WinFS," these rich client technologies, to create interesting shopping experiences for our customers? What kind of things can we do by combining Amazon Web services and "Longhorn?" And we came up with all kinds of ideas. Unfortunately, I only have a few minutes so I'm just going to sort of show you a couple of those ideas. And what I'll do first is fire up the Amazon rich shopping application. This is just a demonstration that we put together. And you can see right away, just as we fire this up, that this is not your normal HTML Web page. Right? We've got some video happening here. That's kind of cool. We've got this shopping cart control so you can sort of check out what's in your shopping cart at any time without having to go and, you know, actually change to a different Web page. That's kind of neat. This is something interesting here. You've got recommendations, and the recommendations are actually cycling through. One of the things that we know at Amazon is that material that we put -- we call this above the fold -- stuff near the top of the Web page is much more likely to convert; that is, people are much more likely to click on it than stuff below the Web page. So some clever person here said, "Well, we can use that space above the fold and rotate some recommendations through it." Now, why would a developer do this? One of the things about our Web services that's really kind of interesting is that developers who build things on Amazon Web services actually have a bit of an economic model that they can leverage. OK, this is an important thing we do with our Web services. The model goes like this. If you write an application and you distribute it out to folks and they use that application to buy things on Amazon.com, then, via our Associates program, we give you a piece of the action. So you get a cut. And there's actually a lot of people who build things on Web services that are making a reasonable living at it. So that's kind of cool. Let's actually use this thing now to buy something. So I'm going to do a search for a digital camera. It turns out that my wife this weekend has gone to visit her sister. Her sister just had a child. And when your sister has a child, you have to go and visit her. The other thing you have to do is you have to take your camera, because you can't have too many pictures of a four-month-old baby. So that left me without a camera. And I got to thinking, well, I really ought to have two, because I'd love to be able to take pictures of all these fine people. And so we'll go ahead and search for a digital camera. What's happened while I was talking is that the application, this rich shopping application, has hit Amazon's Web services, asked for a digital camera, and then gone and retrieved all of the rich information we have about 300 cameras that match that search criteria. It took all of that rich information and stuck it into "WinFS" so that we can have "Avalon" controls that could, you know, quickly and easily go ahead and search through that information to find things. If I was Don Box, I'd actually in real time build this app and show you just how easy it is to do this. But I am not Don Box. So we can go ahead and we can do things like filtering operations. Let's say we're only interested in cameras that are really kind of well-liked by our customers, that got, say, four stars or better, and we've cut down from several hundred cameras down to 31. That's kind of fun. We can sort by brand. Let me reset this. We can sort by brand. Let's say we're interested in -- can we sort -- we can sort by brand; just ask for, say, Canon cameras and Vivitar cameras. So that's kind of neat. We can do some basic sort of filtering things here. We can get detailed information on any camera. And you notice the detail information. This camera doesn't have any reviews. The detail information includes reviews and price and all kinds of stuff like that. That's great. Let's see. Does this one have reviews? Oh, I've picked two cameras without reviews. That's okay. But at the end of the day, this is still kind of a relatively flat sort of a list, right? I mean, it's cool, but it's not kind of what you'd hoped for in this rich graphical environment that we're expecting with this new operating system. So let's take a look at another way to display this information. So this is kind of cool. This is the "Avalon" carousel control. So taking all of that data about cameras that we retrieved from Amazon, and put it in this really kind of nifty control, we display all several hundred cameras at once. And I can go through and rotate through. (Applause). Doesn't that look slick? It's just beautiful. It's not only beautiful; it's actually practical, too. This is a really kind of useful way to be able to check out stuff. Let's see. I can filter on price and you can see the number of panels kind of diminishes there. I want to pay -- you know, I probably want something more than US$200, and I don't really want to spend more than $583.81. So that's great. I can go through, and let's actually buy one of these now. Let's see, how about this one? And here we go. This one actually has reviews, so you can see that I was telling the truth when I said there was additional information about all of these products that's available. Now, to buy this, again, we'll just do a nice simple graphical metaphor. We'll grab this thing and we'll just drag it over here into the shopping cart. There we go. And we've got a shopping cart now. That's kind of fun. And now, to check out, all we have to do is push the button. One of the things that I want to point out here is that all of this stuff is real. OK, this is all real code. So Amazon Web services, this all works today. You can go home and write these kind of applications on top of the Amazon platform and you can use the "Longhorn" bits, once they're available, to actually build this kind of UI. So that's very cool. We can go ahead and change things about our shipping options, and let's actually place that order. The reason -- this is the one thing, actually, that was dummied up in this demo is the demo doesn't actually place real orders. Otherwise I'd own a lot of cameras by now. And you know the nice thing about that? When I buy that camera, buying things from Amazon makes you happy. (Laughter.) It's a great thing. OK, so that's one thing we can do. We have a nice, rich client shopping experience. What else can we do? Like I said, we came up with a lot of things. The other one I'm going to show you right now involves the calendar control, and this is the idea that at Amazon we have lots of, you know, products that release all the time. And it's a big deal to people to know when do products release. So we can go ahead and get that data again from Amazon Web services and display it on this nice calendar control, and you can see that the David Bowie album came out on the 21st. Actually, my family has already bought the two things at the top this week, the Indiana Jones and the David Bowie, and we'll be buying "The Two Towers" as soon as it comes out. My son is just a huge "Lord of the Rings" fan. So this is kind of nice. What I would really like to do, though, is see how this fits in with my personal life, if I'll have time to actually watch these movies and so on. So I can overlay my calendar on top of this calendar. What's interesting about this -- you heard Jim talk about this already -- it used to be very difficult to get at my calendar information, because it was buried somewhere in Outlook or in Exchange or something. I don't know; it was hidden way down there. And there's probably a lot of people in this crowd who are smart enough to know how to get that stuff out and dig it out of there and put it on this page, but it's difficult for mere mortals. Well, with "WinFS" it's easy, because that data is exposed. It's really interesting to think about the Amazon information you're seeing here, because really our Web services strategy is the same thing. All of the Amazon data used to be buried behind a Web site. It was hard to get at. What we've done with Web services is make it easy to get at. Right? So now we can take this easy data to get out from Amazon, the nice data from "WinFS," and put it together in this one control. So that's great. I can see I'm at the PDC this week. This is something else that was made up. I'm not really going to Hawaii. It'd be nice. But this is actually true. This is really true. November the 2nd is my mom's birthday. And I look at this and I go, 'You know, this is terrible, because it's Monday. My mom's birthday is on Sunday and I haven't bought her anything.' This is actually literally true. I've known about her birthday for a while and I still haven't bought her anything. The reason we know this is mom's birthday is because in "Avalon," we have information about all of my friends and family. We go ahead and we look there. We see that there's birthday information. So we know that this is the actual birthday of a friend of mine. We can build functionality into the app, which we've done, to go through and purchase a gift for my mom. So we'll go and we'll purchase a gift for my mom. What we've done now is we've hit Amazon.com Web services and gotten hold of my mom's wish list. And this actually is my mom's wish list, just to show that this is real stuff. And you can see my mom likes cool things, unlike Don Box's mom, who installs E-Max and probably owns all the O'Reilly books; it turns out that my mom quilts and listens to Elton John. So I can go ahead and I think I'll buy here the Elton John CD, and again I wish the ordering thing was actually hooked up here because I've done this several times now and I still haven't bought my mom a present. (Laughter.) So we'll go ahead and drop that in and again I'll go ahead and buy this. I can add a few more things. I can put a message into my mom for her birthday, so that's a good idea. So I'll write my mom just a little note. OK, that's cool. And it knows it's a birthday gift, so it's automatically set up gift wrapping. I can turn that off, but I actually want gift wrapping for my mom. It knows I'm buying something for my mom's birthday, so you notice that the people picker, the contact address has already set this up automatically to ship to my mom. That's great. If I wanted to, I could fire up the people picker and go ahead and change that or I could change it and have it build somewhere else. That's great. Standard shipping will be fine because her birthday is in five days. So we're all set, we'll go ahead and place that order. And there we go. Now, if this was actually hooked up at the end to do the order, my mom would have her gift. So that's cool. The last thing I want to show you -- thank you. (Applause.) The last thing I'm just going to touch on very briefly, and that's to show that this whole environment could be integrated. And what we've done is, over here, in order status, as I'm placing these orders, I go ahead and I drop them into my sidebar. Something really interesting that we've discovered about our customers at Amazon is that they love to see what's happening with the stuff they've ordered. And I'll bet you've done this too, right? People love to track their orders. They love to know that UPS has picked it up in Fernley, Nevada, and it's now going down whatever interstate, and it's getting dropped off here, and so on. So what we're imagining that we could do here -- and this is not real yet, we haven't built this -- what we're imagining we could do is with a notification service, we can actually be sending notifications, via Web services, and a client, like an "Avalon" client, could receive those notifications and sort of show you, in real time, where your order is going. So that's kind of neat. So this is what I want to talk about, is the rich client experience. So in closing, let me just again mention that this was, except for the very last part, all real stuff built on Amazon Web services. We've released -- I believer there's been something over 35,000 developers who are currently using Web services, built lots of cool applications, lots of orders coming through that channel. If you want to learn more, I think we have a booth setup here, and we'll have somebody there to man it, and you can come and talk to them. I encourage you to download the software and play with it. Thank you very much. JIM ALLCHIN: All of the underlying code that you've seen is real. Think about it. It's not that way in some other events. (Laughter.) And nothing crashed. It's not that way in other events too. "Longhorn" is truly a milestone event for Microsoft, who has been sort of the receiving end of not moving fast enough on the Internet. You know, we pay attention and try to get a lead on as many things as we possibly can. We think that this is an area where, if you invest early and get with the train and learn, then you can receive some disproportionate share of the gains that will take place. We've got a lot of technology. We're also going to invest to help you make money in deeper ways than what we have before. Typically, we try to push marketing. We push the product out there, give you a lot of what we would call sockets for your applications. We're going to go beyond that this time. We don't have this all worked out, but some of the things that I wanted to mention at this event was that we've done some system design reviews, some early reviews of this with developers, and they keep saying, 'How about helping us out on licensing? How about putting an automated system in there so you could license your product, if you're a commercial vendor?' That is something that we are going to do. We have continued to work on that technology, so we'll have a facility for you to be able to license your product and do it at scale if you want to, in whatever licensing models that you want to use. But the infrastructure would be in place. That's one thing. Second thing is that we have a very, very, very simple Windows catalogue today. Think about us taking it to a whole other level, where you will be able to have your product and be able to take it from end to end. And we will push, push, push those out to people so that they can see the best Windows "Longhorn" applications. And, of course, there will be more coming. We will make this a tremendously large event. In terms of, now, how do you get there, if you have Win32 bit app today, barring security issues and the like, those applications should be able to run on "Longhorn." If you're working with the .NET Framework today, those applications would work on "Longhorn," and you're on your way to the WinFX APIs. If you have a Win 32 bit app, or a .NET Framework app, you can start taking advantage of the WinFX APIs. And perhaps, you can't rewrite your code to manage. It's OK. Just start using the functionality in the system that you need for your application, whatever it would be. We've designed the system specifically for that purpose. And then, finally, if you're writing a new application and it's in the "Longhorn" timeframe, then you can take advantage of the full WinFX environment. Now, we don't have WinFX APIs today, certainly, in the bits that we're going to give out here that cover the entire system. But it should be very clear that's the path that we're on, to basically make that the new layer, surface area for the system. In terms of schedule, this is only the client. Obviously, there are separate schedules for server. They've both got the same general technology in server, but I'm only going to get into the client schedule. Quickly, the media center just shifts. The "Longhorn" developer preview, that's the bit that we're going to provide to you today. In the first half of 2004, there will be a service pack for Windows XP, and a new updated Tablet, which has dramatically better recognition capabilities, as well as several other very, very nice facilities. In the summer time, and second half of the year, we'll be coming out with a 64-bit edition for AMD, as well as "Longhorn" Beta 1. Beta one will be where we take it to the next level and ask a lot more people besides you. I mean, honestly, we've shown "Longhorn" to no one before today -- just a few set of people, like the ISVs here, to get their feedback. We will be going bigger there. We're not going to make other commitments about when we're going to get done with this product. We're going to try to focus on getting to Beta. See, you will have a pretty good idea, with the bits, about where we're at. We still have a long way to go. We are listening. We have a show net here called. There's an application that, if you already haven't downloaded, I propose that you do that. Give us feedback. I know there's been, already, a bunch of information coming. I was walking back stage, looking at some of the information. It's great. It's a great way for you to get with your peers. It's a great way to tell us what's going on. We are listening, and we're very invested in your success. There's a set of things that we think you should do. This would be what we would call our call to action. They're very straight ahead. We think fundamentals are really important. We, together, have to nail the security infrastructure so that people can trust these systems. Web services: it's the way to get great inter ops. Managed codes: it's the way to avoid arrows, pointers, get higher productivity. Smart clients: you want high, interactive, rich experience. You need to take advantage of those and help us be better in community. We're trying to really work on that, as you'll see with the application we've got here -- all of the people that are into blogs, and other things. We're really trying to connect with you, and that's what this conference is about. Now, you get the bits today. In fact, as you go to lunch, you're going to be able to get the bits. You should have gotten a card, which is in your conference bags. There's a lot of information on these discs. There are two CDs just of "Longhorn" and different versions -- a 32-bit version, 64-bit, both of IA 64 as well as AMD 64. We also talked about that as X64. There is the "Longhorn" driver kit, along with the SDK. There is Visual Studio, the would-be version, Yukon the sequel, newest update of that. There is the Virtual PC 2004 version. Now, that's a virtual machine technology that does actually work with these "Longhorn" bits. And there's lots of white papers, and samples, and other things. Now, I want to set the context for where we are in this release. We still are very early. We've never shared bits this early. So you're going to see a lot of work. There's things in terms of the programming model that we haven't cleaned up yet. Performance is not good. (Laughter.) I mean, there's no other way to talk about it. Performance is not good yet. You should put on only high end machines, and I propose that you not put it on any production machines, and I propose that you not connect it -- at least not knowingly -- to the Internet, in the sense that, it's fine if you put on the Internet connection firewall, which should be on by default. But you should be thinking, you should know that these are early bits. We think it's incredibly cool, and we hope it's what you need in order to get really familiar with the system and provide us that feedback that we want. We're incredibly excited about it. We think it is the next generation. And with that, I want to thank you. Have a good lunch and good conference. Thank you very much. Developers Talk to Developers about New Windows Innovations - Oct. 27, 2003 Jim Allchin Biography
http://www.microsoft.com/presspass/exec/Jim/10-27pdc03.mspx
crawl-002
refinedweb
21,635
82.24
It became clear from the emails and comments to my last post that I should probably spend a little more time describing the functionality found in the VSTS 2010 CTP a bit better, specifically that functionality involving the Architecture Explorer and the graphs generated via the AE. ( I just figured everyone had already run out, downloaded that 7.5gig image, and started playing! :) ) This post introduces the three "Standard Graphs" found off the Architecture Explorer using the DinnerNow - ServicePortfolio2 solution found in that aforementioned CTP. The idea behind these graphs are to give you the ability to get some "typical" views of your source base with as few mouse clicks as possible. Here's a shot of the Archicture Explorer, as seen with the DinnerNow solution open in VS 2010: You'll notice the Visualize Code Relationships menu item, which is where you'll find the three menu items that will create graphs by Assembly, Namespace, or Class dependencies based on the contents of the current solution. If you select the Visualize Call Dependency - By Assembly menu item, here's what you'll get: This graph is all about showing you the dependencies between the various assemblies that make up all the projects in your solution. If you don't have the solution built, you'll notice that after selecting this menu item ( this will happen for any "standard" graph actually ) the solution is built. This is due to the fact that we are cracking the assemblies in the output directories and gathering the information found there. The nodes you see above represent each of the assemblies discovered in this solution. You'll also notice links of various thickness between these nodes. The thicker the link, the more dependencies between the two assemblies. We sometimes refer to these types of links as "blood vessels". Notice the chevrons in the upper right hand corner of the nodes in this graph: This is an "expand / collapse" button for this "group" node. You'll also notice in the upper left corner of each node, a number indicating the number of internal nodes inside the group. Here's what the DinnerNow.Services assembly node looks like when expanded ( click for larger view ): The green and blue nodes represent Classes and Interfaces. You'll notice in the shot above the tooltip displayed as I hover over the CustomerService node, the category reads "Class". If I double-click on that node, it takes me to the source code where that class is defined. Selecting the Visualize Call Dependency - By Namespace results in a similar type graph, except this time the initial nodes you see below represent the namespaces found in the solution: Clicking on the chevron of the DinnerNow.Services node shows the exact same information as it did when viewing from the Assembly diagram ( show below in-situ ): Selecting the Visualize Call Dependency - By Class results in the most complicated of graphs, mostly because what you are seeing is dependencies at the class level, with no grouping by assembly or namespace. Expanding a chevron in this graph reveals methods, properties, fields, indexers, etc. that are contained by that class or interface. Below is a shot of just a section, as the graph is pretty large: One thing to point out if you haven't already discovered this, is that if you hover your mouse over a particular link, you can quickly jump to either end of the link. Quite helpful on large graphs like the Class dependency graph! One other thing worth mentioning. The dependencies discovered on these graphs are dependencies discovered through static analysis of method call data, not structural dependencies. For example, if you have two classes that don't call each other but one includes the other as a type for a member, no dependency link will be created. What other "Standard Graphs" should we include out of the box? What are some typical views over your solution that you would like one to two clicks away? Thanks! Cameron
http://blogs.msdn.com/b/camerons/archive/2008/12/18/standard-graphs.aspx
CC-MAIN-2014-42
refinedweb
667
58.01
This is the highlight of learning Python. We have went through the use of numerous in-built functions and also user defined functions. You would have realised that these types of function represents the two extremes in the use of technology: Either as an end users who utilise what other people have coded for you, or code the logic of a program from scratch. One is convenient but inflexible, the other offers ultimate flexibility but you probably have to go through a 4 year degree code up a complex algorithm. Programmers over the years also realised this issue as well, when they are spending too much time coding things from ground up. Instead of reinventing the wheel, they embraced the open-source and decided to pool together their code that they have optimised for their line of work. Since these libaries are free for all to use (without copyright issues as they are merely logical steps complied for easy use), this is where non computing students should learn to code and program our own custom solutions for our work. In Business Analytics Consulting Team, we pride ourselves in knowing enough to apply many machine learning algorithmn and data analytics tools and explain the signficance of these applications to actual business operations, be it marketing, finance, adminstration or HR. We are less concerned about how it is done, but why should it be done. Installation of packages and importing of modules There are external Python libaries you can download and install on your local Python installation. There are also internal Python libaries that does not require download but is not usually active unless you call for it. Internal Libraries For example, you might always use excel files to analyse CSV files. However, given the massive influx of data in the real business world, a business analyst might be faced with a dataset of more than 1,048,576 rows (Excel’s row limit). Even if your dataset might not even reach 1 million rows, a couple hundred thousand rows of data can already paralyse your computer if you try to manipulate it in excel. Hence we will cover an example of an internal libary that can used to read csv files in to Python – csv import csv #now you can take input from csv files! myCSVfile=open("user.CSV", "r") #open() function takes in the path/name of file, and what action you want to do to it, r stands for read reader = csv.reader(myCSVfile) for row in reader: print(row) ['id', 'first_name', 'last_name', 'gender', 'age', 'email', 'ip_address', 'created_time'] ['1', 'Lyda', 'Clues', 'Female', '32', 'lclues0@java.com', '7.56.94.77', '2017-10-06 20:45:51'] ['2', 'Demetrius', 'Franks', 'Male', '45', 'dfranks1@livejournal.com', '219.3.208.171', '2017-11-09 18:43:57'] ['3', 'Lebbie', 'Laurent', 'Female', '35', 'llaurent2@huffingtonpost.com', '196.15.212.128', '2017-12-04 19:59:39'] ['4', 'Liana', 'Gawen', 'Female', '50', 'lgawen3@google.com', '58.216.62.115', '2018-01-19 02:52:57'] ['5', 'Tymon', 'Huggon', 'Male', '29', 'thuggon4@goo.ne.jp', '127.251.184.252', '2018-02-27 04:35:50'] ['6', 'Jessalin', 'Scini', 'Female', '32', 'jscini5@blogger.com', '80.220.20.106', '2017-08-28 14:03:43'] ['7', 'Ronda', 'Dockrill', 'Female', '36', 'rdockrill6@webs.com', '241.56.47.132', '2017-06-10 06:11:08'] ['8', 'Ashien', 'Glidder', 'Female', '', 'aglidder7@github.io', '149.60.3.61', '2017-06-23 12:54:50'] ['9', 'Cecilla', 'Josefowicz', 'Female', '25', 'cjosefowicz8@ebay.com', '168.34.20.228', '2017-07-13 19:26:57'] ['10', 'Brigg', 'Micklewright', 'Male', '', 'bmicklewright9@boston.com', '25.252.116.121', '2018-04-07 02:05:13'] ['11', 'Avrit', 'Wrangle', 'Female', '33', 'awranglea@home.pl', '80.161.183.123', '2017-08-18 09:01:28'] ['12', 'Isidora', 'Bofield', 'Female', '43', 'ibofieldb@freewebs.com', '214.37.163.204', '2017-09-25 18:54:48'] ['13', 'Gabriel', 'Narramore', 'Female', '47', 'gnarramorec@ft.com', '69.134.203.85', '2017-12-25 19:53:35'] ['14', 'Murray', 'Finney', 'Male', '43', 'mfinneyd@webeden.co.uk', '33.137.59.171', '2018-01-22 10:01:28'] ['15', 'Diann', 'Pauletti', 'Female', '39', 'dpaulettie@gov.uk', '25.191.8.98', '2017-11-28 03:48:51'] ['16', 'Papagena', 'Rooper', 'Female', '38', 'prooperf@forbes.com', '0.230.87.20', '2018-05-10 07:49:21'] ['17', 'Tremaine', 'Lacoste', 'Male', '34', 'tlacosteg@reuters.com', '85.2.94.72', '2017-05-29 23:37:21'] ['18', 'Lanita', 'Suddaby', 'Female', '43', 'lsuddabyh@imgur.com', '127.212.164.138', '2017-06-03 03:26:44'] ['19', 'Jeralee', 'Eslemont', 'Female', '41', 'jeslemonti@yahoo.co.jp', '110.91.134.83', '2018-04-23 22:19:14'] ['20', 'Rabi', 'Gander', 'Male', '47', 'rganderj@comcast.net', '206.195.153.8', '2017-09-06 16:09:36'] ['21', 'Ragnar', 'Betser', 'Male', '32', 'rbetserk@themeforest.net', '39.133.247.86', '2018-03-14 12:08:18'] ['22', 'Cecilio', 'Burke', 'Male', '50', 'cburkel@ox.ac.uk', '51.228.253.81', '2017-08-02 14:50:49'] ['23', 'Anselm', 'Candish', 'Male', '45', 'acandishm@google.pl', '119.114.228.222', '2017-12-16 02:30:55'] ['24', 'Connor', 'Cominetti', 'Male', '40', 'ccominettin@privacy.gov.au', '94.54.250.106', '2017-05-22 01:07:00'] ['25', 'Mario', 'Vannuchi', 'Male', '48', 'mvannuchio@symantec.com', '36.154.173.198', '2017-07-14 06:01:40'] ['26', 'Viola', 'Dedon', 'Female', '', 'vdedonp@deviantart.com', '98.161.127.34', '2017-08-02 20:26:21'] ['27', 'Augustin', 'Beszant', 'Male', '32', 'abeszantq@state.gov', '202.219.140.45', '2017-11-08 11:42:34'] ['28', 'Gill', 'Porteous', 'Male', '', 'gporteousr@unblog.fr', '15.2.75.24', '2018-04-09 17:45:40'] .... and many more rows External Libraries Machine Learning Algorithms – sklearn Data Visualisation – matplotlib You can install them through cmd (windows) / terminal (MacOS) with the command pip install packagename. For example: pip install pandas ()
https://nusbact.com/2018/07/29/python-tutorial-7-libraries/
CC-MAIN-2018-47
refinedweb
967
64.81
Hi, I'm programming a code to generate a table of values with an operator and have to use pointers. I'm having a problem understanding how pointers work and how to use them in the function, even after reading chapters on the topic. If someone could help me out by maybe giving a brief explanation, it would be of great help. 2 Replies - 538 Views - Last Post: 08 March 2011 - 05:43 PM #1 Writing a table in C but having a problem understanding how to use poi Posted 08 March 2011 - 04:56 PM Replies To: Writing a table in C but having a problem understanding how to use poi #2 Re: Writing a table in C but having a problem understanding how to use poi Posted 08 March 2011 - 05:02 PM #3 Re: Writing a table in C but having a problem understanding how to use poi Posted 08 March 2011 - 05:43 PM Quote If someone could help me out by maybe giving a brief explanation, it would be of great help. A pointer is a variable that holds a memory address. This is very useful because a pointer can "refers to" or "point to" other data. To really make this useful you need to be able to "de-reference" the data, that is access the data at the memory address pointed to. So: int var = 10; // var is some data *somewhere* in memory int* ptr = &var; // &var returns the "address of" var and so now ptr is a pointer to var. *ptr = 2; //*ptr dereferences the address ptr and gives access to the data there cout << var << endl; // prints 2 So to access different locations in memory we can assign a value to a pointer and then dereference the pointer to access (read/write) the data at that memory location! Example: Strings in C are a collection a chars with the last one equal to 0. Generally a pointer is used to point to the first char in the string. #include <iostream> using namespace std; int main() { const char* aString = "I had a tiny turtle his name was Tiny Tim."; cout << "Address of aString's data in memory = " << (void*)aString << endl; cout << "value of aString's data in memory = \"" << aString << "\"" << endl; cout << "ADDRESS : ch : ASCII" << endl; for (const char* ptr = aString; *ptr !=0; ptr++) { cout << (void*)ptr << ": " << *ptr << " : " << hex << (int)*ptr << endl; } return 0; }OUTPUT: > "C:\CProjects\Forum Help\ptrExample1.exe " Address of aString's data in memory = 00E89334 value of aString's data in memory = "I had a tiny turtle his name was Tiny Tim." ADDRESS : ch : ASCII 00E89334: I : 49 00E89335: : 20 00E89336: h : 68 00E89337: a : 61 00E89338: d : 64 00E89339: : 20 00E8933A: a : 61 00E8933B: : 20 00E8933C: t : 74 00E8933D: i : 69 00E8933E: n : 6e 00E8933F: y : 79 00E89340: : 20 00E89341: t : 74 00E89342: u : 75 00E89343: r : 72 00E89344: t : 74 00E89345: l : 6c 00E89346: e : 65 00E89347: : 20 00E89348: h : 68 00E89349: i : 69 00E8934A: s : 73 00E8934B: : 20 00E8934C: n : 6e 00E8934D: a : 61 00E8934E: m : 6d 00E8934F: e : 65 00E89350: : 20 00E89351: w : 77 00E89352: a : 61 00E89353: s : 73 00E89354: : 20 00E89355: T : 54 00E89356: i : 69 00E89357: n : 6e 00E89358: y : 79 00E89359: : 20 00E8935A: T : 54 00E8935B: i : 69 00E8935C: m : 6d 00E8935D: . : 2e > Process Exit Code: 0 > Time Taken: 00:00 So as I dereference each address I find that there is a printable ASCII char there and so this data is some text, not all data is text data though. Strings in C rely heavily upon pointers to access blocks of continuous memory containing text data. Rather than requireing a variable for each letter, I can refer to the address of the first character and mark the ending of the string with a '/0' char. Part II: pointers know data size Pointers are addresses and all addresses are is numbers. But pointers are kind of special because the know the "size" of the type they refer to in memory. So a char is typically 1 byte so when you add 1 to a char* the address goes up by 1 to get you to the next char. But an int is typically 32bits or 4 bytes so when you add 1 to an int* the address goes up by 4 bytes to get you to the next int in memory. #include <iostream> using namespace std; int main() { int piDigits[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}; cout << "Address of piDigits's data in memory = " << piDigits << endl; cout << "ADDRESS : digit" << endl; for (int* ptr = piDigits; *ptr < sizeof(piDigits)/sizeof(*piDigits); ptr++) { cout << (void*)ptr << ": " << *ptr << endl; } return 0; }OUTPUT: > "C:\CProjects\Forum Help\ptrExample2.exe " Address of piDigits's data in memory = 0026F98C ADDRESS : digit 0026F98C: 3 0026F990: 1 0026F994: 4 0026F998: 1 0026F99C: 5 > Process Exit Code: 0 > Time Taken: 00:00 note the addresses go up by 4: 0026F98C + 4 = 26F990 So when you add/subtract a number to a pointer it slides the address up/down by units of the size of that pointer's base type. char 1byte, short 2 bytes, int 4 bytes (these values are platform dependent). So if we have int* ptr = 0x800000; (some random address) then ptr = ptr + 10 will be 0x800028 -- since 10*4 = 40 = 0x28 so the array access operator ptr[5] is the same as *(ptr + 5) -- which means that rather than doing a lot of pointer arrithmatic to access elements of a block of memory like a string we can use the array access operator [] to do it! I hope this helps, sorry it was not as brief as I wanted. Page 1 of 1
http://www.dreamincode.net/forums/topic/220921-writing-a-table-in-c-but-having-a-problem-understanding-how-to-use-pointers/
CC-MAIN-2016-30
refinedweb
947
64.98
. No having to break that Hey Alex, The button to go to the next lesson points to lesson 9.6 instead of lesson 9.4 This was a very helpful lesson! Thanks! Big fan of the site! Thanks, fixed. Hi Alex, I was actually interested in the consequences of not using the reference symbol "&" while overloading the output operator. I was thinking it is just matter of efficiency, but I wanted to see it written. Thanks! Would this code work? It can be a bit more memory consuming, but I think it would work as well and it should be possible to make multiple calls like Am I wrong? Thanks! That is exactly what the quiz solution does, except it passes and returns std::ostream by reference instead of by value for efficiency. Am I missing something? Just so I'm clear about the need for referencing the ostream and istream class, here's how I think it works in very basic terms: 1) I use ostream &operator<< to reference the ostream class so I can alter it to my liking. 2) The first parameter ostream &out --> references cout so I can alter it. 3) The second parameter Point &cPoint --> references the actual point from something like cout << cPoint so I can use it in the << definition 4) After I define << to a particular format, I return out (the altered cout) 5) Whenever I use << and an instance of type Point is on the right side, it will use this custom << definition 6) When chaining is used, whatever is returned from the first function call to operator<< will become the new version of cout to use for the next data. So from cout << cPoint1 << cPoint2; cout << cPoint1 becomes just cout, and we'll be left with cout << cPoint2; Apart from this lesson, the rule seems to be "use friend functions when the overloaded operator doesn't modify the object". So why aren't we making >> a member function? Still not entirely clear on when to use friend and when not to with operator overloading. Also - why does the >> function return an &istream? Can you chain the >> operator? Edit: Partially found the answer to my question: Binary operators can either be members of their left-hand argument's class (because of the hidden *this pointer) or free functions. Since you can't edit the ostream or istream objects (which in commonly used syntax are always on the left, and therefore the first parameter of the <> function), you have to use a free function, and to access the members it has to be a friend. Did I get all of that right? I still don't understand why the binary arithmetic operators had to be friend functions though? Yes, you got it right. Binary arithmetic operators don't have to be friend functions, but it's easier to understand them if they are written that way. Also, yes, you can chain the >> operator. "Any time we want our overloaded binary operators to be chainable in such a manner, the left operand should be returned." Is it a general rule to return the left operand or it depends on associativity? Return the left operand regardless of associativity. Ok, I have a question about. Playing with this, I've realized its possible the operator the user chooses to overload can "get confused to ostream". So I'll be short this time. Two 3d points. point1(4,5,6) point2(1,2,3) 1)We have ready an overload for ostream that show us the 3d point we send. 2)We overload a sum of the points with "operator+". Its perfectly possible write: cout<<point1+point2<<endl; But if we change operator+ for, (for example), "|" or "^" in step 2, then it isn't possible get this working: cout<<point1^point2<<endl; We then need to put it in this way: cout<<(point1^point2)<<endl; I guess is a matter of precendences, or maybe a special way ostream haves to interpret that operators. I've no idea why happens this, but I suspect the mystery will be revealed in I/O lesson (chapter 13). Anyway, if this points deserves a menction, I'm looking forward to know a little bit more now. It's a matter of precedence. + has higher precedence than <<, so cout << point1 + point2 << endl; gets prioritized as cout << (point1 + point2) << endl; ^ has lower precedence than <<, so cout << point1 ^ point2 << endl; gets prioritized as (cout << point1) ^ (point2 << endl); That's why the explicit parenthesis are necessary in the second case. Thanks one more time Alex. Here, why I am not allowed to make any of these as constants. Sorry, only 'ostream& out'. Why can't we make it as constant. Point can be a constant. ostream can't be. When you send something to ostream to be output, ostream gets modified -- thus, it can't be const. thank you for this Alex, For the Point class I overloaded opeartor+ and operator- to add and subtract x, y, and z for each point. I have the overloaded operator<< in my program and it works correctly. I tried to add two points in a cout call and got errors at compile saying invalid operands to binary expression for <<. However if I add the points into a new point and then try to print it there is no issue. I can't see why I can't do it as an anonymous variable since my overloaded + for point returns a Point and << knows how to deal with that. A little more of the error invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Point') I was able to compile and run this program successfully in Visual Studio 2015. Can you provide the entire error message that you are getting, including which line it is complaining about? I'm on a Mac, but haven't had any different behavior with the clang compiler before. Full code: First two errors: repro.cpp:62:12: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Point') std::cout << point1 + point2 << '\n'; ~~~~~~~~~ ^ ~~~~~~~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ostream:179:20: note: candidate function not viable: no known conversion from 'Point' to 'std::__1::basic_ostream<char> &(*)(std::__1::basic_ostream<char> &)' for 1st argument basic_ostream& operator<<(basic_ostream& (*__pf)(basic_ostream&)); ^ After that are a lot more notes about not being able to convert from Point to different types for the 1st argument. It seems to think that the first argument to << is a Point (I'm guessing point2). But that doesn't make much sense because the operator precedence should complete point1 + point2 and return a Point, then << should happen left to right and my overloaded operator<< would then get the arguments with the ostream as the first argument. I think I see the problem here. If you look at your overloaded output operator: Note that Point is a non-const reference parameter. But when you call it: point1 + point2 is an rvalue and doesn't have an address, so it can't be passed to a non-const reference. The solution is easy: make your Point parameter const. That way it can take either an lvalue or an rvalue argument. You should be doing this anyway since your output operator doesn't modify the Point parameter. Thanks, that was it. Now I see it, but the compiler was not very helpful here. I can usually puzzle out the errors but wasn't able to this time. Thanks for the help. Dear Alex!! I'm trying my best to learn C++, so please help me out: - Why do you use ostream instead of Point as the friend function's type although the function itself take objects from both ostream and Point class? Is ostream somehow a priority? - Why do we need to make reference like this: friend ostream& operator.... Thank you so much ! Having the operator return ostream allows us to "chain" multiple inputs together: If we didn't return an ostream, then we'd have to print each of these separately, like this: We make ostream a reference to prevent C++ from making a copy of the ostream argument every time the operator is called, or when ostream is returned. Alex, you are an excellent teacher, thank for providing this useful site, thank you very much 🙂 above program crashes after taking the character input(char*) in function operator >>, Why and how to get rid of it? A few things here: 1) Your overloaded operator >> and << both need to return ope. 2) I put your program in a debugger and it's crashing on the line where it's reading obj.m_char with the following error message: Unhandled exception at 0x01122B8B in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x0112EB64. Consider what's happening here: When var is created, you're pointing m_char at a string literal. In the lesson on string literals, I mentioned that string literals can and often live in read-only memory. When your input function tries to input m_char, you're trying to overwrite a string literal in read-only memory, so you're getting a memory access violation. It's a little weird to me that you're declaring a variable with default values and then asking the user to overwrite them. Generally you'd want to do one or the other. That aside, a fix is easy: change m_char from type char* to type std::string. That way, std::string can dynamically manage the memory needed to hold the string for you. You'll also need to update your ret_char() function: Thanks again Alex. You are a very good teacher. In the function declaration: friend ostream& operator<< (ostream &out, Point &cPoint); the out object is passed in by reference. But where in the code does the out object come from. thanx. x << y becomes operator<<(x, y), so when you do something like: "std::cout << point", the out object is std::cout. I am fall in love with this site....so helpful...solve my problem regarding the concepts of overloading...keep it up this good work...again thanks. 😀 Thanks for this great, great website. I am trying to put 9.2 and 9.3 together: overload +, and overload <<. Each of them works by itself. But if I put them together my compiler (Mac OS X 10.8 clang++) complains <b>operators 9.3 b.cpp:137:7: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Point') cout << cPoint1 + cPoint2; ~~~~ ^ ~~~~~~~~~~~~~~~~~ </b> followed by many many errors against /usr/include/c++/4.2.1/ostream like this one: <b> /usr/include/c++/4.2.1/ostream:112:7: note: candidate function not viable: no known conversion from 'Point' to '__ostream_type &(*)(__ostream_type &)' for 1st argument operator<<(__ostream_type& (*__pf)(__ostream_type&)) </b> Here's the code: (I know RSA answered this question above, but I'm not really getting the answer. The code I posted (without the line that doesn't compile) works fine (and follows the code in 9.1 for MinMax) so returning a Point seems to yield a value in the calling program that works fine for assignment to p2. Why doesn't it parse as of the right type for the overloaded <<?) Your operator+ returns an anonymous Point object, which you're then trying to pass into operator<< by reference. C++ won't let you have non-const references to anonymous objects. In your overloaded operator+ and operator<<, make your Point parameters const. friend ostream& operator<< (ostream &out, const Point &cPoint); what does ostream& mean? << is a binary operator that links a stream and whatever is output to it. Also, << chains. So when you overload << you want your function to return a reference to a stream. Hence ostream& is the type of your overloaded << function. It means the function is returning a reference to an object of type ostream. In checking the final example of the "Overloading <<" section, I ran into a peculiar output that I can't understand. I've had a look through the comments, but can't see anyone else mentioning it! cPoint1 and cPoint2 are fed doubles, and the constructor takes those doubles and stores them in private variables of type double. These are then fed through the overloaded << operator, and *should* be printed in their native double form, to my understanding... however when I run the complete program I get the following as output: (2, 3, 4) (6, 7, 8) I can't see any point in the code where the doubles should be collapsed to integers, can anyone help? I literally copy-pasted the last two codeblock examples from the section to play around with, and added the required include for iostream and the std namespace at the top. Visual Studio (at least) prints doubles that have no decimal values as integers by default. You can see this here: This prints 2, not 2.0. Thanks alot for accepting me as a member in this great website. I am interested in learning C++ so much and this website is a great source to depend on in learning C++..... You should mention that "<>" are originally arithmetic bitwise shift operators. It's certainly an interesting bit of trivia, isn't it! ostream& operator<< (ostream &out, Point &cPoint) { // Since operator<< is a friend of the Point class, we can access // Point's members directly. out << "(" << cPoint.m_dX << ", " << cPoint.m_dY << ", " << cPoint.m_dZ << ")"; return out; } Hey Alex we are returning a reference to the object 'out', which has local scope. Is it legal?? Yes, it's legal in this case because the return value was passed _in_ as a reference parameter. This is one of the few times where it's generally okay to return a value by reference. When the operator<< function becomes a friend of class Point, it allows us direct access to the member variables m_dX, m_dY and m_dZ. We could avoid making the operator<< a friend of the class Point and instead use member functions GetX(), GetY() and GetZ(), for improved encapsulation. Is this example purely to demonstrate the use of the "friend" command or are we saying this is a preferred method? Although it might seem like having the friend use access functions would increase encapsulation, I'd argue there's likely to be little value to be found here (unless those access functions are non-trivial). Friends functions can't friend themselves (and thus subvert a classes access controls) -- the class itself has to say that a function is a friend, and thereby grants the friend function the same access as members. Because of that, friend functions really should be considered part of the class, even though they aren't member functions -- and if you update your class, you should update the friend functions too. Personally, I don't have any qualms about having my friend functions have direct access to the internal members of the class they are friends of. would anyone help to understand me why are we passing both the arguments as a reference,and what will happen if we pass them as value parameters Alex replied to this above:-. this should work now Yes, it works, thanks for your solution. Furthermore, can you explain me why, thanks in advance:) This type of error is compiler specific. The reference of the newly created date is no longer valide when the function exits because all the data inside that function are all destroyed. There are few ways to solve this problem, for example you can make static your variable if you consider that its lifetime to be the whole execution of the program. You can make it global and assign with the new operator like I did, but you musn't forget to delete all variables that used "new" (when the program ends the os deletes them automatically). Here it worked because pointer created with "new" remained in the memory. But you should make it global and delete it if you want to avoid memory leak during execution, or make it static. Hi RSA, As per your explanation, how come default copy constructor manages to perform the similar kind of access which overloaded<< operator could not able to perform. The problem with the original program is that it was returning a local (anonymous) variable by reference. That means it was returning a reference to something going out of scope. RSA's solution actually isn't the best, because a developer wouldn't expect operator+ to dynamically allocate a new instance of Date. A better thing to do would be this: That way, a copy of the date is returned by value. the line cout<<date1+date2 outputs wrong result, i cannot find why.. In the above example - any many others like it on the web - the code is written thus: Meanwhile many other texts - including a C++ textbook I'm using - would write it as: I imagine the complier just ignores the difference in whitespace, but what's up with that? The first version makes more sense to me, while the second makes me scratch my head. Can anyone clarify why they'd write it differently? Or are they actually different? This is purely a matter of style. Choose whichever you prefer, since as you guessed, the whitespace is ignored by the compiler. I don't have a reason for it that I can explain, but I prefer "char *func()" and "char &func()" over "char* func()" and "char& func()". I guess I was raised that way. 😉 why it should be friend? If you implement it as a member, it will have to be a member of 'ostream', taking one 'Point' as parameter: In c++ we can't reopen and extend the ostream-class, so we have to use a friend function. Think of it the other way: if you implemented it as a member of 'Point'... ... you could pass a 'ostream' to the 'Point' class through the '<<'-operator: This compiles, but (in our case) it doesn't make any sence. Hope this helped! [offtopic]in some languages (i.e. ruby) you can reopen and extend existing classes (i.e. 'ostream')[/offtopic] Hi I also have a problem that I cannot understand. I tried to compile my code with GNU C++. Here is a part of my code: The header file The source: The compiler sends the following error message: "/home/demarcsek/dev/Kalaha3/src/KCompress.h:63: error: 'std::ostream& Kalaha::KCompress::BitArray::operator<<(std::ostream&, const Kalaha::KCompress::BitArray&)' must take exactly one argument" When I modified this function with only one argument as a const BitArray& and used cout as a default stream, the compiler wrote the following message: "/home/demarcsek/dev/Kalaha3/src/KCompress.h:63: error: 'std::ostream& Kalaha::KCompress::BitArray::operator<<(std::ostream&, const Kalaha::KCompress::BitArray&)' must take exactly two arguments" It's funny...Can anybody help me? Thanks, George ostream& BitArray::operator<< ( ostream& _stream, const BitArray& _arr ) { //implementation return _stream; } That's wrong - it shouldn't be member function of the Bitarray class. Instead, it should be a "global" function: Instead use this: ostream& operator<< ( ostream& _stream, const BitArray& _arr ) { //implementation return _stream; } Alex - I don't understand why this: isn't written like this: I guess I don't get the difference between "out" and "cout". ???? Thanks. Good question! Here's what I think you might be missing: out might not be cout. It might be cerr (an output stream used for error conditions), or a file ostream object (an output stream for writing to a file instead of the screen). You'll learn about both of these in the chapter on I/O. In those cases, we don't want to write to cout, we want to write to whatever alternative output stream we're using. Those alternative streams come into the overloaded < < operator as the "out" parameter. For example: cerr < < "You have hit error # " << nErrorNum << endl; cerr < < "You have hit error # " << nErrorNum << endl; This is broken up like this: ((cerr < < "You have hit error # ") << nErrorNum) << endl; cerr's overloaded extraction operator will receive cerr as the "out" parameter, and "You have hit error # " as a string parameter. When it is done loading the stream, it will return cerr. Then evaluation will continue, and we will have: (cerr < < nErrorNum) << endl; cerr's overloaded extraction operator will receive cerr as the "out" parameter, and nErrorNum as an integer parameter. When it is done putting the value of nErrorNum in the stream, it will return cerr again, and evaluation will continue: cerr < < endl; Again, cerr's overloaded extraction operator will receive cerr as the "out" parameter, and endl as it's other parameter. It will do it's thing, return cerr, and evaluation will continue. At this point, there's nothing left to evaluate, so evaluation is complete. If we had returned cout instead of out, then nErrorNum and endl would have been printed to cout instead of cerr! Hmm, can I reference my own classes in a manner similar to the way ostream& references an ostream class? If that is possible, could it be useful. Curiosity killed the cat! 🙂 Yes. This is typically done in two ways. Let's say you wrote a class named Foo. If you are writing a function that lives outside of Foo: If writing a function that is a member of Foo: Then I shall in good time have to experiment coding a reference to a class. I imagine this will increase my understanding of the ostream implementation. I understand everything on this page well enough to overload I/O operators. I feel I grasp everything that has been presented here. Still, I'm left wondering what goes on under the hood. For example: What does the & (reference operator) do here: ostream& operator< < I believe this is the first time I've seen anything like that, a reference to a function or something? Does this maybe somehow tie into function pointers? ostream& operator< < I'm in a little over my head at this point. I'm wondering if it's even important to know what's going on under the hood with this issue. Your thoughts? Jason, ostream is a class provided as part of C++ that handles outputs streams. The details of how ostream is implemented is very complex, but fortunately also completely unnecessary to use it effectively.. So basically, our overloaded function takes an ostream as a parameter, writes stuff to it, and then returns the same ostream. This allows us to chain < < calls together: < < cout < < cPoint1 << cPoint2 << cPoint3; This resolves as follows: ((cout < < cPoint1) << cPoint2) << cPoint3; cout < < cPoint1 is resolved first, with cout becoming the ostream& parameter. When this overloaded function is finished writing to the out parameter, it returns that cout so the next call to < < can use it. Thus: cout < < cPoint1 becomes: (cout < < cPoint2) << cPoint3; cout < < cPoint3; This calls our overloaded function one last time. At the end of this function, cout is again returned. But there's nobody left to use it, so the return value is ignored. The expression ends, and the program moves to the next line. What really had me confused was the return by reference statement. This ostream& operator< < was confusing me simply because returning a value by reference is something I had not seen or done up until this point. It took me a little while to make sense of this. Anyway, here is some code that I came up with that helped me understand what takes place when returning a value by reference. There really isn't much difference between return statements and function parameters, except for the directionality of the data transfer and the fact that you can only have one return value. Pretty much everything you've learned about pass by value, reference, and address apply to return values in the same way that they apply to parameters. Name (required) Website
http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/comment-page-1/
CC-MAIN-2018-13
refinedweb
3,982
62.48
Set the signal mask attribute of a spawn attributes object #include <spawn.h> int posix_spawnattr_setsigmask( posix_spawnattr_t *_Restrict attrp, const sigset_t *_Restrict sigset_p); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The posix_spawnattr_setsigmask() function sets the signal mask attribute in an initialized attributes object referenced by attrp. You must have already initialized the spawn attributes object by calling posix_spawnattr_init(). The value of this attribute is used as the signal mask in the new process image of a spawn operation if POSIX_SPAWN_SETSIGMASK is set in the spawn flags attribute; to set this flag, call the POSIX function posix_spawnattr_setflags(), or().
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawnattr_setsigmask.html
CC-MAIN-2018-43
refinedweb
108
53.41
API for comparing core cursor positions. All the fuctions here are located in RDM DB Engine Library. Linker option: -l rdmrdm See cursor for a more detailed description of a cursor. #include <rdmcursorapi.h> compare the position of a cursor relative to another cursor This function compares the current position of cursorPrimary relative to cursorSecondary. If the cursor types are not the same the current row of the secondary will be used and then converted to a position in the cursor type of cursorPrimary. If the current row of the secondary is not a valid cursor position in the primary an error will be returned. This means: #include <rdmcursorapi.h> Check a cursor for special conditions. This function will return information about an RDM_CURSOR's position. As you navigate (using any of the rdm_cursorMove* functions) the cursor will typically be in any of these states: CURSOR_BEFORE_FIRST; CURSOR_AT_ROW; CURSOR_BETWEEN; or, CURSOR_BEFORE_FIRST. Changes to the row through this cursor or any other cursor may put the cursor in some other state. #include <rdmcursorapi.h> Check to see if a cursor is positioned after the last row in a collection. This function will set isAfterLast to RDM_TRUE if the cursor is positioned after the last row in the cursor collection. #include <rdmcursorapi.h> Check to see if a cursor is positioned before the first row in a collection. This function will set isBeforeFirst to RDM_TRUE if the cursor is positioned before the first row in the cursor collection.
https://docs.raima.com/rdm/14_1/group__cursor__position.html
CC-MAIN-2019-18
refinedweb
245
55.24
Does Wargus run on a Mac? I'm trying to figure out if I can run Wargus on a Mac. Has anybody had any success with this? I tried downloading and installing Stratagus as per the instructions and hit a snag when I hit: "Could not find library or program tolua++" I'm not sure if I'm installing the right thing either because on the Stratagus install page, it says Mac OS X users: Extract the "contrib/ But I can't find this "contrib/ Any suggestions would be appreciated. Thanks. Question information - Language: - English Edit question - Status: - Solved - For: - Wargus Edit question - Assignee: - No assignee Edit question - Last query: - 2012-03-11 - Last reply: - 2013-02-06 Thanks for the message. I was able to get it working by installing Ubuntu Linus on my Mac, so now it's running under Ubuntu. Not as good as running natively, but at least it runs. The obstacle to getting it to run natively is getting tolua++. I can't get the thing to build under Mac OSX. until you succeed to have a tolua++ working(seem possible according to google), a possible workaround is to use the generated tolua.cpp from Ubuntu under mac So you should be able to run stratagus natively. stratagus instruction has been updated. This question was expired because it remained in the 'Open' state without activity for the last 15 days. I got to compile Stratagus right on Mac OSX 10.6.8 : - Needed to compile a new SDL from the sources and delete Apple one, but its because I am still on Snow Leopard - Needed to create a custom.py file on the root of tolua folder: ## BEGIN custom.py CCFLAGS = ['-I/usr/ LIBPATH = ['/usr/local/lib'] LIBS = ['lua', 'dl', 'm'] ## END custom.py - Needed to patch the homebrew formula for lua (version 5.1), otherwize it gives some error when creating tolua.cpp Homebrew Formula change: def install # Apply patch-level 2 curl "https:/ safe_system '/usr/bin/patch', '-d', 'src', '-i', '../patch- # we could use the patches method if it supported additional arguments (-d in our case) + #patch the patch: http:// + inreplace 'src/llex.c' do |s| + s.gsub! " luaC_checkGC(L);", " //luaC_checkGC(L); //Homebrew patch." + end # Use our CC/CFLAGS to compile. Now, it compiled right. Going for wargus now... Problem with tolua++ was solved Note: I don't have Mac stratagus intallation instruction is a little outdated, sorry. You have some dependencies : - SDL (required). - libpng (required). - zlib (required). - Lua(required). - tolua++ (required) - libogg/libvorbis (recommended). - libmikmod (recommended). - libbzip2 (optional). you need also CMake. you have then to run -- 8< -- cmake make -- >8 --
https://answers.launchpad.net/wargus/+question/190283
CC-MAIN-2020-29
refinedweb
439
66.64
In this tutorial, we will cover how dictionary comprehension works in Python. It includes various examples which would help you to learn the concept of dictionary comprehension and how it is used in real-world scenarios. It is defined in curly braces { }. Each key is followed by a colon (:) and then values. You can also execute dictionary comprehension with just defining only one variable What is Dictionary?Dictionary is a data structure in python which is used to store data such that values are connected to their related key. Roughly it works very similar to SQL tables or data stored in statistical softwares. It has two main components - - Keys : Think about columns in tables. It must be unique (like column names cannot be duplicate) - Values : It is similar to rows in tables. It can be duplicate. Syntax of Dictionary d = {'a': [1,2], 'b': [3,4], 'c': [5,6]}To extract keys, values and structure of dictionary, you can submit the following commands. d.keys() # 'a', 'b', 'c' d.values() # [1, 2], [3, 4], [5, 6] d.items()Like R or SAS, you can create dataframe or dataset using pandas package in python. import pandas as pd pd.DataFrame(data=d) a b c 0 1 3 5 1 2 4 6 What is Dictionary Comprehension?Like List Comprehension, Dictionary Comprehension lets us to run for loopon dictionary with a single line of code. Both list and dictionary comprehension are a part of functional programming which aims to make coding more readable and create list and dictionary in a crisp way without explicitly using for loop.The difference between list and dictionary comprehension is that list comprehension creates list. Whereas dictionary comprehension creates dictionary. Syntax is also slightly different (refer the succeeding section). List is defined with square bracket [ ]whereas dictionary is created with { } Syntax of Dictionary Comprehension {key: value for (key, value) in iterable}Iterable is any python object in which you can loop over. For example, list, tuple or string. keys = ['a', 'b', 'c'] values = [1, 2, 3] {i:j for (i,j) in zip(keys, values)}It creates dictionary {'a': 1, 'b': 2, 'c': 3}. It can also be written without dictionary comprehension like dict(zip(keys, values)). You can also execute dictionary comprehension with just defining only one variable i. In the example below, we are taking square of i for assigning values in dictionary. range(5) returns 0 through 4 as indexing in python starts from 0 and excluding end point. If you want to know how dictionary comprehension is different from For Loop, refer the table below. Dictionary Comprehension d = {i:i**2 for i in range(5)} For Loop d = {} for i in range(5): d[i]=i**2 print(d) Output {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} d.keys() returns [0, 1, 2, 3, 4] d.values() returns [0, 1, 4, 9, 16] Create dictionary containing alphabets as keysSuppose you want letters from 'a' through 'e' as keys in dictionary and digits from 0 through 4 as values. string.ascii_lowercase[:5]returns abcde. import string {i:j for (i, j) in zip(string.ascii_lowercase[:5], range(5))} {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} Create new dictionary out of existing dictionary dic.items()returns the whole structure of dictionary which comprises of both keys and values. In the following example, we are multiplying values of existing dictionary by 2 and building a new dictionary named new_dic. dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} new_dic = {i:j*2 for i,j in dic.items()} new_dic {'a': 2, 'b': 4, 'c': 6, 'd': 8} How to use IF statement in Dictionary ComprehensionHere we are applying conditional statement and considering values above 2. dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} {i:j*2 for (i,j) in dic.items() if j>2} Output {'c': 6, 'd': 8} IF-ELSE condition in Dictionary ComprehensionYou can apply if-else statement like we do in list comprehension. This example outlines how to show odd or even numbers in values in dictionary. {i:('even' if j%2==0 else 'odd') for (i,j) in dic.items()} {'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even'} Use Enumerate Function in dictionary comprehensionEnumerate function runs on list, tuple or string and returns element and its index. list(enumerate(['a', 'b', 'c'])) Output [(0, 'a'), (1, 'b'), (2, 'c')]With the use of this function, we can create a dictionary with elements of the list as keys and the index as values. mylist = ['a', 'b', 'c'] {j:i for i,j in enumerate(mylist)} {'a': 0, 'b': 1, 'c': 2} Remove selected items from dictionarySuppose you have a dictionary containing cities name along with some values and you want to delete specific multiple items (let's say Delhi and London) from dictionary. In this example, i refers to keys of dictionary and d[i] evaluates to d[key]. For e.g. d['Mumbai] returns 221. d = {'Delhi': 121, 'Mumbai': 221, 'New York': 302, 'London': 250} {i:d[i] for i in d.keys() - {'Delhi','London'}}It returns these two items {'Mumbai': 221, 'New York': 302} Good tutorial deepanshu ! Thanks. Thanks for appreciation! Usefull for beginners Glad you found it useful Good one ... Good comprehension Cheers (y) Thanks a lot . I love dict comprehension now . Awesome!
https://www.listendata.com/2019/07/python-dictionary-comprehension.html
CC-MAIN-2020-40
refinedweb
893
64.3
Featured Replies in this Discussion - - - You should never ever go into an infinite loop in the event dispatch thread. That would cause your whole application to freeze. Look at this if you aren't sure how to use javax.swing.Timer: ... I think you want ... . I put 500 instead of 100 because you said you want it every half-second, not every tenth of a second. The listener is just whatever object you are using to handle the event that happens… -... ... I'd be satisfied with ANY font/solution. I'll try to explain my situation in more detail: You know my code for the game of life? Now, when I run that code I get separate prints for each iteration of the matrix (one below the other). What I want is a GUI text area which will print out the whole array in that same field, so basically an output refresher. Step by step: 1. Generate initial matrix (as per my code) 2. Print matrix 3. Delete output 4. Generate new matrix (based on initial matrix) 5. Print new matrix 6. Return to step 3 (and do so XX times) I've tried using jTable, but I simply don't know how to transfer the data from the matrix into the jTable (because, to my understanding, the jTable itself can't actually contain data, just show it). I'm just looking for a push in the right direction: how to print a 2D array (which is in a loop) in a text area. PS I really hope I'm making sense. Allright. I've now managed to properly generate a new matrix; apply the game-of-life rules; output new matrix. From Taywin's link I've learnt about timers. And here is where I fail. I want this: private void izra?unajNovuMatricuActionPerformed(java.awt.event.ActionEvent evt) { M.broja?2++; genNum.setText(String.valueOf(M.broja?2)); izlaz.setText(""); M.matrica2 = M.izra?unajMatricu(M.matrica1); M.matrica1 = M.kopirajMatricu(M.matrica2); M.?i??enjeMatrice(M.matrica2); for (int i = 1; i < M.matrica1.length - 1; i++) { for (int j = 1; j < M.matrica1.length - 1; j++) { if (M.matrica1[i][j] == false) { izlaz.append(" _ "); } else if (M.matrica1[i][j] == true) { izlaz.append(" 0 "); } } izlaz.append("\n"); } } To repeat every half a second. So far, I've cooked up this bit: private void autoGenActionPerformed(java.awt.event.ActionEvent evt) { Timer vrijeme; vrijeme = new Timer(100, whatGoesHere?); vrijeme.setInitialDelay(500); vrijeme.start(); for (;;){ izra?unajNovuMatricuActionPerformed(evt); vrijeme.restart(); } } Please note that autoGen is a toggle-button. The idea is to press the toggle button and watch the game play itself until the toggle button is pressed again. You should never ever go into an infinite loop in the event dispatch thread. That would cause your whole application to freeze. Look at this if you aren't sure how to use javax.swing.Timer: I think you want new Timer(500, listener). I put 500 instead of 100 because you said you want it every half-second, not every tenth of a second. The listener is just whatever object you are using to handle the event that happens when your timer goes off. ... import javax.swing.JFrame; import javax.swing.JTextArea; import java.awt.Container; import java.awt.Font; class GoLGUIDisplay extends GoL { public GoLGUIDisplay(int r, int c) { super(r, c); } /***** * Return the current matrix for display. */ public String getDisplayString() { int rows = getRowSize(); int cols = getColumnSize(); String out = ""; for (int r=0; r<rows; r++) { if (r>0) { out += "\n"; } for (int c=0; c<cols; c++) { out += (getValue(r,c)>0 ? "X" : "_"); } } return out; } /********** * MAIN * **********/ public static void main(String[] args) { int fwidth = 800; int fheight = 480; int millisec = 80; GoLGUIDisplay gol = new GoLGUI(12, 30); // create matrix with random alive cells JFrame jf = new JFrame("Display Game Of Life"); Container c = jf.getContentPane(); JTextArea tArea = new JTextArea(10, 100); tArea.setText(gol.getDisplayString()); tArea.setEditable(false); tArea.setVisible(true); tArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12)); tArea.setBounds(4, 4, fwidth-10, fheight-10); // arbitrary size jf.setLayout(null); // reset layout manager for absolute positioning jf.setResizable(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); c.add(tArea); jf.setSize(fwidth, fheight); jf.setVisible(true); System.out.println("... Started Matrix ..."); System.out.println(tArea.getText()); // hold on to see the started matrix try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } while (!gol.isRepeating()) { try { Thread.sleep(millisec); // simulate animation tArea.setText(gol.getDisplayString()); gol.computeMatrix(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } System.out.println("... Result Matrix ..."); System.out.println(tArea.getText()); // hold on to see the result matrix try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } } Pobunjenik - be careful - the approach used in Taywin's code is not one you should follow. "Loops with sleeps" fit very badly with Java Swing, and can behave quite differently on different machines. You will run ito all kinds of problems with that approach as you GUI gets more complex. Using a Timer was the right way to do this - don't worry. Ok James, thanks for the headsup! I did in fact use a timer, but not the javax.swing.timer, I used java.util.timer (as I didn't need the more advanced functions, I think). I did, however, run into one minor problem. I thought that the toggle button would run some code when toggled on, and cease running same code when toggled off. Instead, it seemed to double the speed of the timer (which was in the toggleButtonActionPerformed bit). So, I took the lazy man's approach: simple button and an exit button right beloew. :D LINK: This contains the .jar and the source code. NOTE: The program's buttons are all on my native language, and here are the translataions: Faktor ?ivota - Factor of Life Generi?i prvu matricu - Generate initial matrix Izra?unaj novu matricu - Calculate new matrix Zaustavi i iza?i - Stop and exit Pravila - Rules In the future, I'll add English and German (somehow). PS Daniweb won't let me upload .jar or .rar, so I used RapidShare. The two Timers do different things. Javax.swing.Timer executes code on the Swing Event Dispatch Thread, so that code can call any of the Swing methods safely, but equally it will block the swing thread until finished. java.util.Timer knows nothing of Swing. It's not safe to call (most) swing methods from a jav.util.Timer timer task, but equally a long running task will not block the swing thread. java.util.Timer is also upward compatible with more advanced thread management such as thread pools etc. You should chose one or the other based on how they need to interact with swing. I don't have time now to look at your code, but yur symptom is consistent with not stopping the existing timer before starting the new one - 2 timers running = task scheduled twice as often. I understand that looking at unknown code can be... mind numbing. I've looked at the methods in the timer class (timer.someAwesomeMethods, if I'm right), and the only thing related to a stopper is the timer.cancel(); one, but that one destroyers the timer. Now, if I understand this correctly, javax.swing.timer has the timer.start and timer.stop functionalities which could do what I'm looking for. Another confusion was the toggle button: I thought the code in the button would only be executed while the button is pressed down (toggled on), and stop executing once the button toggles off. Should I not have used the toggleButtonActionPerformed event? Should I have used toggleButtonMousePressed and toggleButtonMouseReleased? Yes, for a java,util.Timer there's just cancel (AFAIK), after which you just create new Timer when you want to start again. As I said before, it's not the methods that determine your choice of Timer, it's the thread that your code needs to run on. You get an ActionEvent each time a toggle button is clicked. In your event listener just call your button's isSelected() method to see whether the event was it being selected or de-selected.
https://www.daniweb.com/software-development/java/threads/444926/the-game-of-life-adding-gui
CC-MAIN-2015-14
refinedweb
1,370
68.77
A Chalcedon Publication [] 3/30/07 Ѯe Journal of Christian Reconstruction A CHAICEDON PUBIICATION Volume 6 Summer 1979 Number 1 Symposium on Puritanism and Progress A Chalcedon Publication [] 3/30/07 The Journal of Christian Reconstruction Volume 6 / Number 1 Summer 1979 Symposium on Puritanism and Progress Gary North, Editor ISSN 0360–1420 A CHALCEDON MINISTRY Electronic Version 1.0 / July 15, 2006 Usage: Copies of this file may be made for personal use by the original purchaser of this electronic document. It may be printed by the same on a desktop printer for personal study. Quotations may be used for the purpose of review, comment, or scholarship. However, this publication may not be duplicated or reproduced in whole or in part in any electronic or printed form by any means, uploaded to a web site, or copied to a CD-ROM, without written permission of the publisher. Chalcedon Foundation P.O. Box 158 Vallecito, California 95251 U.S.A. To contact via email and for other information: Chalcedon depends on the contributions of its readers, and all gifts to Chalcedon are tax-deductible. Opinions expressed in this journal do not necessarily reflect the views of Chalcedon. It has provided a forum for views in accord with a relevant, active, historic Christianity, though those views may have on occasion differed somewhat from Chalcedon’s and from each other. A Chalcedon Publication [] 3/30/07 THE JOURNAL OF CHRISTIAN RECONSTRUCTION This journal is dedicated to the fulfillment of the cultural mandate of Genesis 1:28 and 9:1—to subdue the earth to the glory of God. It is published by the Chalcedon Foundation, an independent Christian educational organization (see inside back cover). The perspective of the journal is that of orthodox Christian- ity. It affirms the verbal, plenary inspiration of the original manuscripts (auto- graphs) of the Bible and the full divinity and full humanity of Jesus Christ—two natures in union (but without intermixture) in one person. The editors are convinced that the Christian world is in need of a serious publi- cation that bridges the gap between the newsletter-magazine and the scholarly academic journal. The editors are committed to Christian scholarship, but the journal is aimed at intelligent laymen, working pastors, and others who are interested in the reconstruction of all spheres of human existence in terms of the standards of the Old and New Testaments. It is not intended to be another outlet for professors to professors, but rather a forum for serious discussion within Christian circles. The Marxists have been absolutely correct in their claim that theory must be united with practice, and for this reason they have been successful in their attempt to erode the foundations of the noncommunist world. The editors agree with the Marxists on this point, but instead of seeing in revolution the means of fusing theory and practice, we see the fusion in personal regeneration through God’s grace in Jesus Christ and in the extension of God’s kingdom. Good princi- ples should be followed by good practice; eliminate either, and the movement falters. In the long run, it is the kingdom of God, not Marx’s “kingdom of free- dom,” which shall reign triumphant. Christianity will emerge victorious, for only in Christ and His revelation can men find both the principles of conduct and the means of subduing the earth—the principles of Biblical law. The Journal of Christian Reconstruction is published twice a year, summer and winter. Each issue costs $4.00, and a full year costs $7.00. Subscription office: P.O. Box 158, Vallecito, CA 95251. Editorial office: 713 W. Cornwallis Road, Durham, NC 27707. Copyright by Chalcedon, 1979. A Chalcedon Publication [] 3/30/07 TABLE OF CONTENTS Editor’s Introduction Gary North . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1. SYMPOSIUM ON PURITANISM AND PROGRESS The Puritan Doctrine of the Priesthood of All Believers Rousas John Rushdoony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22 Medieval Speculation, Puritanism, and Modern Science Charles Dykes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 The Role of Puritan-Calvinism in the Rise of Modern Science E. L. Hebden Taylor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62 The Emergence of Postmillennialism in English Puritanism James R. Payton Jr. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112 Purity and Progress: New England’s First Generation Aletha Joy Gilsdorf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137 From Medieval Economics to Indecisive Pietism: Gary North . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173 A Neo-Puritan Critic Replies 2. DEFENDERS OF THE FAITH Oliver Cromwell (1599–1658) Judy Ishkanian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .224 3. CHRISTIAN RECONSTRUCTION Introduction to William Symington’s Messiah the Prince James B. Jordan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247 William Symington, D.D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248 Publication Schedule The Ministry of Chalcedon A Chalcedon Publication [] 3/30/07 EDITOR’S INTRODUCTION Gary North The idea of progress is a distinctly Hebrew-Christian concept. The belief that there was a unique beginning of time, has been a linear development of time, and will be a final judgment at the end of time, is biblical to the core. The pagan world has always held to some version of cyclical time, or as Mircea Eliade has called it, the myth of the eternal return. The centrality of this theme in pagan literature has provided Eliade with seemingly endless quantities of citations for his stream of books on comparative religion. 1 Ludwig Edelstein’s book, The Idea of Progress in Classical Antiquity (1967), hardly refutes the traditional view of ancient philosophy as being essentially pessimistic and cyclical. The most Edelstein proves is that a few of the Classical authors, such as the Roman, Pliny the Elder, told their followers not to lose hope, that things might continue to progress over time. His impressive command of the sources only reinforces the case for the Hebrew-Christian origins for the idea of linear, unidirectional human progress, since he could produce so few Classical sources that even vaguely hinted at the possi- bility of long-term linear development. The faith of Christians, espe- cially after Augustine, in the irreversible nature of time, is one of the most important facts in human history. This is not to say, however, that early Christianity as a whole was characterized by its defense of the idea of long-term earthly progress. One important tradition was that of the fourth-century church histo- rian, Eusebius, whose writings were laudatory of Emperor Constantine, 1. A partial listing of Eliade’s books dealing with the idea of historical cycles and cosmic regeneration would include: Cosmos and History: The Myth of the Eternal Return (1959); Myth and Reality (1963); The Two and One (1962); The Sacred and the Profane (1957); The Forge and the Crucible: The Origins and Structures of Alchemy (1956); Rites and Symbols of Initiation (1958), all published by Harper Torchbooks. See also, Patterns in Comparative Religion (New York: Sheed & Ward, 1958). 6 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 and who believed the Constantinian order was the beginning of the expansion of God’s kingdom on earth. On the other hand, Augustine’s pessimism concerning the fate of Rome led him to give up hope in lin- ear development of earthly kingdoms. The progress we can expect is strictly spiritual; Christ’s church will advance, while the kingdoms of men will rise and fall. Robert W. Hanning’s book, The Vision of History in Early Britain (1966), contrasts these two eschatological traditions. The Eusebian position could {2} be called early postmillennialism, while Augustine’s position is basically amillennial. Luther’s position was Augustinian and pessimistic concerning earthly affairs. 2 Calvin’s was ambivalent, although Greg Bahnsen’s dis- cussion of Calvin’s eschatology indicates that there were many passages in his writings that were unquestionably postmillennial. 3 The interpre- tation of Calvin as a strictly amillennial thinker, argued by Heinrich Quistorp, must be drastically qualified as a result of Bahnsen’s work. 4 The Puritans of the seventeenth century, especially those who came to New England, held to a “Eusebian” position, at least in the first generation (1630–60). They believed in historical progress. The call to spiritual and physical battle issued by Edward Johnson’s Wonder-Work- ing Providence of Sions Saviour in New England (1654) was the battle cry of that first generation—confident in the coming external victory, constructing the “city on a hill” that all the world would see as the out- post of the New Heavens and the New Earth. The dynamic of history, meaning historical optimism, was supplied by postmillennial eschatol- ogy. In an important essay on the debate between the Rev. John Cotton, the intellectual leader of the first generation in New England, and Roger Williams, the opponent of the New England civil government, Sacvan Bercovitch writes: 2. George F. Hall, “Luther’s Eschatology,” Augustana Quarterly 23 (1944). Cf. T. F. Torrance, Kingdom and Church (London: S.P.C.K., 1956), chap. 2. 3. Greg L. Bahnsen, “The Prima Facie Acceptability of Postmillennialism,” Journal of Christian Reconstruction 3, no. 2 (Winter 1976–77). 4. Heinrich Quistorp, Calvin’s Doctrine of the Last Things (Richmond, VA: John Knox Press, 1955). Editor’s Introduction 7 A Chalcedon Publication [] 3/30/07 ... Cotton, like Eusebius, thought himself part of a great collective endeavor. In this endeavor the New England theocrats attempted to join two seemingly incompatible doctrines: the national covenant, by which a group of men enter voluntarily into a pact with God, and the covenant of grace, by which God mysteriously determines to redeem certain individuals.... The national covenant emphasized the Lord’s promise to Abraham, which materialized in the Israelite state; after the Hebrews’ apostasy, the promise was renewed, this time in aeternum, by Christ to His church. The renewal antitypes the earlier agreement; historically, it establishes a developmental connection between two elect communities. Seen in this double aspect, the New World theoc- racy becomes a collection of saints whose public contract reflects the progress of human history and by the same token is mystically fore- ordained, like the covenant of grace. 5 Believing in the possibility of earthly progress prior to the second coming of Christ at the final judgment, the Puritans had a perfect rea- son to devote {3} themselves, as individuals and as a holy common- wealth, to the reconstruction of all human institutions. In the area of charity, for example, the Puritan tradesmen and merchants of London began setting up schools, orphanages, poorhouses, hospitals, and numerous other charitable institutions. W. K. Jordan’s multi-volume study of the outpouring of charity in England in the Puritan era stands as a lasting testimony to what the Puritans accomplished. Jordan was astounded at what he found—the sheer volume of giving. 6 The vision of Christian reconstruction was a motivating factor on both sides of the Atlantic. The Puritans also possessed the tool of Christian reconstruction, a concept of biblical law. It was God’s holy law which would provide them with the outline of the godly society, as well as the means for establishing it, they believed. The New England Puritans of the first generation were especially determined to rebuild human institutions in terms of Old Testament law. The optimism concerning the possibilities of progress on earth and the construction of a holy commonwealth 5. Sacvan Bercovitch, “Typology in Puritan New England: The Williams-Cotton Controversy Reassessed,” American Quarterly 19 (Summer 1967): 181–82. 6. W. K. Jordan, Philanthropy in England, 1480–1660 (New York: Russell Sage Foundation, 1959). This is his summary volume of a multi-volume investigation. It was published in England simultaneously (George Allen & Unwin). 8 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 combined with their faith in a law-order that was in conformity to the mind of God and His creation to produce a culture that was highly favorable to social change. Nevertheless, there was not complete agreement among all Puritans, not to mention the splintering sects in England, concerning the proper handling of natural law, revealed law, and human experience. The medieval rationalism of classical education in English universities col- ored the intellectual outlook of the Puritan divines. By the end of the seventeenth century, as Puritans began to abandon formal Protestant scholasticism, a new version of natural law, the mechanical-mathemat- ical universe of Newtonian logic, was substituted for the older rational- ism. This transition from “ancients to moderns” substituted new philosophical problems for the old ones. The dualism between nature and grace (autonomous reason and nonrational salvation) was steadily abandoned, only to leave Puritan thinkers facing a new dualism between nature and freedom (mechanical causation and autonomous personality). 7 That they did not see the threat of the new rationalism in 1700 is not surprising, but the substitution of Newtonian logic for medieval logic did not solve the pressing questions of the scope of bib- lical law and its applications in society. The second generation in New England steadily abandoned both the optimistic eschatology of the first generation—shifting, more and more, from Eusebius to Augustine, or in some cases, to premillennial chiliasm—and the older generation’s confidence in the straightforward applicability of {4} biblical law. The version of biblical law imported by the first generation was deeply influenced by medieval scholastic cate- gories, especially in the area of economics. When this medieval guild socialism proved unworkable in a series of experiments from 1630 to 1676, the second-generation preachers began to adopt more general- ized criticisms of social developments in New England. Pietism began to replace the older reconstructionism of the earlier settlers, while social pessimism replaced the earlier optimism. The result was a shift in political and cultural power to the merchants and lawyers, who were the beneficiaries of the extraordinary economic growth that had been 7. Cf. Herman Dooyeweerd, In the Twilight of Western Thought (Philadelphia: Presbyterian and Reformed, 1960), chap. 2. Editor’s Introduction 9 A Chalcedon Publication [] 3/30/07 produced by an ideology of expansion coupled with free (or inexpen- sive) land and relatively free trade. The old semi-medieval categories of social thought that the first generation had assumed were in confor- mity to the Old Testament’s law-order could not contain the social change generated by Puritan concepts of thrift, hard work, and the sub- duing of the earth to the glory of God. In England, the restoration of Charles II brought an end to the commonwealth experiment. The Puritan movement no longer could be directed along political lines. In 1688, the Glorious Revolution brought Parliament unchallenged power, and the strictly theological issues faded from the political scene. The secularization of culture began in earnest, with Arminianism (Locke) and deism coming into their own. The Puritan movement fragmented and turned inward. The vision of a Puritan holy commonwealth grew dim. Puritanism nevertheless had left its mark on English and Western culture. The essay by R. J. Rushdoony shows how important the Puri- tan doctrine of the priesthood of all believers was for freeing the indi- vidual from both church and state hierarchies. It was the Puritan movement which developed this doctrine most fully in the seventeenth century, and the spiritual heirs of Puritanism took it several steps fur- ther. If grace is free, God is sovereign, and human conscience is free from priestly domination, then the role of the institutional church is ministerial, not sovereign. “God alone is Lord of the conscience, and hath left it free from the doctrines and commandments of men, which are, in anything, contrary to His Word,” states the Westminster Confes- sion (chap. 20, sec. 2). This set free the priesthood. Rushdoony writes: “The new priesthood now had its priestly ordination papers in hand, the Bible, and the consequences in Britain were revolutionary.” The same was true in America. This was the antithesis of the divine right of king or clergy. It was this fear of church-state absolutism that led the colonial Americans to include the First Amendment in the Constitution—not to deny the relationship between Christian religion and state, but to limit the possibilities of an authoritarian ecclesiastical-state fusion. The First Amendment was a response to a religious demand, one which was Christian in character, {5} not deist. The order of political life, like all other life, would be imposed by the priests below, not the church-state 10 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 hierarchy above. The Great Awakening of the 1740s affirmed this doc- trine a generation before the Constitution. Jonathan Edwards revived postmillennialism (though without returning to the idea of Old Testa- ment law), and optimism returned to American preaching generally. “With the Great Awakening,” Rushdoony writes, “there was a growing break with civil religion. Both church and state still had to be Christian, but the key was no longer a powered establishment but a priestly peo- ple transforming institutions and society by their own regeneration and progressive sanctification.” Pietism and Neoplatonism, with their call to retreat from the evil world, eventually undermined eighteenth- century postmillennial evangelism and disarmed the doctrine of the priesthood of all believers, “but not before that priesthood radically directed history.” Charles Dykes takes up the question of science. Prior to the Reformation, science was burdened by medieval notions of logic, which meant Aristotelian or Platonic logic. The dualism of nature and grace separated the two realms, making it more difficult for scientists, especially experimental scientists, to pursue their work. Their work was seen as second-best, something of less value than an ecclesiastical calling. Protestantism changed all this forever. The spell of classical sci- ence, which had always been static, theoretical, and devoid of world- constructing vision, was broken by the Puritan challenge to Rome’s authority. Puritans stressed the creation story. God is interested in this world, for He created it and sustains it. The study of His creation is the study of His providence. The totally sovereign God of Calvinism controls everything, which implies that there is an inescapable order in the cre- ation. This order can be studied by man, who is made in God’s image. Whereas medieval Catholicism had tolerated science, the Puritans encouraged it. Dykes cites Robert Merton’s findings that a high per- centage of the members of the late-seventeenth century’s Royal Society in Britain were Puritans or grew up in Puritan households. The Puritan doctrine of the calling helped create an atmosphere favorable to scientific development. E. L. Hebden Taylor calls attention to the importance of this doctrine for the development of scientific equipment, so important to modern experimental science. The calling gave new meaning and social prestige to manual workers, and these Editor’s Introduction 11 A Chalcedon Publication [] 3/30/07 men were instrumental, literally, in creating modern science. He, too, relies on Merton’s work, and cites Merton’s discovery that of the 92 for- eign members elected to the Paris Academy between 1666 and 1883, 80 were Protestants. (Actually, it was first discovered by a French statisti- cian, de Candolle, and Merton passes along his findings.) The Puritans wanted to conquer the world. Law, including scientific {6} law, was understood to be a tool of conquest. This impulse broke down a centuries-long fatalism, Taylor argues. The earth may lawfully be developed by man for God’s glory and the benefit of other men. What undermined the Puritan impulse in science was a growing secularism. The autonomy of natural law reasserted itself in the late seventeenth century. Natural law, not the Bible, became the highest sci- entific court of appeal. This was tantamount to a depersonalization of the universe. It led to deism. Even the great educational reforms made by the Puritans were eventually secularized, as natural law—autono- mous natural law—steadily replaced the idea of revelational law. But the foundations of modern science had been laid, not by defenders of natural law, but by those who came in the name of a personal law-giver. The Puritans believed in the revealed word of God in His Bible. They also believed that His creation is orderly because it reveals His law- order. Men can therefore use reason and observation to create a coher- ent science of the external world. This scientific intellectual order serves as a tool of dominion. But what of the possibilities for success in this extension of God’s kingdom? Did the Puritans have a dynamic for history? James Payton answers affirmatively. This dynamic outlook was based on their eschatology, what we today call postmillennialism. He then explores the sources of mid-seventeenth-century Puritan post- millennialism. First, there was the influence of Martin Bucer and Peter Martyr Vermigli, the two mid-sixteenth-century continental Calvinists who came to teach at Oxford and Cambridge. Second, there was the influence of the annotations of the Geneva Bible, which followed Bucer’s exegesis of Romans 11. The Jews will be converted, and this will lead to an era of glorious triumph for all Christians. (This interpreta- tion has been defended by such scholars as Charles Hodge, Robert Haldane, John Murray, and others who are in the “Old Princeton” Pres- byterian tradition, to the dismay of amillennial Calvinists and the absolute horror of professional anti-semites who occasionally wind up 12 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 in Calvinistic churches—fortunately, a rare occurrence.) Third, the influence of William Perkins was an important factor in spreading the belief in eschatological optimism. Fourth, Thomas Brightman, Per- kins’s contemporary, was widely read by Puritans in the early seven- teenth century, and he was a postmillennialist. The Westminster divines (1646) and the writers of the Savoy Declaration a decade after the Westminster Assembly inserted postmillennial sections into their respective creedal formulations. The groundwork was established, by the mid-seventeenth century, for the efforts expended by the New England Puritans to create a holy commonwealth, the hoped-for first stage of an expanding earthly kingdom of God. Aletha Joy Gilsdorf ’s article surveys Puritan eschatology in New England in the first generation. It first appeared as chapter three of her Ph.D. {7} dissertation, “The Puritan Apocalypse: New England Escha- tology in the Seventeenth Century,” written under Professor Edmund Morgan of Yale University in 1965. (The original chapter was titled, “The New England Way.”) What she demonstrates is that postmillenni- alism reigned almost supreme in early New England. Her carefully documented survey concludes with this observation (among several): Thus from the very beginning, the bent of the colonists in Massa- chusetts Bay—unlike their brethren at Plymouth—was not to with- draw tem- poral but spiritual. Somehow this world’s institutions had to be refashioned to conform to Christ’s spiritual Kingdom.... It is no won- der that most of their English contemporaries reacted to this intention with incredulity and charges of fanaticism, for the New England design was precisely to make visible that which they admitted was invisible. She contrasts this view with Calvin’s, which is understandable, since in 1965 Dr. Bahnsen’s study of Calvin’s eschatology was not available, and the prevailing scholarship interpreted Calvin’s views as basically Augustinian. But her point is sound: the New England Puritans, Editor’s Introduction 13 A Chalcedon Publication [] 3/30/07 separated geographically from the mother country, could make the attempt to realize the postmillennial vision, in time and on earth. What Dr. Gilsdorf shows in her essay is that the Puritan concern for the purity of the institutional church did not end with the institutional church. The early sections of her essay are devoted to a detailed exposi- tion of the writings of Thomas Goodwin and John Cotton, specifically their expositions on the book of Revelation. She demonstrates the inseparable relationship between their understanding of the events of their day and the events foretold in Revelation. The purification of the institutional church was not understood by the Puritans as being an end in itself. This purification would, they believed, lead to a total transformation of the external culture around them. Purified theology and ecclesiastical practice would inevitably have implications for the success of the gospel in the world outside the institutional church. Dr. Gilsdorf is a scholar. She is not a neo-Puritan, nor has she involved herself in the debates of the neo-Puritan movement. But she has dealt with a most important aspect of the neo-Puritan movement, namely, church purity. She shows that this concern for purity by the seventeenth-century Puritans was all-encompassing. Purity, in their view, could not be called to a halt at the exits of the church meeting houses. The optimistic vision {8} of New England Puritans involved the whole world, not simply a single human institution, despite its importance as God’s monopoly of sacramental exclusiveness. This is the heart of the Puritan dynamic for history. They fully expected the extension of ecclesiastical purity to break the chains of anti-Christian culture just as surely as Samson burst the chains of his captors. Purity cannot be contained by the ungodly to one insignificant and suppos- edly shrinking aspect of society, meaning the institutional church. The Puritans, in short, were believers in comprehensive purification, not the narrow purification process of ecclesiastical reform alone. Readers interested in following through on a study of the postmillennialism of English Puritans should consult Iain Murray’s book, The Puritan Hope (Banner of Truth Trust, 1971), and J. A. de Jong’s book, As the Waters Cover the Sea: Millennial Expectations in the Rise of Anglo-American Missions, 1640–1810 (Kampen, Holland: J. H. Kok, 1970). This was de Jong’s doctoral dissertation at the Free Univer- sity of Amsterdam, and we can all be grateful that the Free University 14 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 has the outrageous, preposterous requirement that doctoral recipients publish their dissertations, usually at their own expense. (J. H. Kok, the firm that publishes most of them, is the major beneficiary of such aca- demic nonsense.) Once in a great while, a doctoral dissertation is worth reading, and this is one of those rare instances. Chapter 2 of de Jong’s book demonstrates how widely a mild post- millennialism suffused the Puritan movement from 1640 to 1670. He cites the eschatological writings of J. H. Alsted, the German Reformed theologian who had “an unusually great following in England in the crucial second quarter of the seventeenth century” (11), Thomas Brightman, Joseph Mede, Thomas Goodwin, John Owen, and the majority of Independents and Presbyterians, who held to at least a mild postmillennialism. John Owen, for example, “defined the kingdom of God as spiritual control of Christians which produced outward obedi- ence and conformity to Christ.” Furthermore, “In both England and America the mild hopes popularized by Owen and Cotton assumed a nationalistic dimension in conjunction with political and social devel- opments. They were a new version of Elizabethan expectations.” What was happening in New England, therefore, was only by degree more intensely theocratic and optimistic than developments in England, 1640–60. My own contribution is an extension of the work I presented in the previous issue of the Journal. 8 When the first generation in New England began to look for economic rules, they looked to the inherited medieval framework. Medieval guild socialism was sporadically and indecisively imposed {9} on the economy, especially during times of rapid economic change, in the name of God’s revealed law. This policy led to an increasing disenchantment with economic legislation gener- ally, since the controls invariably disrupted the economy even further. Yet the old theological language was difficult to abandon, and the sec- ond generation struggled mightily to return to the earlier, purer ways of the fathers. Economic growth and social change on an unprece- dented scale—the products of original Puritanism—could not be dealt with in terms of the canons of Protestant scholasticism. So a pessimism 8. Gary North, “Medieval Economics in Puritan New England, 1630–1660,” Journal of Christian Reconstruction 5, no. 2 (Winter 1978–79): 153–93. Editor’s Introduction 15 A Chalcedon Publication [] 3/30/07 set in among the second generation, and the sermons became pietistic. The call for specific reforms in the economic sphere diminished, for Puritan preachers no longer knew what to do, specifically, about the economy, apart from prohibiting wigs (which always was ignored by everyone) and tavern frequenting. Their irrelevance in the area of eco- nomic theory was evident to everyone by the 1680s. Simultaneously, the old postmillennialism was abandoned by most preachers—at least the majority of those who went into print on eschatological matters—leaving the Puritan system without a convinc- ing dynamic for history. The churches could no longer command the respect that they once had in New England. With optimism gone, and faith in the inherited version of medieval economic law no longer taken seriously, the leadership of New England steadily shifted from pastors to lawyers, politicians, and merchants. A process of seculariza- tion hit New England, too. This process of secularization must not be misunderstood. It was not that deism flooded New England. Deism never did flood the American colonies; it was, in the late eighteenth century, an intellectual position held by a tiny handful of educated religious skeptics. This seculariza- tion process was far more the product of the new faith in autonomous laws than anything else. The clergy were leaders in this movement. Cotton Mather, grandson of John Cotton, a premillennialist, a pro- moter of voluntary self-help societies, and the most widely published man in American colonial history, made the following statement in 1711: “The light of reason is the work of God; the law of reason is the law of God; the voice of reason is the voice of God.” 9 His book, The Christian Philosopher (1721), was a defense of the Newtonian science of astronomy, in which he cited experts on the fact that there is life on other planets and their satellites, and that the speed of light is anywhere between 9,000 miles per second and 130,000 miles per second. 10 With the clergy taking the lead in the rationalization of intellectual catego- ries, it became difficult for them to defend a uniquely Christian recon- struction and development of social institutions. As Clifford K. 9. Cited by Josephine K. Percy, “Introduction,” Cotton Mather, The Christian Philosopher (Gainesville, FL: Scholars’ Facsimiles & Reprints, [1721] 1968), v. 10. Ibid., 20. 16 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Shipton concludes, “The most striking social phenomena of these {10} years [1680–1740] is the decline of clerical authority and of the relative importance of religion in New England life.” 11 It was out of this decline that the Great Awakening emerged. An anonymous critic supplies insight into the nature of some of the objections raised verbally by several “reprinting neo-Puritans,” though we hope not all of them. The commitment of the Journal to the social ethic of Puritanism, meaning the broad sweep of applied Puritan theol- ogy outside the sanctuary, has alienated at least one of those who claim to be devout followers of Puritan theology. The Journal has called attention to this neglected aspect of Puritan thought—neglected, at least, by the “reprinting neo-Puritans”—and has pointed to the con- tinuing responsibility of contemporary Christians to follow through on the Puritan social heritage, not just in the pulpit, but outside the insti- tutional church. Our critic has made it clear just how demonic he thinks the Journal’s perspective is. Judy Ishkanian presents a well-rounded biography of Oliver Crom- well, the leader of the Puritan forces against the tyranny of the English church and state in the mid-seventeenth century. This two-decade period literally changed Western civilization, and it was Cromwell, above all, who was instrumental in changing it. His unquestioned com- mitment to Puritan theology presents a problem for neo-Puritans of today’s sanctuary, just as it did for Puritans of the sanctuary in his own day. He compelled them to take part in the central historical events of their day—a role not always relished by those seeking the protection of officially ordained social neutrality. He took Puritan theology outside the narrow confines of the institutional church, forcing men to choose sides. He chose to deal with inescapable social and political issues in terms of Puritan theology, and that theology, then as now, is a theology of social relevance. Ishkanian writes: As the Civil War progressed, the Independents were to be found as well represented on the battlefields as the Presbyterians were in Parlia- ment. However others might view the challenge of war, the Puritans did, with one heart, regard it as a signal from God that at last He was 11. Clifford K. Shipton, “The New England Clergy of the ‘Glacial Age,’ ” Publications of the Colonial Society of Massachusetts (1937), 46. Editor’s Introduction 17 A Chalcedon Publication [] 3/30/07 going to advance His kingdom on earth. The Lord was calling His own servants into battle to subdue and overcome the Antichrist, whom Puritans on both sides of the Atlantic believed was either Charles I or Archbishop Laud. At last, the great war of faith raging on the conti- nent (the Thirty Years War), which they had viewed from afar for so many years, was coming to English soil. Whatever the commitment of others, there was no hesitation on the part of the Puritans, with Crom- well resolutely in their number, to answer the momentous opportunity that God was providing His own elect to bring righteous government to England. Those who would have preferred to avoid such open choices in life {11} no doubt resented Cromwell. Certainly in our own day many of those who claim to be the representatives of the Puritan tradition have systematically neglected mentioning Cromwell, the choices he made, and the stands that he believed he was compelled to take. One might conclude that Cromwell never existed, or that men like John Owen never came to his defense, or that virtually the whole of the Puritan movement never backed him. This man of action had too many flaws, made too many mistakes, and took too many controversial stands to bring comfort to those who claim to be today’s Puritans. Ishkanian’s study reveals Cromwell as a military genius. His cavalry tactics revolutionized warfare in his day. His ability to command men in battle time and again baffled his opponents, including “no-win” gen- erals in Parliament’s army. Those who have no taste for victory seldom make good commanders. Cromwell expected victory, planned for vic- tory, and finally attained victory on the military battlefield. A revolution is not a pleasant series of events. The issues of any era are never easy to sort out, and Cromwell made decisions in the face of shifting alliances and momentous problems that tenderhearted inheri- tors of his efforts may today blush about. Like other brilliant generals in history, his political leadership left much to be desired. Still, it was a time of chaos throughout Europe. He did not conduct the purges that the continent came to expect, and which are basic to the revolutions of secular humanism, from France in the 1790s to the Soviet, Chinese, and Cambodian bloodbaths in our century. He acted like a general, tol- erating sometimes only limited opposition. But successful revolutions are seldom led by the fainthearted. They only write the histories once the dust is settled and the risks are over. 18 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Oliver Cromwell lived in a century in which religious issues were clearly political issues, in which men went into battle believing that God was on their side. It was a century in which secular humanism, the dominant religion of our era, was unthinkable, when the cry of “reli- gious neutrality” was as inconceivable as “ideological neutrality” is in our day. Rulers in the seventeenth century, like rulers in every era, did not know how to reconcile completely the need for freedom and the need for law and order. Every social order requires religious first prin- ciples to undergird it, and an attempt to suppress rival religious first principles sometimes necessitates the use of force if the law-order is not to disintegrate into anarchy. What those of Cromwell’s era recog- nized for the most part, and which Christians often refuse to recognize today, is that there can be no neutral law-order, and that any attempt to create one is a snare and a delusion, and plays directly into the incom- petent, rebellious hands of the secular humanists, who come to us in the name of zero religion, zero respect for the God of history, and zero respect for biblical law. They are aided in {12} their efforts by those who claim allegiance to the God of history, but who reject the idea that such a God prescribes a unique law-order, the enforcement of which He commands throughout history. What we need are reprints of Puritan sermons before Parliaments and armies. What we need are reprints of Puritan sermons preached in the heat of battle, in the very midst of the battlefields, both military and political. Such sermons exist in the archives. Without them, we will never understand Oliver Cromwell and his supporters, the Puritans. If someone in the camp of the “reprinting neo-Puritans” should pro- test against our charge of “pietistic selectivity” in the choice of which Puritan works to reprint (and more important, not to reprint), he might be wise to consider an announcement that appeared in the book notices section of the May 1970 issue of the Banner of Truth. The Corn- market Press proposed the publication of up to 1,000 volumes of Puri- tan sermons, tracts, and other materials, with the set to begin with the Fast Day sermons preached before Parliament, 1640–53. These ser- mons alone were expected to fill thirty-five volumes. Needless to say, there is a lot of material yet to be reprinted, not to mention absorbed and reconsidered, by those in the business of reprinting the works of the Puritans—representative Puritans. (The expenses, of course, are Editor’s Introduction 19 A Chalcedon Publication [] 3/30/07 horrendous; only one volume of the set promised by Cornmarket Press ever appeared. But let us not take seriously the lame reply of any “reprinting neo-Puritan,” who asks rhetorically: “But what else could we have published?” Lots, brother, lots!) A study of Puritanism’s history helps us to recognize a truth under- stood by Cromwell, a truth built into the creation itself: it is God’s law or chaos. The line has been drawn by God. There are those in the camp of the faithful who have chosen to blindfold themselves in the hope that their blindfolds will erase this line and permit them to retreat in comfort to the sanctuary. It cannot work. Blindfolds only make men stumble. The line remains intact. One of the lines which history has drawn is the line between Puritan social theory and its rivals. Cromwell and his followers realized that the affairs of life cannot be relegated to the hypothetical realm of the adia- phora, the “things indifferent” to religion. Modern Christianity has wound up baptizing a seemingly endless string of secular humanist fads in the name of “relevance” or “concern,” or “compassion.” To hold a position that almost anything secular humanists dream up for social and economic policy is somehow acceptable in the eyes of God—as acceptable as any other alternative—is to assert that almost nothing is fundamentally wrong with the world outside the institutional church. To believe, on the other hand, that something—indeed, practically everything—is wrong in society at large implies a belief that there are biblical alternatives that are morally correct and therefore socially mandatory. This, of course, is a categorical {13} denial of the tenets of Anabaptistic, pietistic antinomianism—an intellectual position unfor- tunately adopted by too many of those within the “reprinting neo-Puri- tan” movement. Some of the Calvinistic neo-Anabaptists have recognized the accuracy of the Journal’s presentation of Puritanism’s social heritage, and they have outspokenly abandoned that tradition. Furthermore, they have called on their socially antinomian brethren within the “reprinting neo-Puritan” movement to follow them in their rejection of that social heritage. 12 These Calvinistic neo-Anabaptist critics have a point. They under- stand how central Cromwell was to the Puritan movement of the Civil War period in England. How, then, can modern neo-Puritans ignore Cromwell’s contributions? One of them, contrary to the emphasis of 20 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the neo-Anabaptists, was religious toleration for all churches except the Anglicans (because of their political threat to Puritan rule) and the Roman Catholics. As Michael Boland pointed out in his 1961 Banner of Truth essay: “He was unflinchingly opposed to religious persecution and has justly been acclaimed as the champion of liberty of con- science.” And Boland accurately assesses the political alternative against which Cromwell and the Puritans revolted: “Episcopalian tyr- anny.” 13 Those who call themselves neo-Puritans should not flinch from an enthusiastic support of Cromwell’s heritage. They should be willing to affirm with Boland: We who love the name and the religion of the Puritans should thank the God of history that at such a time he raised up, in Cromwell, a man of transparent spirituality and practical wisdom. Had he not done so, the wrath of man would almost certainly have wrought polit- ical anarchy and religious strife. Such an outcome would have left an ineradicable blot against the name of Puritanism and the Gospel. 14 12. See, for example, John Zens, “More of Cromwell, Less of Gurnall,” Baptist Reformation Review 8 (1st quarter, 1979). Address: P.O. Box 40161, Nashville, TN 37024. Mr. Zens and his colleagues have revived one aspect of the Anabaptist movement, namely, a refusal to get involved in social and political issues by advocating the enforcement of biblical law by the civil government. They neglect the more familiar heritage of anabaptism, namely, the revolutionary movements that swept over Europe in the name of a new antinomian (and then tyrannical) kingdom of God on earth. To see where Anabaptist principles can lead, once men decide that it is impossible to remain neutral in a world in which all social, economic, and political policies are inevitably enacted in terms of religious principles, take a look at the pro-socialist, pro-liberation theology Anabaptist journal, the Other Side, especially the issues dealing with “economic exploitation”: Jan.–Feb. 1976 and March–April 1976. Address: P.O. Box 158, Savannah, OH 44874. Modern Anabaptists cannot stay neutral forever in social and political affairs. Their refusal to baptize anything is ultimately a willingness to baptize everything, but eventually they must pick and choose which social policies they wind up baptizing. Where they are not guided by biblical law, they baptize the policies drawn up by secular humanists. 13. Michael Boland, “Oliver Cromwell—The Puritan,” Banner of Truth, no. 23 (February 1961): 25. 14. Ibid., 29. A Chalcedon Publication [] 3/30/07 1. SYMPOSIUM ON PURITANISM AND PROGRESS A Chalcedon Publication [] 3/30/07 THE PURITAN DOCTRINE OF THE PRIESTHOOD OF ALL BELIEVERS Rousas John Rushdoony Despite a large number of important studies, the importance of the Puritans, and the Puritan premises in history, are far from adequately explored, or likely to be, because the Puritan story is as yet a far from finished one. While Augustinian and Calvinistic, the Puritans differed markedly from continental Reformed churches and were thus, while Reformed, not to be identified with the Reformed cause as a whole. They were clearly a separate movement, although having deep roots in Calvinism. Again, while Puritanism was not only a Protestant move- ment but a major force therein, its medieval and catholic roots were also strong. Its temper was hostile to the centralism of both Rome and Protestantism and more akin to feudalism and decentralization. Amer- ican federalism is a descendant of medieval feudalism. Although not many have agreed (or pursued the subject), Thomas Cuming Hall saw Puritanism as a continuation of the work of John Wyclif and the Lol- lards. 15 If true, this means that the pre-Reformation roots of Puritan- ism are deeper than normally held to be. To understand Puritanism, it is important to recognize the role of a key doctrine in shaping the Puritan mentality. It should be noted that Puritan doctrines agreed in the essentials of soteriology (salvation) and theology with Calvin and Luther. It was a difference of emphasis which produced differing results in the Christian life. Thus, Luther wrote, of the priesthood of all believers, in The Babylonian Captivity of the Church: As many of us as have been baptized are all priests without distinc- tion.... For thus it is written in I Peter ii, “Ye are a chosen generation, a royal priesthood, and a priestly kingdom.” Therefore we are all priests, as many of us as are Christians. But the priests, as we call them, are 15. Thomas Cuming Hall, The Religious Background of American Culture The Puritan Doctrine of the Priesthood of All Believers ministers chosen from among us, who do all that they do in our name. And the priesthood is nothing but a ministry, as we learn from I Corinthians iv, “Let a man so account of us as the ministers of Christ, and the dispensers of the mysteries of God.” 16 Luther indeed has a central role in the formulation of this doctrine, but, in the practical realm, Lutherans are about as docile in relation to their clergy as Catholics are. Calvin also set forth this same doctrine clearly and {15} strongly, but with about the same results. Some Reformed churches are almost as “priest-ridden” as their Catholic neighbors. Clearly, we have a problem here: a great Biblical doctrine is revived, but its practical consequences are none too great. Great differences mark Rome from Geneva and Wittenberg, but the priestly role of the laity is not one of them. This does not mean that the doctrine was without consequence. The priestly role of the believer as head of his household gained strong emphasis in both Lutheran and Calvinist circles, but not within the church as an institution. The reason appears in Calvin’s reference to the doctrine in the Institutes: For we, who are polluted in ourselves, being “made priests” (Rev. 1:6) in him, offer ourselves and all our services to God, and enter boldly into the heavenly sanctuary, so that the sacrifices of prayers and praise, which proceed from us, are “acceptable,” and “a sweet-smelling savour” (Eph. 5:2) in the Divine presence. This is included in the dec- laration of Christ, “For their sakes I sanctify myself ”; (John 17:19) for being arrayed in his holiness, he having dedicated us, together with himself, to the Father, we, who are otherwise offensive in his sight, become acceptable to him, as pure, unpolluted, and holy. This is the meaning of the “anointing of the Most Holy,” (Dan. 9:24) which is mentioned in Daniel. For we must observe the contrast between this unction and that shadowy unction which was then in use; as though the angel had said that the shadows would be dissipated, and that there would be a real priesthood in the person of Christ. So much the more detestable is the invention of those, who, not content with the priesthood of Christ, have presumed to take upon themselves the office of sacrificing him; which is daily attempted among the Papists, where the mass is considered as an immolation of Christ. 17 A Compend of Luther’s Theology Institutes of the Christian Religion The doctrine of the priesthood of all believers was of central impor- tance to the Reformers in attacking the validity of Rome’s doctrine of the priesthood. The only earthly priesthood after Christ’s death, resur- rection, and ascension is the priesthood of all believers; the church is led by a ministry, but it is a congregation of royal priests. The practical import for the institutional church or Christian synagogue of that con- gregational priesthood was not explored. Furthermore, the relationship of that priesthood to the soteriology of the Reformation was not explored. This link Puritanism has made. If grace is sovereign and free, then what happens to the church, its authority, and its traditions? If grace is sovereign, how then can priest, prelate, or king lord it over man? We should not forget the connections, in 1381, of the Peasants Revolt with Lollardy. Then or later the slogan was born, Who was then the gentleman? {16} The Lollards had stressed strong personal devotions, the study of and meditation on the Bible, and a high standard of sexual morality. They refused to leave such things as doctrine to a priestly class. Thomas Hoccleve wrote against this Lollard perspective thus: Hit is unkyndly for a knight That shuld a kynges castel kepe To babble the Bibel day and night In restyng time when he shuld slepe. 18 Lollardy threatened society with a break-up of the old order. If knights and commoners became Bible readers and babblers, then what would happen to authority? Lollardy was seen as a disruptive force, and, later, Puritanism was viewed similarly. True, many Puritans feared their own doctrine. New England’s Puritan hierarchy wanted the people to be a silent democracy within church and state alike, but, in spite of their inconsistency at this point, they did see the saints, in civil and ecclesiastical government, as a royal priesthood and democracy. 18. Gervase Mathew, The Court of Richard II (New York: W. W. Norton, 1968), 149. The Puritan Doctrine of the Priesthood of All Believers 25 A Chalcedon Publication [] 3/30/07 Cyril Eastwood has very ably summarized the “three great princi- ples” of Puritanism which “have their origin in the doctrine of the Priesthood of all Believers.” These three principles are: (a) That God’s free grace, mediated by the soul’s faith in Christ, is the essential root of human salvation. (b) That God’s will, revealed in His written Word and interpreted by His living Spirit, is the supreme law for human conduct both in the sphere of the Church and the world. (c) That the conscience must be free from merely human dictation and above all, from the enslaving rule of the priest. 19 Note that Eastwood sees the source of these doctrines in the doctrine of the priesthood of all believers. If God is sovereign, then man is not, and authority in church and state is ministerial, not sovereign. If God is sovereign, then grace is free and sovereign grace, and kings, priests, knights, and gentlemen give way to God’s royal priesthood. Then, too, the governing principle is not in man but in God and in God’s law- word. Accordingly, no man can bind the conscience, because God alone is the lord of the conscience. Thus, both liberty and conscience are to be defined, as are all things, by God and His word. The Westminster Confession of Faith, in chapter 20, “Of Christian Liberty, and Liberty of Conscience,” declares, in words clearly reflecting the Puritan faith: 1. The liberty which Christ hath purchased for believers under the {17} gospel consists in their freedom from the guilt of sin, the con- demning wrath of God, the curse of the moral law; and in their being delivered from this present evil world, bondage to Satan, and domin- ion to greater boldness of access to the throne of grace, and in fuller commu- 19. Cyril Eastwood, The Priesthood of All Believers: An Examination of the Doctrine from the Reformation to the Present Day (Minneapolis, MN: Augsburg Publishing House, [1960] 1962), 141. 26 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 nications of the free Spirit of God, than believers under the law did ordinarily partake of. 2. God alone is Lord of the conscience, and hath left it free from the doctrines and commandments of men which are in any thing con- science, power which God hath ordained, and the liberty which Christ hath purchased, are not intended by God to destroy, but mutually to uphold and preserve one another; they who, upon pre- tense of Christian liberty, shall oppose any lawful power, or the lawful exercise of it, whether it be civil or ecclesiastical, resist the ordinance of God. And for their publishing of such opinions, or maintaining of such practices, as are contrary to the light of nature, or the known principles of Christianity, whether concerning faith, worship, or con- versation; or to the power of godliness; or such erroneous opinions or practices, as, either in their own nature, or in the manner of pub- lishing or maintaining them, are destructive to the external peace and order which Christ hath established in the Church; they may lawfully be called to account, and proceeded against by the censures of the Church, and by the power of the Civil Magistrate. This amazing statement is all the more impressive when we realize that, even as Luther was upset by the Peasants’ Revolt, so too the West- minster divines were deeply concerned over the rising spirit of resis- tance, civil disobedience, and civil conflict. Section 4 of chapter 20 reflects this concern. Thus, on May 1, 1646, Daniel Cawdry preached to his fellow divines on 1 Timothy 1:19. He spoke with grief of the divi- sions and dissensions in the Church of England: “It is a sad observation that the professing part of the Church of England has been like a fair looking glass, all of one piece, only one image to be seen in it; but now, look at it, all {18} in pieces.” There was an irresponsible demand for lib- erty on all sides, and The Puritan Doctrine of the Priesthood of All Believers 27 A Chalcedon Publication [] 3/30/07 the common bait that catcheth is Antinomianism; the Anabaptist asks for liberty from the magistrate, from any superior ecclesiastical power, from the Sabbath; the Brownist seeks liberty from classes (i.e., pres- byteries), from superior power, and wants everyone to have a vote (in the congregation); the Seeker, who has lost all his religion, claims a toleration of all religion, and calls it liberty of conscience. 20 In spite of their fears of irresponsible liberty, or antinomian freedom, the divines all the same set forth the radical demands and freedom of man’s conscience when informed by God’s word and Spirit. We cannot understand the role of conscience in the Westminster theology apart from its doctrine of Scripture. It is popular now with the skeptics to call the Westminster Standards, and especially its view of infallibility, scholastic. Such a statement says nothing about the Westminster Standards and much about the person making it. The Westminster Standards placed God and His inscriptured word above man and his institutions, so that church and state were now alike under God and His word. Such a doctrine of the infallible and governing law-word of God requires liberty of conscience. Luther, Calvin, and Cranmer had chosen Scripture over the church. The logical step was now taken: “God alone is Lord of the conscience, and hath left it free from the doctrines and commandments of men which are in any thing contrary to his Word....” Thus, the, and the consequences in Britain were revolutionary. Later, in America, the new priesthood found greater freedom to realize itself, especially after the adoption of the U.S. Constitution. The multitude of differing churches on the American scene is a product of this doctrine, as is the First Amendment to the U.S. Constitution. Moreover, the Westminster Assembly’s stand on liberty of con- science made it very clear that it was anti-liberty when things are con- trary to the word of God, “to believe such doctrines, or to obey such commands out of conscience, is to betray true liberty or conscience; 20. S. W. Carruthers, The Everyday Work of the Westminster Assembly (Philadelphia: Presbyterian Historical Society, 1943), 71–72. 28 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 and the requiring of an implicit faith, and an absolute and blind obedi- ence, is to destroy liberty of conscience, and reason also.” Thomas Goodwin and Philip Nye, in their introduction to John Cot- ton’s The Keys of the Kingdom of Heaven (1644), wrote: In those former darker times, this golden ball was thrown up by the clergy (so called) alone to run for among themselves…. This {19} instruc- tion and guidance of their teachers, they are enabled to understand for themselves such other things as they are to join in the practice of, they do therefore further (many of them) begin more to suspect that some share in the key of power should likewise appertain unto them. 21 These are startling words, against the backdrop of continental royal absolutism and the divine right of kings in politics, and the power of the clergy in churches. That whole world of power and authority is seen as already a part of the past, as “former darker times.” The priest- hood of all believers even refers to “the clergy (so called)”! “The key of power” is now to be shared by the priesthood of all believers. In the American Colonies, the Puritan clergy held strongly to the doctrine, but were still fearful of the people’s priesthood. With the Great Awakening, Isaac Backus, the real and effective founder of the Baptist movement in America, made the doctrine basic to the Baptist churches. He held that “the common people claim as good a right to judge and act for themselves in matters of religion as civil rulers or the learned clergy.” 22 The key to the Baptist position for Backus was the 21. A. S. P. Woodhouse, ed., Puritanism and Liberty, Being the Army Debates (1647– 49) from the Clarke Manuscripts with Supplementary Documents (London: J. M. Dent & Sons, 1938), 293. 22. William G. McLoughlin, ed., Isaac Backus on Church, State, and Calvinism, Pamphlets, 1754, 1789 (Cambridge, MA: Belknap Press of Harvard University Press, 1968), 37. The Puritan Doctrine of the Priesthood of All Believers 29 A Chalcedon Publication [] 3/30/07 priesthood of all believers. “If we cannot know certainly that the Bible is true without understanding of Hebrew, Greek, and Latin ... then, alas, we are in a woeful case indeed.” Men would then be the prey of the cunning of learned priests and Arminians. “It is the privilege of God’s people to have the divine Spirit given to them to seal his truth in their hearts.” 23 Significantly, Backus looked at the Westminster Standards for sup- port; that Confession’s view of Scripture and the Spirit made possible his view of the priesthood of all believers: For though I have heard many (both ministers and others) assert that without the knowledge of the original tongues a man could not know whether he preached truth or falsehood, yet I shall not only assert, but prove, that every saint now has the same way to know the truth {20} and certainty of God’s Word that his people had of old, without which all the learning in this world will never bring any man to know cer- tainly the truth of the Scriptures. Christ told his disciples that the Spirit of Truth would guide them into all truth, John xvi, 13.... The way that the Thessalonians knew and received the Gospel not as the word of man but (as it is in truth) the Word of God was by its coming to them in power, and in the HOLY GHOST, and in much assurance, 1 Thess. 2:13 and 1:5; 1 Cor. 2:2, 4, 11–14. This is the only way by which God’s people in every age have known the truth and certainty of his Word which hath been given in to by Protestants in general both at home and abroad since the Reforma- tion. The Westminster Confession of Faith, after mentioning sundry arguments that may induce us to believe the Scriptures, say, “Yet notwithstanding, our full persuasion and assurance of the infallible truth and divine authority thereof is from the inward work of the Holy Spirit bearing witness by and with the Word in our hearts,” chap. 1, sect. 5. 24 Scripture, Backus pointed out, declares that believers are kings as well as priests. 25 In A Fish Caught in his Own Net (Boston, 1768), Backus pressed home the implications of this faith: 23. Ibid., 30, 103–4. 24. Ibid., 102–3. From “A Discourse Showing the Nature and Necessity of an Internal Call to Preach the Everlasting Gospel,” Boston, 1754. 25. Ibid., 156. 30 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Now if each saint is complete in him which is the Head of all wisdom and power, then they have no need of philosophers to see for them, nor of princes to give them power to act for God, but they freely confess with their mouths what they believe in their hearts, and so their hearts are comforted, being knit together in love, and are built up together as they have been taught. And as those saints had received the substance of what was shadowed forth in circumcision, and had declared in their baptism that they were dead to the body of sin and to the worship of the worldly sanctuary, the apostle says, Whereof if ye be dead with Christ from the rudiments of the world, why as though living in the world are ye subject to ordinances after the commandments and doc- trines of men. Which things indeed have a show of wisdom and humil- ity. 26 Does such a doctrine lead to disorders? On the contrary, Backus held, it is the denial of the priesthood of all believers which leads to what in the sight of God are the true disorders, a trust in the wisdom of men and the suppression of God’s working through His word and Spirit: Thus the Son of God plainly held forth the right which common peo- ple ever have to judge both of the doctrine and conduct of teachers, and the meek he will guide in judgment while those who receive not the love of truth but have pleasure in unrighteousness are constantly exposed to be given over to strong delusions. This being the order of Christ’s kingdom, hence see what a disorder it makes when common {21} Christians are denied the free liberty of examining their teachers and of acting according to their judgments in the affair; and also that ‘tis a great disorder to condemn and reproach any teachers, only because they are not owned by rulers or learned ministers, for by this very rule our glorious Lord was condemned as a deceiver and his fol- lowers stigmatized as ignorant, cursed people by men who were as famous in the world’s esteem, for learning, devotion, and order, as any in our day (John vii, 47–49). Nor is the disorder less on the other hand when any under a pretence of special teachings and divine influence crowd their improvements upon those who are not edified thereby, and plead their right to do so because they see further than others who they say can’t discern where they are, though (it may be) serious Christians do see them at the same time conduct in a flesh-pleasing way and even not providing things honest in the sight of men. 27 26. Ibid., 273. 27. Ibid., 281. The Puritan Doctrine of the Priesthood of All Believers 31 A Chalcedon Publication [] 3/30/07 Prior to the adoption of the U.S. Constitution and the First Amend- ment, there had been very real fears for the future of an independent Christianity in America. Bridenbaugh has shown that fear of the estab- lishment of the Church of England as the colonial state church, with an American bishop, was a factor leading to American independence. 28 It is surprising, therefore, that the religious sentiment concerning the new republic has been so greatly misunderstood. The new federal gov- ernment, from Washington through Buchanan, had very limited pow- ers. A minor bureaucrat in Washington, D.C., today exercises more power than presidents once did. Federal, state, and county govern- ments only rarely touched the life of the people. Hatch believes that somehow theology moved in a few years from the church to the civil order, and the result was a belief in what he calls a civil millennialism. 29 His thesis is a popular one, and a substantial body of writings castigate “America’s civil religion.” 30 There are, however, certain serious weaknesses in this argument. Let us take Hatch as an example, because his thesis is heavily documented with source materials, unlike others. Hatch sees a shift from a theologi- cal to a political or civil perspective which led eschatology to shift to the concept of a “civil millennialism.” Hatch’s knowledge of the sources is excellent; his appraisal of them is another matter. A key problem is that millennialism can mean a variety of things. It can mean not only postmillennialism, premillennialism, and amillennialism, but also a variety of other concepts which can include everything from the English seventeenth-century Fifth Monarchy {22} men to Mormonism and Seventh-day Adventism. The millennialism Hatch is concerned with is the revised postmillennialism of Jonathan Edwards and his suc- cessors. He is not as extravagant as some, who have tried to see as one such very different and even hostile concepts as postmillennialism, civil religion, manifest destiny, continentalism, imperialism, America’s 28. Carl Bridenbaugh, Mitre and Sceptre, Transatlantic Faiths, Ideas, Personalities, and Politics, 1689–1775 (New York: Oxford University Press, 1962). 29. Nathan O. Hatch, The Sacred Cause, of Liberty, Republican Thought and the Millennium in Revolutionary New England (New Haven, CT: Yale University Press, 1977). 30. See Russell E. Richey and Donald G. Jones, eds., America’s Civil Religion (New York: Harper & Row, 1944). 32 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 mission, and the like. Some clarification of these concepts is possible in Merk’s study. 31 Tuveson and Cherry give us confusion. 32 For Hatch, Edwards’ss postmillennialism supposedly underwent a change in the hands of his successors to become civil millennialism. Let us remember, however, that Edwards, in Some Thoughts Concerning the Present Revival of Religion in New England, has a section on “The latter-day glory, is probably to begin in America” (part 2, sec. 2). Indeed, Cherry used portions of this to place Edwards in the whole tra- dition of civil millenarians, whereas Hatch exempts him, because the method for Edwards was for him exclusively revivalism. Let us see first what Edwards had to say: cre- ation out of nothing; agreeable to Hos. 1:10. “And it shall come to pass, that in the place where it was said unto them,. 32:15. 31. Frederick Merk, Manifest Destiny and Mission in American History (New York: Alfred A. Knopf, 1963). 32. See Ernest Lee Tuveson, Redeemer Nation: The Idea of America’s Millennial Role (Chicago: University of Chicago Press, 1968), and Millennium and Utopia: A Study in the Background of the Idea of Progress (Gloucester, MA: Peter Smith, 1972). See also Conrad Cherry, ed., God’s New Israel: Religious Interpretations of America’s Destiny (Englewood Cliffs, NJ, 1971). The Puritan Doctrine of the Priesthood of All Believers 33 A Chalcedon Publication [] 3/30/07 “Until the Spirit be poured from on high, and the wilderness become a fruitful field.” And chap. 41:18–19. “I will open rivers in high places, and fountains in the midst of the valleys: I will make the wilderness a pool of water, and the dry land springs of water. I will plant in the wil- derness the cedar, the shittah-tree, and the myrtle, and {23} oil-tree: I will set in the desert the fir-tree, and the pine, and the box-tree together.” And chap. 43:20. “I will give water, young- est, and weakest part of it, where the church of God has been planted last of all; and so the first shall be last, and the last first; and that will be fulfilled in an eminent manner in Isa. 24:19. “From the uttermost part of the earth have we heard songs, even glory to the righteous.” 33 Revivalism and evangelism were indeed basic to what Edwards saw as the means to this fulfillment, and revivalism and evangelism remained as basic to the American scene. But we fail to understand the particular importance of evangelism to America if we think of it apart from the doctrine of the priesthood of all believers. The Great Awakening, in fact, aroused more than a little hostility and distress because the laity now began to make religion their concern. They judged their pastors, civil authorities, and professors in terms of the requirement that every man manifest grace and the workings of the Lord in his life. No longer was it the duty of the laity merely to listen silently and obey: they were now an aggressive priesthood. There were indeed disorders, but there was now a nonecclesiastical Christianity abroad. Insubordination motivated by religion, once the exception, now became commonplace. The famous episode of David Brainerd’s expulsion from Yale is illustrative of this. When Brainerd was asked his opinion of a tutor, Whittesley, Brainerd replied, “He has no more grace than this chair.” When Brainerd declined to retract his statement, he was expelled. The point of the Great Awakening was that the Holy Spirit was now at work among the people of God. This had repercussions in every area of life. This meant that the people now were God’s instruments in church and 33. The Works of Jonathan Edwards, vol. 1 (Edinburgh: Banner of Truth Trust, [1834] 1974), 381–82. 34 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 state: it meant “power to the people,” republicanism, and a strong stress on the necessity of virtue on the part of the people. As Samuel Cooper declared in a sermon of 1780, cited by Hatch, “Virtue is the spirit of a Republic; for where all power is derived from the people, all depends on their good disposition.” 34 Moreover, what these Christian leaders, whom Hatch accuses of civil millenarianism, celebrated in America was not America as such, or the state, but the freedom from the state control of religion common to Europe, the freedom of the Christian man from church and state into his priesthood in every realm. The fear of a state church establishment imposed by the crown gave way to the freedom for Christianity spelled out by the First {24} Amendment. The First Amendment was adopted in response to a religious demand: there was a fear of any church-state connection. 35 Whereas in Europe the church-state connection was strong, and the priestly role of the believer nonexistent, minor, or sup- pressed, in the new United States it was now free to manifest itself. This fact alone was commonly seen as a major step towards Christ’s king- dom. Because of the doctrine of the priesthood of all believers, the hope of society was seen not in an established order imposed from above, but as an order created by the priests below. Presbyterian Sam- uel Miller, in Christianity the Grand Source, and the Surest Basis, of Political Liberty (1793), declared: The truth is, that political liberty does not rest, solely, on the form of government, under which a nation may happen to live.... Human laws are too imperfect themselves, to secure completely this inestimable blessing. It must have its seat in the hearts and dispositions of those individuals which compose the body politic; and it is with the hearts and dispositions of men that Christianity is conversant. When, there- fore, that perfect law of liberty, which this holy religion includes, pre- vails and governs in the minds of all, their freedom rests upon a basis more solid and immoveable, than human wisdom can devise. 36 Men who had recently feared the imposition of bishops and an English establishment were thus rejoicing that the new civil order represented 34. Hatch, Sacred Cause, 105. 35. See Robert Allen Rutland, The Birth of the Bill of Rights, 1776–1791 (Chapel Hill, NC: University of North Carolina Press, 1955), 127. 36. Ibid., 110n. The Puritan Doctrine of the Priesthood of All Believers 35 A Chalcedon Publication [] 3/30/07 an absence rather than a power, and because now true revival could do its work. John Murray, in Nehemiah, or the Struggle for Liberty Never in Vain (1779), saw the glorious future in terms of the rule of God’s law, or Biblical law, in the state, and the rule of faith and obedience in the hearts of the people. In brief, he stated the classic position of postmillennialism, no new doctrine as Hatch seems to think. Murray declared: ... the security of the body is the government’s charge—that can never be had where the reins are laid on the neck of men’s lusts, and immoralities are under no public restraint—the system of laws that affixes no penalty to theft, adultery, murder, and the like enormities, is, justly regarded as designedly opening the widest door for undoing the State: nor is it easy to say why those should be punished whilst blasphemy and profaning the name of God—whilst public mockery of his word, his day and his worship, enjoy the sanction of a public license; and for ought that appears, may plead the shelter of legal establishment. It is hard to investigate any ingredient in the acts restrained more truly pernicious, than is the whole nature of those that go free, unless we conclude that the first table of God’s law is not as binding and authoritative as the second—or that obedience to the one exculpates the breacher of the other, or that killing the body is a greater crime than {25} destroying the soul; or in a word, that every member may be ruined and the community safe. 37 Because Christianity sets forth a sovereign God who claims jurisdic- tion over every area of life, including the civil, it is necessary for the believer to assert the sovereign crown rights of Christ the King over church, state, and every other realm. The so-called civil millenarians were simply Christians rejoicing in a great step forward in the history of the faith as they saw it, the freedom of the church and state from controls of either one by the other, and the freedom of the Christian man to discharge his priestly, royal, and prophetic offices. Not surprisingly, one of the consequences of the new republic was the rapid growth of two groups, the Methodists and the Baptists, both of whom in those days placed great stress on the priestly role of the laity. Methodism then had a strongly lay basis; as Bishop William T. Watkins observed in 1947, “For Methodism there was no rabble.” 38 Even more, the Baptists became the American church. While Baptists 37. Ibid., 115f. 36 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 can be criticized for their neglect of the doctrine of the covenant and like matters, it must be recognized that, in their development of the doctrine of the priesthood of all believers, they have been uniquely a representation of a key aspect of the Reformation. Moreover, in every area of life, this priestly power has been mani- fested. The characteristic American initiative in education (especially now in the Christian school movement), in economics, science, inven- tiveness, farming, and in other areas has roots in the Great Awakening and the Reformation doctrine of the priesthood of all believers. Revivalism and evangelism are American phenomena to a great degree, although not lacking in Britain also, and now elsewhere, as a result of missionary influences. Both for Rome and Geneva, and cer- tainly for Wittenberg, Reformation and counter-Reformation were civil concerns; we can indeed speak of civil religion and civil millenarianism when we describe Europe’s old order. The future of Christianity and of civil government was seen as requiring the imposition from above of a particular form of civil religion. With the Great Awakening, there was a growing break with civil reli- gion. Both church and state still had to be Christian, but the key was no longer a powered establishment but a priestly people transforming institutions and society by their own regeneration and progressive sanctification. Earlier, Pietism had called for withdrawal from an evil world. Pietism and Neoplatonism were later to infect and disarm the Puritan concepts of {26} the priesthood of all believers and postmillen- nialism, but not before that priesthood had radically directed history. The postmillennial faith was the natural and theological counterpart of the doctrine of the priesthood of all believers. Premillennialism looks to a supernatural deliverance or rapture out of history. Amillen- nialism had its origin in Augustine, who, influenced by Neoplatonism and Manichaeanism, could see “no City of God in a temporal sense.” 39 Man’s only hope was in a fortress church, and hence amillennialism moves to build up a power-church to hold out against an evil world. 38. Charles W. Ferguson, Organizing to Beat the Devil: Methodists and the Making of America (Garden City, NY: Doubleday, 1971), 93. 39. Franklin L. Baumer, Modern European Thought, Continuity and Change in Ideas, 1600–1950 (New York: Macmillan, 1977), 120. The Puritan Doctrine of the Priesthood of All Believers 37 A Chalcedon Publication [] 3/30/07 Postmillennialism sees a necessary and a required triumph of the king- dom of God in history by means of God’s regenerating power, and by His law applied and made the life of man by a royal and a priestly peo- ple. It should therefore not surprise us that both postmillennialism and the doctrine of the priesthood of all believers were brought into central focus by Jonathan Edwards, the Great Awakening, and subsequent Christian leaders. They were merely different aspects of a common faith. The decline of one led to the decline of the other. Puritanism indeed represented a new development in the history of Christianity. More conservative in some respects than any other move- ment, its emphasis on the priesthood of all believers created a great, new, and radical impetus in history, especially in Britain and America, and, through them, in all the world. For this reason, the Puritan history is not only an unfinished one, but also a reviving one. A Chalcedon Publication [] 3/30/07 MEDIEVAL SPECULATION, PURITANISM, AND MODERN SCIENCE Charles Dykes Men who have assurance that they are to inherit heaven have a way of presently taking possession of the earth.—William Haller, The Rise of Puritanism, 162. The seventeenth century, a great watershed in Western history, marks the dawn of the distinctively modern world. New concepts and institu- tions arose in many areas. In the economic order, modern rationalized capitalism—as opposed to the older “adventure” capitalism (to use Max Weber’s distinctions)—became firmly established in northwestern Europe. In politics, the national state emerged triumphant over the feu- dal decentralized structure in many places. But among the events of this epochal era—Whitehead’s so-called “age of genius”—none was more dramatic and consequential than the rise of modern science. “The seventeenth century,” notes G. R. Cragg, “witnessed a major revolution in the intellectual outlook of Western Europe. Few areas of thought remained untouched; in none was the change so dramatic as in the world of science, and nowhere was the transformation more remarkable than in England.” 40 As the year 1600 approached, English scientists trailed their counterparts on the Continent; by the year 1700 they led all Europe in scientific progress. A fascinating debate among scholars in recent years concerns the role Protestantism played in the rise and development of modern sci- ence. Some argue it was absolutely essential; others contend it was of no positive consequence—that, in fact, Christian faith had to be over- come before modern science could flourish. But what explains the unequaled scientific transformation of England in the seventeenth century? In order to suggest an answer to this question, we will present a brief delineation of certain salient 40. Freedom and Authority (Philadelphia: Westminster Press, 1975), 36. Medieval Speculation, Puritanism, and Modern Science 39 A Chalcedon Publication [] 3/30/07 events in the history of science which bring us to the England of 1600– 1700; and second, we will review some of the crucial philosophical and theological presuppositions held by thinkers from the ancient pagans down to the early moderns. From these we will attempt to indicate the basis for our conviction that the {28} general worldview of Christianity was essential to provide the intellectual foundation from which mod- ern science could emerge. We will contend, moreover, that the Refor- mation made an important contribution to the presuppositional context so basic to the growth of experimental science. And finally, we will survey briefly the role of the Puritans in the progress of scientific endeavor. By way of introduction, let us consider some insights of Stanley Jaki. He writes: “... in a world history that had witnessed at least half a dozen great cultures, science had as many stillbirths. Only once, in the period of 1250–1650, did man’s scientific quest muster enough zest to grow into an enterprise with built in vitality.” 41 Jaki tells us why this was so:. 42 This was true of the pagans and Greeks with their cyclic view of his- tory. 43 The contrast with the Christian view, especially after the time of Augustine, is radical indeed. “The Christian,” observes Roland Bain- ton, “could never say of Christ what Aristotle said of Plato: that in another age there might be another Plato.... ‘Once and for all Christ died unto sin.’ ‘Once and for all He entered into the holy place.’ ‘Once and for all we are sanctified by the offering of His body.’ ” 44 As August- 41. Stanley Jaki, Science and Creation: From Eternal Cycles to an Oscillating Universe (New York: Science History Publications, 1974), viii. 42. Ibid. 43. Robert Nisbet, Social Change and History (New York: Oxford University Press, 1969), 35–36. Nisbet argues that the Greek idea was a theory of developmentalism, but admits: “No doubt there were Greeks and Romans who did indeed believe in recurrent cycles of the specific history of events of an Attica or Rome....” 44. Early and Medieval Christianity (Boston: Beacon Press, 1962), 8. 40 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 ine declared, “For once Christ died for our sins; and rising from the dead, he died no more.” That there are specific theological reasons for the stillbirths of sci- ence can be illustrated by considering China. Writing about 150 years ago, Yu-Lan Fung admitted “it was a state of mind that prevented sci- ence from taking roots in Chinese soil up to very recent times.” 45 The Chinese were obsessed with a cyclic view of the world and were addicted to astrology, 46 but ultimate failure turned on their answer to this question: was the world made by God, or is the world itself a god? They gave the wrong answer. The Chinese held to a conception of an organismic universe, and to the workings of chance spontaneity: this was part of the reason they never formulated a truly scientific concept of physical law. Joseph Needham, one {29} of the outstanding scholars of Chinese culture, has commented: “It was not that there was no order in nature for the Chi- nese, but rather that it was not an order ordained by a rational personal being, and hence there was no conviction that rational personal beings would be able to spell out in their lesser earthly languages the divine code of laws which he had decreed aforetime.” 47 Jaki remarks, with ref- erence to Needham, “a Marxist interpreter of science, it must have been a frustrating pill to acknowledge the crucial role played by faith in a personal Creator in the rise of modern science.” 48 Many of the same chains of darkness that gripped the Chinese also bound the Arabs. They made some advances: Islamic medicine, and in particular, the treatment of eye diseases, was well developed for its day, 49 but Islamic science only “made notable contributions to those parts of science which had ... little or nothing to do with the laws of the physical world at large.” 50 Like the Chinese, the Arabs held to an organ- 45. Jaki, 25. 46. Ibid., 36. 47. Joseph Needham, Science and Civilization in China (Cambridge University Press), vol. 2, 581, cited in Jaki, 42. 48. Jaki, 42. 49. Averroes, the great advocate of the Aristotelian philosophy among the Arabs, was a leading ophthalmologist of his time. 50. Jaki, 195. Medieval Speculation, Puritanism, and Modern Science 41 A Chalcedon Publication [] 3/30/07 ismic world picture; their thinking was dominated by mysticism and astrology. Throughout the Middle Ages and into modern times, Islamic thinkers tried to combine the teaching of the Koran with belief in God as Creator, Pythagorean number mysticism, the doctrine of world-soul, and the hierarchical ordering of the universe. This differs in essence little if any from an emanationist, pantheistic conception of the world. Let us turn aside now to consider a few of the more significant ideas and events in the history of scientific thought which led to the Scien- tific Revolution of the seventeenth century. We begin by noting that the idea that the sun is the center of the universe was not original to Copernicus. Aristarches (ca. 310–230 BC), the most inspired astrono- mer of the ancient world, had taught eighteen hundred years before Copernicus that the earth and other planets revolve in circles about a stationary sun; and he understood the moon revolves around the earth. Few people paid any attention. Some historians of science maintain that the first truly great scien- tific achievement of the human race was the development of the calen- dar. As commerce, agriculture, and the bureaucratic state advanced among the ancients, the need for a more predictable and uniform cal- endar, free from local variations and other irregularities, grew strong. Pursuant to this, Hammurabi (ca. 1800 BC) ordered that a common calendar be devised and made operative throughout his empire. The task was assigned the Babylonian astronomers, whose chief business (in common with their contemporary {30} star-gazers) was astrology. This commingling of rudimentary astronomy with astrological lore was encouraged by the Babylonian state, which believed the celestial bodies were gods who influenced not only weather, tides, and health, but also the fortunes of the state. Another significant event in antiquity was the development of num- bers and mathematics. A primary theme of Greek philosophy was the power of reason: the derivative idea grew up among them that mathe- matical axioms constituted the true principle of things; out of this came the classical ideal of abstract mathematics. Thus the Greeks conceived of mathematics as a system of general, abstract propositions whose connecting link was logic. 42 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The Greeks, however, were almost totally uninterested in employing mathematics to solve practical problems. Only in geometry did the Greeks excel; it was the Egyptians who devised arithmetical operations of division, addition, and subtraction, as well as the decimal system. (Curiously, the Egyptians never learned to multiply, nor did they con- trive a symbol for zero.) 51 The major premise of Pythagoras (ca. 580–500 BC) and his school was that “number is everything.” For the first time numbers were used to express basic relationships that had been observed in nature. 52 Plato (429–348 BC) in the Timaeus described the world in geometrical terms, declaring that when things are reduced to their simplest form, number evolves as the basic constituent of the universe—e.g., bodies are made up of surfaces, surfaces of lines, lines of points or numbers. Two thousand years later this Platonic view of mathematics, which pre- supposed that the world of nature was a mere approximation to the world of pure mathematics, had to be overthrown before modern sci- ence could emerge. The insight of R. G. Collingwood is of enormous significance: “The possibility of an applied mathematics is an expres- sion, in terms of natural science, of the Christian belief that nature is the creation of an omnipotent God.” 53 Mathematics came to Western Europe during the Middle Ages through the intermediation of the Arabs. The latter had built on the mathematics of the ancients, combining some Hindu innovations with several of their own. {31} Prior to the eleventh century, medieval Europe seems not to have had a mathematician who was not a Moor, a Greek, or a Jew. But the 51. Morris Kline, Mathematics in Western Culture (Oxford University Press, 1953). 52. Cf. Carl B. Boyer, The History of the Calculus and Its Conceptual Development (New York: Dover Publications, 1949), 1. “The Pythagoreans and Plato.” 53. An Essay on Metaphysics (London: Oxford University Press, 1940), 253. According to Galileo, “the book of nature is a book written by the hand of God in the language of mathematics.” Medieval Speculation, Puritanism, and Modern Science 43 A Chalcedon Publication [] 3/30/07 priests of the medieval church finally became interested in mathemat- ics for practical reasons: as custodians now of the calendar, they needed to learn mathematics (and astronomy). Despite its admixture with astrology, in learning to fix the year as the interval between successive repetitions of an astronomical event, ancient astronomy developed two basic scientific tools, observation and measurement. But seminal thinkers like Plato gravely undercut these simple anticipations of modern scientific method. For Plato, sci- ence and mathematics were purely intellectual activities, completely divorced from the observable world. 54 Aristotle used the method of observation in his biological studies, but completely ignored it in astronomy and physics. Like Plato, Aristo- tle thought that nature was a living organism, and that the heavenly bodies possessed life and initiative. 55 He believed the heavens were composed of a different kind of matter from that on earth. Following Empedocles, he thought that all earthly things were made of four ele- ments: water, air, fire, and earth; to accommodate his matter-theory of difference between the composition of celestial and terrestrial, he con- ceived a fifth element, the “quintessence”; everything composed of it possessed eternal unchangeability. Another field where Aristotle’s teaching long held the minds of sci- entific thinkers in bondage was his theory of motion. In Aristotelian theory, the celestial bodies all moved in perfectly circular orbits, each moving at the same uniform speed throughout its orbit. True, astrono- mers had great difficulty reconciling these ideas with the planetary movements they observed; that they tried so hard for so long is indica- tive of the immense prestige of Aristotle. Concerning motion, Aristotle taught that every material object has a motion of its own corresponding to the materials of which it is com- posed. All terrestrial elements move in straight lines (either up or down); the motion of the celestial bodies, being composed of the quintessential element, is circular and eternal; terrestrial motion, being rectilinear, is therefore violent and unnatural by contrast. 54. Cf. The Republic of Plato, trans. Allan Bloom (New York: Basic Books, 1968), 208. 55. Stephen Toulmin and June Goodfield, The Architecture of Matter (New York: Harper Torchbooks, 1962), 87. 44 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The continued movement of a projectile in flight, Aristotle assumed, can be attributed to its being pushed onward by the continuous force of onrushing air—i.e., moving forward the projectile displaces the air immediately in its path, which then rushes round behind to prevent a vacuum from forming. This explanation was logical—and dead wrong—but it {32} points to the reason for the appeal of Aristotelian physics, which “was not its superficial agreement with observations, but that it could ... be deduced from a few basic postulates.” 56 The Aristotelian cosmology posited a spherical universe which con- tinually rotated in a circle; at its center was the immovable earth, also spherical. Since the universe was divine, it must be spherical, the sphere being the perfect figure. It rotates necessarily in a circle; circular motion, having neither beginning nor end, is eternal. The earth, the center of the universe —in common with the center of all rotating bod- ies—is at rest. Thomas Aquinas (1225–1274) attempted to Christianize the philos- ophy of Aristotle, including his cosmology. In literature this medieval picture of the universe was most graphically painted in the Divine Comedy of Dante (1265–1321). C. S. Lewis, in his last book, The Dis- carded Image, brilliantly describes this cosmology: at the center is the spherical earth, with the earth surrounded by a series of transparent globes, one above the other. A luminous body is fixed in each of these spheres—i.e., a planet. Beyond is the realm of the stars, and beyond them, the First Mover, itself invisible. The First Mover, moved by its love of God, imparts to all the inner spheres. Medieval man believed in three hierarchies of angels, each hierarchy composed of three different kinds. These angels “were allotted different functions, and were associated with different parts of the cosmos: three grades operated in the outermost empyrean, three on the earth itself, and three in the intervening region.” 57 Beyond the outermost sphere was Heaven—the abode of God and all the elect. The astronomy of the Middle Ages was Ptolemaic. Ptolemy (AD 85– 165), while holding to the physics of Aristotle, thought physics irrele- 56. Jaki, 208. 57. Stephen Toulmin and June Goodfield, The Fabric of the Heavens (New York: Harper Torchbooks, 1961), 162–63. Medieval Speculation, Puritanism, and Modern Science 45 A Chalcedon Publication [] 3/30/07 vant to astronomy, so confined himself to mathematics. His system would reign supreme until the seventeenth century. There were several thinkers during the Middle Ages who attacked the Aristotelian notion that the earth is fixed, immovable. For example, while Nicole Oresme (1323–1382), bishop of Lisceaux, did not ulti- mately accept the rotation of the earth, his arguments were damaging to Aristotle and Ptolemy, and many of his ideas were taken over by Copernicus and Galileo. Copernicus (1473–1543) can best be described as a Ptolemaic revisionist: he was unhappy with the Ptolemaic system because of its complexity. He was following the Pythagorean idea that the ultimate truth about the universe must consist of simple and elegant geometri- cal relations. Ptolemy’s astronomy, Copernicus concluded, with its many circles and epicycles, was much too complicated to be true. {33} In 1512 Copernicus set forth the seven principles of his theory of the universe. Two of these principles are: that all planets circle the sun; and that the sun is stationary, its apparent motion caused by the rotation of the earth. Copernicus, still under the spell of Aristotle, could not con- ceive of noncircular motion by the planets, however. When his new world system was published in 1543, it contained thirty-four circles— Ptolemy’s had contained about eighty—so complexity was reduced, not eliminated. Kepler (1571–1630), devoted to the theory of Copernicus, was the first scientist to use mathematical methods to study the laws of plane- tary motion. By 1618 he had published the three laws that were to become the cardinal principles of modern astronomy. Two of these are: that the planets revolve around the sun in ellipses with the sun at one focus of the ellipse; and that each planet moves at a variable speed. From the eighty circles and constant speed of Ptolemy, and the thirty- four circles of Copernicus, now with Kepler we have seven ellipses and variable speed. Gone was the geocentric universe; gone were the logi- cally necessary circles of Aristotle. Archimedes of Syracuse (287–212 BC) is often called the father of the science of mechanics, in which he made pioneering studies. Around AD 500, a Monophysite theologian and critic of Aristotelian physics, John Philoponos, studied motion and devised an impetus the- ory. His ideas were picked up by the Parisian school of physicists in the 46 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 fourteenth century, chiefly Jean Buridan (ca. 1295–1358) and Nicole Oresme. Building on their ideas (though he failed to acknowledge this), Galileo (1564–1642) began his investigations into mechanics. While attending Mass one day, Galileo became intrigued with a swinging chandelier. This gave him the idea for a crude pendulum, using only a stone attached to a string; from this he discovered that the length of time required for one swing depended only upon the length of the string, not upon the weight of the stone. The pendulum, he reck- oned, was merely a special case of a freely falling body. In addition, Galileo measured the time required for objects of differing weight to roll down an inclined plane. From these experiments, he concluded that objects of different weight fall with the same acceleration in a vac- uum, and that this applies to all bodies throughout the terrestrial realm. Galileo was given to speculate that this might apply to the celes- tial realm as well. Aristotle had taught that a body would stop moving when the net force on it was zero; Galileo concluded that if all the forces acting upon a body balance out to zero, the body will nevertheless continue to move, and move uniformly. Galileo’s theory in essence is: it is as “natu- ral” for a body to move uniformly as it is for it to remain at rest. Clearly, the contention of Galileo that motion was as “natural” as rest contradicted Aristotle; and soon this insight was to radically change man’s thinking about physical causation and the nature of the universe. For if {34} it is as “natural” for a body in motion to continue moving on earth as it is in the heavens, the conclusion follows that there is no basic difference between the two realms. Around 1611, Kepler worked out his theory of lenses. Though little noted at the time, it was of enormous importance, because it produced a different attitude in the scientist toward his instruments. It was the telescope and careful observations of Tycho Brahe that Kepler built his astronomical theories on; and it was Galileo’s telescope that brought him into confrontation with the Roman Church. On the night of 7 January 1609, Galileo directed his telescope at Jupiter, and saw close to the planet three little moons. “These ‘Med- icean planets’ (as he named them in honor of the Medici, the ruling house of Florence) made it impossible any longer to argue that all the Medieval Speculation, Puritanism, and Modern Science 47 A Chalcedon Publication [] 3/30/07 bodies in the planetary system must be revolving around a single cen- ter. A major objection to the Copernican view was overcome.” 58 The reaction of the ecclesiastical and academic world to this discov- ery was swift and violent. The Aristotelians declared that what Galileo saw through his telescope were optical illusions; some claimed it was the instrument of Satan. How, they asked, could Jupiter suddenly acquire a bevy of moons? Had not Aristotle explained that the heavens were immutable? The Aristotelian-Ptolemaic cosmology, having reigned a thousand years, was in its death throes; the hierarchical concept of the universe, conceived by Aristotle and Christianized by St. Thomas, was finally shattered by the telescope. Neither the gates of God’s Empyrean Heaven nor the celestial beings responsible for moving the planets in their orbits could be seen. The telescope, moreover, helped to destroy the categorization of matter into higher and lower forms: the jagged, mountainous surface of the moon was obviously composed of the same matter as exists on earth. So much for Aristotle’s “quintessence.” In affirming the Copernican view, Galileo had set himself against the Aristotelian teaching of the church. In 1616 the Inquisition moved in, and Galileo was advised to abandon his Copernican opinions. After publication of his Dialogues on the Two Principal World Systems, Gali- leo was tried and found guilty in 1633; under house arrest thereafter, he died in 1642, the year Newton was born. 59 {35} Aquinas had Christianized Aristotle so well that when the authority of Aristotle in the area of astronomy and physics was called into ques- tion, many Christian theologians thought biblical truth was being denied. So completely had Aristotle and medieval Christian theology been harmonized in the Thomistic synthesis that the threatened over- throw of Aristotelian cosmology seemed to many theologians to be a rejection of biblical revelation as well. Hence the move against Galileo: 58. Ibid., 196. 59. Cf. George Salmon, The Infallibility of the Church (Grand Rapids, MI: Baker Book House, 1959), 229–52. Giorgio de Santillana, The Crime of Galileo (Chicago: University of Chicago Press, 1955). Jerome J. Langford, Galileo, Science and the Church, rev. ed. (Ann Arbor: University of Michigan Press, 1971). It was not until 1835 that Rome removed the works of Copernicus, Kepler, and Galileo from the index of prohibited books. 48 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the Aristotelian theologians realized that if the Copernican doctrines were sanctioned, this would seriously damage their own authority as guardians of orthodoxy by proving false what they had taught was true. The real issue in the trial of Galileo was not the truth of Holy Scripture, but rather the truth of Aristotle and the authority of the Aristotelian theologians. The medieval church had also followed the matter-theory of Aristo- tle; it was not until the seventeenth century that men would suspect that here too he was wrong. Throughout the Middle Ages, what chem- istry there was, was alchemy. Its foundation premises were as follows: (1) all matter is composed of a mixture of earth, air, water, and fire in varying ratios; (2) gold is the noblest and purest of metals; (3) any metal can be changed into another by a process called transmutation— changing the proportion of the four basic elements. The alchemists believed a base metal could be transmuted into gold by using an elusive substance called the Philosopher’s Stone. During the sixteenth century the leadership of alchemy passed from Islam to Europe. Paracelsus (1493–1541), a Swiss physician, turned his followers somewhat from their obsession with gold to the study of medicines: his approach served as a bridge between alchemy and chemistry as an exact science in its later development. When Robert Boyle in 1661 published The Sceptical Chemist, he swept away the Greek idea that chemistry, like geometry, could be developed logically from self-evident principles. With Boyle, the idea that theoretical conceptions must give way to experimental discoveries found a champion among the chemists. And he attacked the accepted belief that there were only a small number of chemical elements. 60 Such is the bare outline of the progress of the exact sciences by the middle of the seventeenth century. We have seen that while the Greeks made a few positive contributions, for the greater part their influence was negative; it was necessary for their teaching to be thoroughly dis- credited before experimental science could emerge. Neoplatonism can- not be considered here, but its doctrines were even more antiscientific than Aristotelianism. For what is called modern science represented a 60. Marie Boas, Robert Boyle and Seventeenth-Century Chemistry (Cambridge University Press, 1958). Medieval Speculation, Puritanism, and Modern Science 49 A Chalcedon Publication [] 3/30/07 radical shift {36} in perspective: no longer was the attempt made to explain all nature by a single theory; rather, men now concentrated on limited objectives. Each of the scientific disciplines began to look for relations in nature that could be observed as “cause” and “effect,” finally choosing only those “effects” which could be measured or estimated. And the model of the world was transformed from living organism to great machine, ruled by inexorable natural laws whose workings were open to understanding by the mind of man. Whatever its flaws, this picture was closer to the biblical view: behind the concept of the world as a living organism was the assumption that the world had been gen- erated; the mechanistic image had behind it the belief that the world had been created by an omnipotent Lawgiver. Before sketching the general pattern of the biblical presuppositions that emerged in opposition to the maze of Greek-pagan conjectures prior to the Scientific Revolution, we need to be reminded of just a few of the distinctives of the biblical teaching regarding nature. First of all, there is a radical contrast between the Greek-pagan deification of nature, and the biblical depiction of nature as the creation of God out of nothing. Only the personal God is divine: He has not to reckon with eternal forms; nor, being omnipotent, can He be opposed by any mat- ter. For the pagans, nature was a god to be worshipped and feared; in the biblical perspective nature is the handiwork of a transcendent Cre- ator, who purposed that man should admire, study, and control His creation. While their thinking continued to be infected somewhat with cer- tain ideas of Greek-pagan teaching, the biblical view of nature began to transform the thought patterns of the early Christians as they moved across the Greco-Roman world. Clement of Alexandria powerfully charged the pagan educators: “Let none of you worship the sun; rather let him yearn for the maker of the sun. Let no one deify the universe; rather let him seek after the creator of the universe.” 61 In The City of God, Augustine declared that both the material universe and human history have their origin in the sovereign creative work of God. Not surprisingly, those who followed Augustine had a sense of purpose, their life had a meaning, and they were able to discern intelligible pat- 61. Jaki, 168. 50 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 terns in nature. Contrast this with Marcus Aurelius: “His universe was at the mercy of the blind forces of the cosmic treadmill. Humans in that universe were as many momentary bubbles appearing and dissolving with a cyclic necessity over the dark expanse of an unfathomable sea of cosmic and individual destinies.” 62 Coming to the fourteenth century, we clearly see in such men as Jean Buridan the vast gulf separating the Aristotelian and Christian world- views. Over against Aristotle’s denial that the heavens could decay, Buridan declared {37} the Creator has the ability, if He chooses, to destroy the world. Buridan’s contemporary, Nicole Oresme, denied the heavens were eternal, asserting instead that the heavens have a begin- ning in God’s creation. 63 During the Renaissance, such teachers as Marsilio Ficino, leader of the Neoplatonic academy of Florence, sought to demonstrate that Pla- tonism and Christianity carried the same message. This attempt was, of course, absurd, and consequently unsuccessful. But another fifteenth- century scholar, Nicholas of Cusa, moved by the Christian worldview, denied that the earth was motionless, and suggested all cosmic bodies are basically similar. While Nicholas sometimes spoke favorably about Plato and Neoplatonism, “he did so with an eye on the doctrine of Cre- ation.” 64 Other Christian thinkers of the later Middle Ages often admired Plato and Aristotle, but their biblical perspective kept them from falling into a humanistic apriorism and immanentism. As Kepler, who all his life was attracted to astrology, was later to put it: “Christian religion has put up some fences around false speculation.” The Reformation of the sixteenth century was many things, but fundamentally it was the rediscovery of the gospel. Many voices were clamoring for the reformation of the church—i.e., administrative or moral reform. (By moral, they had in mind such things as restrictions to prevent the priests from sleeping around, or to preclude them from administering the sacraments while drunk.) But the Reformation that came was, at its most basic level, doctrinal, with far-reaching conse- 62. Ibid., 184. 63. Cf. Nicholas H. Steneck, Science and Creation in the Middle Ages (University of Notre Dame Press, 1976). 64. Jaki, 255. Medieval Speculation, Puritanism, and Modern Science 51 A Chalcedon Publication [] 3/30/07 quences for many areas of life and thought. One of those areas was sci- ence. In recent years, historians of science have begun to wonder why modern science had its specific beginnings in the latter part of the six- teenth century. While they notice that the Reformation triumphed in the very geographic regions where modern science later was to attain its greatest development, the historians usually deny the Reformation had any positive contribution in this regard. Typical is Alan G. R. Smith, who writes: ... in the 1530s Martin Luther made a contemptuous reference to Copernicus as “the new astrologer who wants to prove that the earth moves and goes round....” Calvin also joined in the condemnation in his Commentary on Genesis, where he cited the opening verse of the ninety-third Psalm, “the world also is stablished that it cannot be moved,” and asked, “who will venture to place the authority of Copernicus above that of the Holy Spirit?” 65 (Against this, R. Hooykaas has pointed out in “several periodicals concerned with the history of science that the ‘quotation’ from Calvin is {38} imaginary and that Calvin never mentioned Copernicus; but the legend dies hard.”) 66 The conceptual edifice to be destroyed in the late sixteenth century was the Aristotelian-medieval universe moved by pantheistic, organis- mic purposiveness. While men like Galileo were little affected by the Reformation, they were guided in their work by the Christian world- view, and, in particular, the doctrine of God as Creator and omnipotent Lawgiver. The Protestant worldview, especially that flowing from the Calvinistic Reformation, was destined to separate still more sharply the biblical from other ideas of nature, and to complete the demolition of the medieval Aristotelian-Scholastic synthesis. In a paper first published in 1962, Thomas F. Torrance asked: “Why was it then that modern empirical science had to wait until the begin- ning of the seventeenth century for its real advance?” 67 Torrance argues forthrightly that the Reformation and the change it wrought in 65. Science and Society in the Sixteenth and Seventeenth Centuries (New York: Harcourt Brace Jovanovich, 1972), 97. 66. Religion and the Rise of Modern Science (Grand Rapids, MI: Wm. B. Eerdmans Publishing Co., 1972), 121. 52 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the intellectual sphere made this advance possible. The foundation was a change in the doctrine of God: the change from the “Stoic-Latin view of God”—that God is unfeeling, uncaring and distant— “to an essen- tially biblical view of God as the living, active Creator and Redeemer.” 68 Under the teaching of the Reformers, men learned to think differently of God and of his relation to creation as something utterly distinct from him while yet dependent upon his will for its being and ultimate order, and therefore learned to think differently of the nature of nature and of the creaturely nature of its order. 69 The Reformers, moreover, swept away the Thomistic dichotomy between nature and grace. Torrance contends this “gave new signifi- cance to the world as the object of divine attention, and therefore as the object of human attention in obedience to the divine.” 70 This was cru- cial to the development of modern science: men had looked away from the world, believing purpose and meaning came only through contem- plation of the divine. The Reformation restored the biblical perspec- tive, stimulating thereby an interest in God’s handiwork. Torrance also discusses the contribution of the Reformation to sci- entific objectivity. It is this masterful objectivity, with its distinction between unwar- ranted {39} presupposition and proper entailment arising out of the nature of the object, that is one of the great contributions of the Refor- mation to the modern world, for out of it came the spirit and proce- dure so characteristic of modern science. 71 The Reformation made many other highly significant and essential contributions to modern scientific development, but we must hasten on to the seventeenth century, and to the English Puritans. In the latter part of the nineteenth century, two books appeared— John W. Draper’s History of the Conflict Between Religion and Science 67. “The Influence of Reformed Theology on the Development of Scientific Method,” reprinted in T. F. Torrance, Theology of Reconstruction (Grand Rapids, MI: Wm. B. Eerdmans Publishing Co., 1965), 62–75. 68. Ibid., 62. 69. Ibid., 63. 70. Ibid., 65. 71. Ibid., 67. Medieval Speculation, Puritanism, and Modern Science 53 A Chalcedon Publication [] 3/30/07 and A. D. White’s History of the Warfare of Science with Theology— which announced, on the basis of positivistic presuppositions, that the relation between Christianity and science had always been one of con- flict and opposition. This is today the received opinion, and the humanistic mind of our age regards any suggestion of a positive associ- ation of the two as incredible. It must, therefore, have been with con- siderable amazement that the intelligentsia greeted a series of studies by Robert K. Merton which appeared in Osiris in 1938, 72 wherein the writer argued that Puritanism made a powerful contribution to the legitimacy of science as an emerging social institution. Merton insisted, however, that his thesis did not “presuppose that only Puritanism could have served that function. As it happened, Puritanism provided major (not exclusive) support in that historical time and place.” 73 Merton attempted to explain the extraordinary advances of seven- teenth-century science by correlating its particular objectives and underlying values with other aspects of society. What he evolved are two theses which overlap at certain points. The first stresses the attempt of the Baconians, by learning the techniques of contemporary craftsmen, to make science applicable to vital problems of the day— e.g., navigation, deforestation, and land drainage. The second identifies Puritanism as the source of the singular values and objectives of the first thesis. Critics usually point out that the Merton thesis is an extension of the Weber thesis, and Merton indeed acknowledges his debt to Weber. But Merton denies that he began his studies with the prior assumption that Puritanism was of positive value for modern science. He simply set out to make sense of scientific development in seventeenth-century England, guided by a general sociological hypothesis which assumed that “various institutions in the society are variously interdependent so that what happens in the economic or religious realm is apt to have perceptible connections with some of what happens in the realm of sci- ence, and conversely.” It {40} was during “the course of reading the let- ters, diaries, memoirs and papers of seventeenth-century men of 72. Reprinted in 1970, with a new preface by the author, as Science, Technology & Society in Seventeenth Century England (New York: Howard Gertig). 73. Ibid., xviii. 54 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 science” that Merton “slowly noted the frequent religious commit- ments of scientists in this time, and even more, what seemed to be their Puritan orientation.” 74 Merton is anxious that a main presupposition of his thesis be under- stood: The substantial and persistent development of science occurs only in societies of a certain kind, which provide both cultural and material conditions for that development.... Before it became widely accepted as a value in its own right, science was required to justify itself to men in terms of values other than that of knowledge itself. 75 The achievement of these conditions, as Merton understands it, was largely accomplished by the Puritans. In order to show how Puritanism achieved the legitimation of sci- ence, Merton studied various aspects of the Puritan perspective and character. The glorification of God, he notes, was the be-all and end-all of the Puritan; and secondarily, the well-being of his fellow man. There was “the tendency to laud the faculty of reason,” which is “praiseworthy because man, chosen of God, alone possesses it,” and because “it enables man more fully to glorify God by aiding him to appreciate His works.” 76 Merton accentuates the Puritan concern with utility and practicabil- ity. He quotes Richard Baxter: “Knowledge is to be valued according to its usefulness,” and then observes: “Puritanism tends ever more and more to emphasize the value of reshaping this world.” 77 A distinction is made between the pre-Reformation and post-Reformation type of reli- gious personality—the former, Merton (following Spranger) classifies as “transcendent mystic”; the latter, “immanent mystic.” The first finds rest only in a super-sensuous world. For such a being science is without value since it does not answer the ultimate ques- tions; all his energies are concentrated on preparing his soul for inner vision. The immanent mystic ... applies his religious beliefs in a totally different fashion. Life and action become positively valued precisely because they are indications of God. 78 74. Ibid., xvii. 75. Ibid., xix. 76. Ibid., 66. 77. Ibid., 72–73. Medieval Speculation, Puritanism, and Modern Science 55 A Chalcedon Publication [] 3/30/07 The Puritans are, in this view, “immanent mystics.” “Puritanism,” according to Merton, “differed from Catholicism, which had gradually come to tolerate science, in demanding, not merely condoning, its pursuit.” 79 The Puritans held that “the study of nature enables a fuller appreciation of His works and thus leads us to admire and praise the Power, Wisdom and Goodness of God mani- fested in His creation.” 80 {41} Not unexpectedly, Merton’s thesis has been the target of severe criti- cism in the years since its publication. These attacks intensified after Christopher Hill argued in the British journal, Past and Present, as well as in his book, Intellectual Origins of the English Revolution (1965), that Puritanism and modern scientific ideas developed together in opposi- tion to the scientific obscurantism of the Anglicanism of the seven- teenth century. 81 Alternative theories to explain English scientific development were offered; for example, B. J. Shapiro argued that “reli- gious moderation was far more intimately connected than Puritanism with the English scientific movement of that period.” 82 And while The- odore K. Rabb admits: “Nobody can ignore the links between the reformed religion and scientific advance. The heavy preponderance of Protestants among scientists after the 1640s is inescapable,” he none- theless insists that the Merton thesis “can no longer be adduced as the final word on the subject.” 83 78. Ibid., 74. 79. Ibid., 87. 80. Ibid., 102. 81. Cf. Past and Present: C. Hill, “Puritanism, Capitalism and the Scientific Revolution,” no. 29 (December 1964); “Science, Religion and Society in the Sixteenth and Seventeenth Centuries,” no. 32 (December 1965); H. F. Kearney, “Puritanism, Capitalism and the Scientific Revolution,” no. 28 (July 1964); T. K. Rabb, “Religion and the Rise of Modern Science,” no. 31 (July 1965); “Science, Religion and Society in the Sixteenth and Seventeenth Centuries,” no. 33 (April 1966); B. J. Shapiro, “Latitudinarianism and Science in 17th-Century England,” no. 41 (July 1968). Kearney, Rabb, and Shapiro are concerned to refute Hill, but Merton also catches a good part of the flak. 82. “Latitudinarianism and Science in 17th-Century England,” Past and Present, no. 40 (July 1968): 16. 56 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Perhaps the basic weakness of the Merton thesis, aside from ques- tions of methodology, is that it sometimes seems to equate all men and ideas which are non-Catholic and non-Laudian (Anglican-Arminian) with Puritanism. The most striking illustration of this is in the section where Merton discusses the Puritan contribution to science in early America. Concerning the men of science of this period, and the lists of the Royal Society, Merton says one finds “a preponderance of Puritans among the colonists elected Fellows....” 84 One of those he cites is Ben- jamin Franklin! On the other hand, critics of the Merton thesis like Shapiro tend to equate Puritanism with the most savage form of religious fanaticism whose inevitable concomitant is extreme intolerance of any view which differs from one’s own. That such a view is the wildest kind of carica- ture can easily be demonstrated, but such an image readily commends itself to the modern humanist, for whom Puritanism is anathema. This is not to say all the criticisms are false: some indeed are needed correc- tives; religious moderates like John Wilkins and Robert Boyle were not, strictly speaking, {42} Puritans—though we would vigorously dissent from Shapiro’s identification of religious moderation in these men with latitudinarianism. The point is that the narrow definition of “Puritan” is just as false and misleading as the wider view. While we agree with Hooykaas that “the relationship between Puritanism and science was 85 the confusions alluded to above make it imperative that we clarify what we mean when we speak of “Puritanism.” The Puritan movement had from its beginning in the early days of the reign of Queen Elizabeth two closely related, though distinguish- able, objectives. The one was concerned to carry reform of polity, wor- ship, and discipline in the Anglican Church beyond the limits established by the Elizabethan Settlement; the other had reference to the all-consuming passion of the Puritan to preach and apply the Word of God. Of these two, the latter is by far the more important. We wholly agree with William Haller: 83. “Religion and the Rise of Modern Science,” Past and Present, no. 31 (July 1965): 111–12. 84. Merton, 122. 85. Hooykaas, 135. Medieval Speculation, Puritanism, and Modern Science 57 A Chalcedon Publication [] 3/30/07 The disagreements that rendered Puritans into presbyterians, inde- pendents, separatists and baptists were in the long run not so signifi- cant as the qualities of character, of mind and of imagination, which kept them all alike Puritan.... It was a new way of life, overrunning all the divisions which from time to time seamed its surface.... 86 In reviewing the confusion of scholars over the definition of Puritan- ism, David Little—after insisting that “Puritanism was, indeed, a dis- tinct system of meaning and values with an indomitable logic that shook the very foundations of Elizabethan and Stuart society”—com- ments with no little irony: If certain modern scholars have trouble recognizing it as such, con- temporaries were hardly so undiscerning. One would not have found Elizabeth, James, or Charles, Whitgift, Bancroft, or Laud questioning the distinctiveness and singular vitality of Puritanism. They all felt its threat and knew its power. 87 So Puritanism was fundamentally “a new way of life, a distinct sys- tem of meaning and values with an indomitable logic.” The thought- forms of the Puritans very clearly derive from the theology of Calvin. According to Little, “the remarkable coherence between Calvinism and Puritanism is more readily apparent in the light of their common antagonism to certain presuppositions that both Renaissance and Anglican thinkers seem to share.” 88 When we read the gospel accounts of the first advent {43} of Christ, there presses upon us a profound awareness that a new order has appeared in the world. In the teaching of Calvin, we see this new order rediscovered and vigorously asserted against his Catholic and humanist contemporaries. With the Puri- tans—standing as they did on the foundation of the whole Word of God alone as ultimate authority over every sphere of life—we see afresh and with incomparable dynamism, the new order of Christ pro- claimed against its adversaries. Powerfully opposed in their efforts at ecclesiastical reform by Eliza- beth, James, and Charles I, the Puritans concentrated their efforts in 86. The Rise of Puritanism (New York: Harper Torchbooks, [1938] 1957), 17–18 (emphasis added). 87. Religion, Order and Law (New York: Harper Torchbooks, 1969), 82. 88. Ibid., 33. 58 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 other directions. “If they could not change the system,” Cragg observes, “they would change the men within it.” Cragg continues: This kind of change was a contagion, passed from preacher to hearer in ever-widening circles.... They were fully occupied in the task of cre- ating the new man. This, as it proved, had revolutionary consequences far beyond anything that could have been foreseen. 89 Merton pointed out that “among the original list of members of the Royal Society in 1663, forty-two of the sixty-eight for whom informa- tion pertaining to religious leanings is available, were clearly Puritan.” 90 While these figures have been subjected to the most searching criti- cism, they have emerged substantially intact. This indication of the preponderance of Puritans among English scientists in the seventeenth century is all the more striking when consideration is given to the fact that the Puritans were never more than about four percent of the popu- lation. 91 What were some of the specifics making for the unusual affinity of the Puritans for the new science? We will enumerate in cursory fashion a few things: each of these should be developed in much greater detail. The preeminent element, to our mind, was the Puritan view of the absolute authority of the Bible. As Christopher Hill puts it, “You could brave the King of England if you were obeying the orders of the King of Kings.” The Puritan was convinced he was to “think nothing, conceive nothing, know and resolve nothing” until given warrant to do so by Holy Scripture. His presuppositions about nature, and his boldness to pursue its investigation, derived from the same source. It kept him, moreover, from an unfounded dependence on reason. While using rea- son, he believed it was safe only when controlled by faith. According to John Preston, “A man hath reason to guide him, and he hath grace to guide reason.” Following from the emphasis on the authority of Scripture, was the doctrine of God as Creator and omnipotent Lawgiver. “The conviction in immutable law is as pronounced in the doctrine of predestination as in scientific investigation,” 92 as Merton has seen. Since God was under- 89. Cragg, 138. 90. Merton, 114. 91. Little, 259. Medieval Speculation, Puritanism, and Modern Science 59 A Chalcedon Publication [] 3/30/07 stood {44} as the One who created all things after the counsel of His own will, and who rules over all by means of His law, the Puritans, developing the insights of the Calvinistic Reformation, believed these laws as they relate to nature can be—indeed, must be!—found out. The greatest naturalist of the seventeenth century, the Puritan John Ray, “argued that because the Almighty created man able to study nature, He intended that man ought to study nature. The pursuit of natural philosophy is a religious duty.” 93 Ray, with his profound sense of provi- dence, was typical of the Puritans described by Owen Chadwick: “Such men were impregnated with Biblical texts; conscious of the imminent hand of God upon every act and moment; denying the possibility of chance....” The great emphasis of the Puritans on vocation and calling was based on the conviction that the Christian must live his life in terms of God’s law in order to glorify and enjoy Him. One Puritan (Norden) declared that the best way to execute the positive demands of the eighth commandment was to be in a calling that is “lawful, agreeable to the Word of God, honest or necessary for the use and society of men....” The intense vigor with which a Puritan pursued his calling was closely related to his doctrine of work. This is illustrated perfectly by a letter from John Ray to James Petiver: I am glad your business increases so as to require more attendance, and take up more of your time, which cannot be better employed than in the works of your proper callings. What time you have to spare you will do well to spend, as you are doing, in the inquisition and contem- plation of the works of God and nature. 94 Another Puritan, William Perkins, considered the lazy and slothful the very incarnation of evil. Giving alms to such was, he believed, the severest infringement of God’s law. The Puritan’s work was purposeful and goal-oriented. The post- millennial eschatology of the first generation gave them an indomitable confidence that through the faithful proclamation and exposition of 92. Merton, 109. 93. Richard S. Westfall, Science and Religion in Seventeenth-Century England (Ann Arbor: University of Michigan Press, 1973), 46. 94. Merton, 86n9. 60 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the Word and its application to the whole of life, the world would be conquered and transformed for Christ. This Puritan idea of progress— as opposed to the secular version that came later—was based on Deuteronomy 8, which teaches that obedience to the law of God brings spiritual and material blessings. 95 The postmillennial vision of a victorious Christian future was a pow- erful spur to scientific and technological advance. Simply compare it with the {45} psychology of premillennialism— “you don’t polish brass on a sinking ship!” That such an interest—assuming it is biblical—can yield positive results is clearly incredible to the modern humanist. Consider some comments on Sir Isaac Newton’s commentary on the book of Revelation. Newton, whose Arian Christology set him apart from the Puritans, was yet an intensely religious man. The incredulous Cesare Lombroso declared: “Newton himself can scarcely be said to have been sane when he demeaned his intellect to the interpretation of the Apocalypse.” 96 We set out to answer the question, “What explains the unequaled scientific transformation of England in the seventeenth century?” Our answer is that Puritanism created a spiritual climate in England uniquely favorable to the pursuit and development of experimental sci- ence, as well as the personal qualities, objectives, and values so essential to progress. The Puritans were the heirs of the Reformers and, as such, carried many of their insights to their logical conclusion. That is, they restored the biblical perspective. In conclusion, let us briefly consider the faith and work of the great- est of Puritan scientists, John Ray (1627–1705). A man of transcendent ability, Ray believed in the harmony of Christianity and science. When he published the Wisdom of God Manifested in the Works of Creation, he prefaced it with words from Psalm 104:24: “How manifold are thy works, O Lord. In wisdom hast thou made them all.” For Ray, nature was the vast library of creation, and there he found a limitless store of divinity. He believed the most glorious calling of man was to study and 95. Cf. Gary North, “Magic, Envy, and Economic Underdevelopment,” Journal of Christian Reconstruction 1, no. 2 (Winter 1974): 153. 96. Merton, 106n62. Medieval Speculation, Puritanism, and Modern Science 61 A Chalcedon Publication [] 3/30/07 enjoy the works of God as manifested in nature, and thereby to honor the wisdom and goodness of the Creator. Ray, in words of power and beauty, has given us the Puritan vision of nature as the creation of an infinitely wonderful God: You ask what is the use of butterflies. I reply to adorn the world and delight the eyes of men, to brighten the countryside like so many golden Jewels. To contemplate their exquisite beauty and variety is to experience the truest pleasure. To gaze inquiringly at such elegance of color and form devised by the ingenuity of nature and painted by her artist’s pencil, is to acknowledge and adore the imprint of the art of God. 97 Would to God that there would be a restoration of this vision of nature in our generation, and again the men of science would speak of the “wonderful works of the Creator”! 97. Quoted in Westfall, 46. A Chalcedon Publication [] 3/30/07 THE ROLE OF PURITAN-CALVINISM IN THE RISE OF MODERN SCIENCE E. L. Hebden Taylor The Role of Paradigms and Ground Motives in the History of Science Before we begin our examination of the role played by Puritan-Calvin- ism in the rise of modern science, it is first necessary to consider the role played by paradigms and ground motives in the history of science. Older historians of science such as Sir William C. Dampier in his book, A History of Science, have tended to view the history of science as a cumulative process concerned with obtaining a true view of the nature of reality, especially in its physical and biological aspects. 98 More recently this view of the history of science has been challenged by Tho- mas S. Kuhn in The Structure of Scientific Revolutions. In the first edi- tion of his book, published in 1962, Kuhn broke new ground in providing us with new insights into the nature of modern science, its origin and development. Kuhn sees science at any given point in time as dominated by a spe- cific paradigm or model which he defines as the “universally recog- nized scientific achievements that for a time provide model problems and solutions to a community of practitioners,” 99 and later in his book he elaborates upon this definition by stating that “paradigms provide scientists not only with a map but also with some of the directions essential for map-making. In learning a paradigm the scientist acquires theory, methods, and standards together.... Therefore, when paradigms change, there are usually significant shifts in the criteria determining the legitimacy both of problems and of proposed solutions.” 100 Normal 98. Sir William C. Dampier, A History of Science and Its Relations with Philosophy & Religion (New York: Macmillan Co., 1946). 99. Thomas S. Kuhn, The Structure of Scientific Revolutions (Chicago: University of Chicago Press, [1962] 1970), preface, x. The Role of Puritan-Calvinism in the Rise of Modern Science 63 A Chalcedon Publication [] 3/30/07 science is a period of accumulating scientific knowledge in which sci- entists work on, and expand, the reigning paradigm, e.g., Newtonian mechanics and physics. Inevitably, however, such work spawns anoma- lies, or things that cannot be explained within the existing paradigm or model. If these anomalies increase, a crisis stage is reached, which ulti- mately may end in a scientific revolution in which the reigning para- digm or model is overthrown and a new one takes its place {47} at the center of science, e.g., Einstein’s relativity theory in physics supplanting Newton’s model. Thus a new reigning paradigm is born, and the stage is set for the cycle to repeat itself. It is during the period of revolution that great changes in scientific status take place. Such a view of “scien- tific revolutions” clearly places Kuhn at odds with the lay and textbook conception of scientific progress and development, which suggests that such progress in scientific knowledge is cumulative. The key concept in Kuhn’s model of scientific revolutions is clearly his concept of a paradigm. Unfortunately, his concept of a paradigm is elusive. According to M. Masterman in Criticism and the Growth of Knowledge, Kuhn uses the term in at least twenty-one different ways. 101 In response to those who criticized his vagueness about the concept of a paradigm in his first edition, Kuhn offered a very narrow definition of a paradigm in the epilogue to the second edition of The Structure of Scientific Revolutions. 102 There he equates paradigms with exemplars, or “the concrete puzzle solutions which when employed as models or examples, can replace explicit rules as a basis for the solution of the remaining puzzles of normal science.” 103 There is another reason for this narrow definition of a paradigm. As Kuhn himself notes, his original work was criticized for its “subjectivity and irrationality.” The thrust of the first edition pointed in the direc- tion of a very broad definition of a paradigm encompassing the entire constellation of beliefs, values, techniques, and so on shared by the members of a given community. 104 By 1970 Kuhn viewed this defini- 100. Ibid., 108. 101. Imre Lakatos and Alan Musgrave, Criticism and the Growth of Knowledge (Cambridge: Cambridge University Press, [1970] 1974), essay by M. Masterman. 102. T. S. Kuhn, Structure, 1970 ed., 175. 103. Ibid. 64 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 tion as an “inappropriate” use in the term paradigm, primarily because it makes science appear to be irrational. In his retreat from a broad to a narrow definition of a paradigm we may note in passing that Kuhn reveals himself as still in the grip of an autonomous reasoned-based view of what constitutes truth. To save man’s autonomous reason he cannot now admit to the part played by religious presuppositions or what Herman Dooyeweerd has called religious ground motives in The Twilight of Western Thought 105 and in A New Critique of Theoretical Thought. 106 Kuhn in fact seems to admit that science is noncognitive, that is to say, it cannot lead us to any ultimate truth at all. He wrote in the first edition of The Structure of Scientific Revolutions: {48} In the sciences there need not be progress of another sort. We may, to be more precise, have to relinquish the notion, explicit or implicit, that changes of paradigm carry scientists and those who learn from them closer and closer to the truth.... We are all deeply accustomed to seeing science as the one enterprise that draws constantly nearer to some goal set by nature in advance. But need there be any such goal? Can we not account for both sci- ence’s existence and its success in terms of evolution from the commu- nity sub- stitute evolution-from-what-we-do-know for evolution-toward-what- we-wish-to-know, a number of vexing problems may vanish in the process. 107 In The Unity of Creation, Russell Maatman criticizes Kuhn’s irrationalistic view of science for ignoring the “existence of an over- arching paradigm, the coherent power of God.” Maatman writes of Kuhn’s views as follows: 104. Ibid. 105. Herman Dooyeweerd, In the Twilight of Western Thought (Philadelphia: Presbyterian and Reformed Publishing Co., 1960), 27–61. 106. Herman Dooyeweerd, A New Critique of Theoretical Thought, vol. 1 (Philadelphia: Presbyterian and Reformed Publishing Co., 1957), 169–207. 107. Kuhn, Structure, 1962 ed., 169–70. The Role of Puritan-Calvinism in the Rise of Modern Science 65 A Chalcedon Publication [] 3/30/07 Kuhn’s emphasis on paradigms as the umbrella under which physical scientists work suggests—although it is obviously an idea that he would not accept—that we might take his changing paradigms to have meaning only as they exist under one unchanging, overarching para- digm. This overarching paradigm, like his paradigms, is a mental con- struct, but it is not one that changes, for our unchanging mental construct is the certain knowledge that all men possess, although some have suppressed it, the knowledge that there is a single, coherent power that ultimately causes all that we observe.... There is no para- digm change unless the new paradigm shows us more clearly that the overarching paradigm is valid. For a new paradigm, by definition, must show that more of our observations can be brought together. We conclude, therefore, that Kuhn’s paradigm theory, insofar as it deals with the nature of scientific revolutions which bring about the accep- tance of new paradigms, cannot be true if the central principle is not true.... The trend toward better paradigms can only be accounted for by the existence of an unchanging, overarching paradigm. Therefore, the knowledge of the existence of such a paradigm must not be sup- pressed. 108 According to Herman Dooyeweerd, underlying every human system of thought, belief, value, and science may be found after close investi- gation a religious ground motive, which determines not only man’s view of the truth but even controls the methods he uses to attain it. The inner problematics of paradigm changes in the history of modern sci- ence are not due to the nature of God’s creation law structures, but they are due to the conflict between varying religious ground motives. {49} Man’s relationship to the truth about God’s creation will ultimately be determined by his obedient or disobedient response to God’s Word. As Harry Cook, a professor of biology at Dordt College, well said in his review of the first edition of Kuhn’s Structure of Scientific Revolutions: We must differ with Kuhn’s extremely subjectivistic conclusion, no matter how much we approve of his belligerence against the predomi- nant spirit of the scientific community.... the formulation of natural laws is not a matter of survival of the fittest, the fittest being the formulation which leads to most progress. Rather, it is the Word which was from the beginning, through which everything was made 108. Russell Maatman, The Unity of Creation (Sioux Center, IA: Dordt College Press, 1978), 123–25. Dr. Maatman is professor of chemistry at Dordt College. Cf. R. J. Rushdoony, The Mythology of Science (Craig Press, 1967), 85ff. 66 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 (John 1:1–14), which originated and upholds reality. It is the business of the scientist to investigate this structure which holds for reality, and he should attempt to formulate laws or theories which reflect this structure. Then formulations, while often in error, and always influ- enced by the “paradigm” of the investigator, should still be seen as man-made attempts to reflect the creating, upholding, structuring Word. When we accept that it is this Word which structures reality, it is not surprising that Kuhn, and also Conant, have to back away from their position, to account for the constancy which confronts them as they, or others, investigate reality. 109 Science in all its aspects is the product of human cultural formation, and the direction which it takes will ultimately depend upon whether it makes the Word of God revealed in the Holy Scriptures the key to knowledge or whether it takes the autonomous human reason as its ultimate point of reference. 110 Basic then to the cultural forming activ- ities of men and of the type of science they build is a commitment to some god or absolutization of man’s own devising or to the God of the Bible. This commitment, whether openly avowed or only implicitly recognized, is what Dooyeweerd means by a religious ground motive. Dooyeweerd has distinguished four such basic ground motives: that of Form and Matter, which dominated pagan classical Greek philoso- phy and science; that of Nature and Grace, which underlay the medi- eval synthesis of Christian and Graeco-Roman science and philosophy; that of Nature and Freedom, which has shaped the philosophies and sciences of modern times; and finally the biblical ground motive of cre- ation, fall, and redemption which lies at the root of a radical and inte- grally scriptural philosophy and science. The nature-freedom ground motive has been defined by Dooyewe- erd as the ground motive governing the development of modern West- ern post-Christian civilization. It is the motive of “Nature,” or of men’s faith in {50} science as their only ground of certainty and salvation, and 109. Harry Cook, review of The Structure of Scientific Revolutions, by T. S. Kuhn, in Journal of the American Scientific Affiliation 25, no. 1 (1973): 34–38. 110. Gary North, Foundations of Christian Scholarship (Vallecito, CA: Ross House Books, 1976), 3–24, essay by North on “The Epistemological Crisis of American Universities.” The Role of Puritan-Calvinism in the Rise of Modern Science 67 A Chalcedon Publication [] 3/30/07 of “Freedom,” or the ideal of the free autonomous personality. While the watchword of the Reformation was soli Deo gloria, and man’s lib- erty and salvation were defined in terms of his willing obedience to the Lord Jesus Christ, the new secular humanistic nature-freedom ground motive proclaimed the independence of man from the God of the Bible and the sovereignty of the human reason and of the new scientific methods brought about by the discoveries of Copernicus, Galileo, and Newton. 111 Man now came to regard himself as independent of the God of the Bible and absolute in himself. He was henceforth to be con- sidered the only ruler of his destiny and that of the world. He was now regarded as creative of the world in which he was placed, not, of course, in any originating sense, but in the sense that his mind or “rational will” would impress its character upon the universe and give it its dis- tinctive character, especially in the realms of intellectual, scientific, and political activity. The biblical revelation of the creation of man in God’s holy image was now subverted into the idea of the creation of God in the idealized image of man. Henceforth, unbelieving Western men and women will be subject to none but themselves. They sought to become autonomous and to become the source of their own light, making their own reason and science the final reference point for man’s understand- ing of his own nature and destiny. 112 This nature-freedom ground motive has provided the dialectical framework in which not only modern Western society itself has devel- oped in modern times but also modern secular humanistic science. No cultural realm has escaped the impact of this ground motive, including the realm of scientific discovery and pursuit. Scientific work is looked upon as the means by which man can literally remake his world and himself. To use a Latin phrase, scientia ancilla vitam captandi, that is, science is to be used to capture or dominate human life. 111. T. S. Kuhn, The Copernican Revolution: Planetary Astronomy in the Development of Western Thought (Cambridge, MA: Harvard University Press, 1957), and R. G. Collingwood, The Idea of Nature (Oxford: Clarendon Press, 1945). 112. Cornelius Van Til, In Defense of the Faith: A Survey of Christian Epistemology (Den Dulk Foundation, 1969), vols. 1 and 2; also Robert L. Reymond, The Justification of Knowledge (Presbyterian and Reformed Publishing Co., 1976), and R. L. Reymond’s pamphlet, A Christian View of Science (Presbyterian and Reformed Publishing Co., 1964). 68 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 After quoting from both Kuhn’s and Conant’s works, Harry Cook points out that the writings of these men “illustrate a dialectical tension between Freedom and Nature (or Freedom and Determinism, as it is often called), which seems unresolvable.” 113 As a Christian biologist and philosopher of science, Cook rightly teaches that only the motive of “Creation-Fall-Redemption in the communion of the Holy Spirit” can “avoid the dialectic {51} tensions which inevitably arise on the other ground motives he [Dooyeweerd] has identified.” 114 In the light of our discussion of the part played by both paradigms and ground motives in the history of science, we shall now proceed to examine the origins of the so-called “Scientific Revolution” of the sev- enteenth century and of the role played by Puritan Calvinists in its development. Most secular historians of this scientific revolution have, by and large, tended to ignore the great contribution made by Puritan Calvinist scientists, and by the leaders of the Reformation in the six- teenth century. The Contribution of the Reformation to the Rise of Modern Science Philosophers of science such as A. N. Whitehead in Science and the Modern World 115 and Herbert Butterfield in The Origins of Modern Sci- ence 116 have tended to emphasize the role of genius most strongly in their interpretation of the origins of the scientific revolution which took place during the later years of the sixteenth century and the sev- enteenth century. The Renaissance rather than the Reformation is the decisive analogy by which to interpret the rise of modern science. It is of course true that both Whitehead and Butterfield go out of their way to treat the Middle Ages sympathetically. Whitehead maintained that without the long training of logical thought which Europe had obtained during the Middle Ages, modern science as we know it today 113. Cook, review, Journal of the American Scientific Affiliation 25:38. 114. Ibid. 115. A. N. Whitehead, Science and the Modern World (Cambridge: Cambridge University Press, 1946). 116. Herbert Butterfield, The Origins of Modern Science: 1300–1800 (London: Bell, 1949). The Role of Puritan-Calvinism in the Rise of Modern Science 69 A Chalcedon Publication [] 3/30/07 would have been impossible. He argued that faith in the regularity of nature, without which there could be no empirical science, could not have arisen apart from the antecedent faith of medieval Christendom in the rationality of God. Belief in the uniformity of nature must have arisen, he writes, “from the medieval insistence on the rationality of God, conceived as with the personal energy of Jehovah and with the rationality of a Greek philosopher. Every detail was supervised and ordered: the search into nature could only result in the vindication of the faith in rationality.” 117 Herbert Butterfield devoted a chapter of his book, The Origins of Modern Science, to an appraisal of the significance of medieval dynam- ics. But for both writers, the sixteenth and seventeenth centuries are preeminent. Whitehead describes the seventeenth century as the “cen- tury of genius.” Butterfield uses phrases such as “an epic adventure” and “a great episode in human experience.” In their interpretation, the sci- entific revolution seems to have taken the place of the Renaissance, but it is essentially a secular {52} humanist movement of the same kind, one in which the imaginative leaps of particular individuals are more important than any social, economic, philosophic, or religious factor or trend. Whitehead’s view of the part played by medieval science ignores the fact that it was based on a Roman Catholic scholastic conception of nature in terms of self-existent autonomous beings and of reality as consisting of a great impersonal chain of being moving towards prede- termined ends. Arthur O. Lovejoy attributes to the Greek philosopher Plato the philosophic genesis of the idea of “The Great Chain of Being.” 118 According to Edwin A. Burtt, in The Metaphysical Foundations of Modern Science, medieval science was teleological in nature and was concerned to establish a series of basic rational principles, from which it sought to deduce all things, because most medieval thinkers had sup- posed, following the example of Aristotle, that only ultimate principles and final causes had any real or significant existence. 117. Whitehead, Science, 15–16. 118. Arthur O. Lovejoy, The Great Chain of Being (New York: Harper, [1936] 1960), 45ff. 70 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Burtt writes of medieval science in comparison with modern science thus: For the dominant trend in medieval thought, man occupied a more significant and determinative place in the universe than the realm of physical nature, while for the main current of modern thought, nature holds a more independent, more determinative, and more permanent place than man. It will be helpful to analyse this contrast more spe- cifically. For the Middle Ages man was in every sense the centre of the universe. The whole world of nature was believed to be teleologically subordinate to him and his eternal destiny. Toward this conviction the two great movements which had become united in the medieval syn- thesis, Greek philosophy and Judeo-Christian theology, had irresist- ibly led. The prevailing worldview of the period was marked by a deep and persistent assurance that man, with his hopes and ideals, was the all-important, even controlling fact in the universe. This view underlay medieval physics. The entire world of nature was held not only to exist for man’s sake, but to be likewise immediately present and fully intelligible to his mind. Hence the categories in terms of which it was interpreted were not those of time, space, mass, energy, and the like; but substance, essence, matter, form, quality, quantity—categories developed in the attempt to throw into scientific form the facts and relations observed in man’s unaided sense-experi- ence of the world and the main uses which he made it serve. Man was believed to be active in his acquisition of knowledge—nature passive. When he observed a distant object, something proceeded from his eye to that object rather than from the object to his eye. And, of course, that which was real about objects was that which could be immedi- ately perceived about them by human senses. Things that appeared different were different substances, such as ice, water and steam. The famous puzzle of the water hot to one hand and cold to the other was a genuine difficulty to medieval physics, because for it heat and cold were {53} distinct substances. How then could the same water possess both heat and cold? 119 One of the great tragedies of church history is that the Roman Catholic Church resisted the rise of modern science in the mistaken belief it was defending the teachings of the Bible rather than the medieval synthesis of Aristotle and the Bible. At the same time we agree with Dampier that 119. Edwin Arthur Burtt, The Metaphysical Foundations of Modern Science (London: Routledge & Kegan Paul Ltd., 1949), 4–5. Cf. A. C. Crombie, Augustine to Galileo (London: Mercury Books, W. Heinemann Ltd., 1961), vols. 1 and 2. The Role of Puritan-Calvinism in the Rise of Modern Science 71 A Chalcedon Publication [] 3/30/07 Bruno was burned at the stake in 1600 “and was condemned by the Inquisition, not so much for his science, as for his philosophy and his zeal for religious reform.” 120 Dampier also points out that the Papacy silenced Galileo upon the instigation of the academic world of the time, which was chiefly Aristotelian. 121 Of the evil consequences of such synthesizing, Alan Richardson writes in The Bible in the Age of Science: So well had Aquinas succeeded in Christianizing Aristotle that when the authority of Aristotle in the sphere of astronomy or physics was called in question, it seemed as though Christian truth itself was being impiously assailed. So completely had Aristotle and the Bible been harmonized in the mediaeval synthesis of natural and revealed theol- ogy that the overthrow of Aristotelian philosophy by the rise of mod- ern science seemed to the Aristotelian philosophers, though not to the new scientists themselves, to involve the rejection of the biblical reve- lation as well.... The worldview which the new scientific movement had to destroy before it could come to maturity was that based on Aristotle and Ptolemy; it was not derived from the Bible, and, in the event, the Bible has continued to exercise authority over the minds of men long after Aristotle has been deposed. 122 Both Stanford Reid in Christianity and Scholarship and R. Hooykaas in Religion and the Rise of Modern Science have argued with some justi- fication that it was mainly due to the Protestant Reformers’ rejection of the authority of Aristotle in natural and social science, and their return to the biblical doctrines of the creation of the world by Almighty God, and of the cultural mandate given to man to have dominion over the world, and of man’s calling to be God’s prophet, priest, and king in the creation, that modern science was born. In Calvin’s view of nature, according to Stanford Reid, the biblical doctrine of creation holds pride of place. The classical Greek deification of nature now gave place in Calvin’s thought to the secularization of nature. The God who has revealed Himself in the Bible is no immanent principle {54} of being or even a divine demiurge, as the Greeks had 120. Dampier, History, 124. 121. Ibid. 122. Alan Richardson, The Bible in the Age of Science (London: SCM Press, 1961), 11– 12 (emphasis added). 72 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 supposed, but a personal ruler who created the universe out of nothing (ex nihilo) according to His sovereign will. Matter as well as design and form are equally God’s creatures; neither can exist one moment apart from His divine will. Neither form nor substance, universals nor par- ticulars, can be co-eternal with God. Instead, there are two levels of reality, the eternal and the temporal. Calvin insisted that temporal real- ity forms one vast system, not of substantial forms superimposed upon an eternally preexisting and recalcitrant matter, as Plato had supposed, but of phenomena and laws. The order of nature for Calvin forms one grand machine which manifests God’s wisdom, goodness, and power. 123 Writing of the tremendous historical significance of this Reformed return to the biblical conception of nature as the creation of God, R. Hooykaas, then of the Free University of Amsterdam, said in the Free University Quarterly: Modern science arose when the consequences of the biblical concep- tion of reality were fully accepted. In the late 16th and 17th centuries science was led out of the blind alley into which it had got itself through the philosophy of Antiquity and the Middle Ages. New hori- zons were opened. The picture of the world as an organism was replaced by that of the world as a mechanism. It was not self-gener- ated but made; it is not self-supporting but it needs maintenance. 124 No early modern scientist has better expressed this mechanistic- mathematical view of nature than Galileo. In his polemical work, The Assayer, Galileo wrote: Philosophy is written in this great book, the universe, which stands continually open to our gaze. But the book cannot be understood unless one first learns to comprehend the language and read the letters in which it is composed. It is written in the language of mathematics, and its characters are triangle, circles, and other geometric figures without which it is humanly impossible to understand a single word of it; without these, one wanders about in a dark labyrinth. 125 Marjorie Grene comments upon this statement of Galileo in her Approaches to a Philosophical Biology as follows: 123. W. Stanford Reid, Christianity and Scholarship (Nutley, NJ: Craig Press, 1966), 55–77. 124. R. Hooykaas, Free University Quartely 8 (October 1961): 259. The Role of Puritan-Calvinism in the Rise of Modern Science 73 A Chalcedon Publication [] 3/30/07 So authoritative is the place of mathematical physics in our concep- tion of scientific knowledge that we take this pronouncement as the enunciation, trail-blazing in its time, of what is now a truism. Applied mathematics is the paradigm case of science, science the paradigm {55} case of knowledge; of course someday all we know or can know will be statable in strict mathematical form. 126 According to this new mechanistic view of nature, the truths of nature consist in mathematical facts; what is real and intelligible in nature is that which is measurable and quantitative. Qualitative distinc- tions, like those between colors and sounds, and so forth, have no place in the new mechanistic picture of the world. Such secondary qualities are merely modifications produced by us by the operation of determi- nate natural bodies on our sense-organs. Without this geometrization of physics and astronomy, modern science as we know it would have been impossible. Of this new view of nature Hooykaas points out: Whereas a living organism suggests the idea of an immanent final cause (the maintenance of the life of the individual), a machine finds its reason for being in the plan of its maker and outside of itself. A world organism has been generated; a world mechanism has been fab- ricated. That is why the latter fits in more suitably with a biblical view of the world. 127 Michael B. Foster has suggested that this return to the biblical view of nature as God’s creation was indispensable to the development of modern science. Only a view of the natural order which takes seriously the freedom of God in creation can give rise to the realization that the contingent regularities of nature must be investigated by direct observa- 125. Quoted by Marjorie Grene in Approaches to a Philosophical Biology (New York: Basic Books, 1968), 10. Grene then goes on to refute this mechanistic view of reality in a discussion of the views of the German biologist, Adolf Portmann. 126. Ibid., 10–11. 127. R. Hooykaas, Religion and the Rise of Modern Science (Grand Rapids, MI: Wm. B. Eerdmans Publishing Co., 1972), 15. He goes on to write, “So seventeenth century mechanistic philosophy was not a new compromise of Christianity, this time with ancient materialism instead of ancient organicism or idealism, but rather a step towards the Christianization and emancipation of natural science. Neither the de-deification of the world by the materialists, nor the rationalization of the world by the idealists, has been able to find the right pattern for science. Evidently, the mechanization of the world picture (a radical de-deification in the biblical sense) was necessary to do this” (15). 74 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 tion of the facts by experiment. It cannot be apprehended by an aristo- cratic intelligence which expects to find itself at home in a hierarchical rational order. It cannot be without significance that modern science as we know it today did in fact arise in the homelands of the Reformation, which acknowledged that God alone is the sovereign Creator of heaven and earth, nor that the most ardent and dedicated pioneers of the new scientific movement, men such as Petrus Ramus, Palissy, Ambrose Pare, Sir Isaac Newton, Robert Boyle, and John Ray, were all devoted students of God’s Word. 128 {56} The Reformation Recovery of the Cultural Mandate and the Calling The rediscovery of God’s sovereignty over His creation at the time of the Reformation not only resulted in the recovery of the biblical idea of nature as contingent upon God’s Eternal Decrees, but also led to the rediscovery of God’s world in its true dimensions. The contingency of nature was no longer viewed as a defect, as it had been in the eyes of the Renaissance Platonists, but rather an addition, by which creation is more than a mere artifact. The world has been created in accordance with God’s laws and structuring for it, and therefore we can find order in it. Man, being made in God’s image, can understand something of it but not completely or exhaustively. Man cannot read all the Creator’s thoughts after Him. Nature is not fully perspicuous to man’s reason; man, being made only in the image of God, cannot fully understand all God’s works in creation, any more than an image reflected in the mir- ror is the real object of which it is only the reflection. Such an attitude encouraged Calvinist scientists to be humble in the presence of God’s wonders in creation, even as they sought to unveil its mysteries. With this new interest in the Father’s world came the insistence that man has the responsibility laid upon him by the cultural mandate and his vocation to be God’s “prophet, priest, and king,” to develop the hid- den potentialities of God’s creation by means of his culture and science. 128. Michael B. Foster, “The Christian Doctrine of Creation” and “The Rise of Modern Science,” in Mind, n.s., 18 and 44 (1934–1936): 439ff., and 45: 1ff. For a good discussion of Foster’s argument consult E. L. Mascall, Christian Theology and Natural Science (London: Longmans, 1956). The Role of Puritan-Calvinism in the Rise of Modern Science 75 A Chalcedon Publication [] 3/30/07 Man’s culture and science were thus understood by Calvinist scientists to be the result of a divinely imposed task. Culture and science became in Calvinist-Puritan eyes just as true vocations as the sacred ministry of Christ’s church. Neither Calvin nor those who came after him held any brief for mere learning as such. Man’s knowledge and abilities must be applied to good use. They held upon the biblical grounds of the Great Cultural Mandate, or Dominion Charter, as Nigel Lee has called it in The Cen- tral Significance of Culture, 129 that God has placed man upon this earth to “be fruitful and multiply, and replenish the earth, and subdue it and have dominion” over it (Gen. 1:28). Thus, man should employ the good gifts of God for the benefit of human need and, as Francis Bacon called it, “the improvement of man’s estate.” This utilitarian approach is found not only in the writings of John Calvin but in Zanchi, Palissy, Pare, Ramus, Isaac Beeckman, Francis Bacon, and, as we shall see, in the writings of the seventeenth-century English Puritans such as John Wilkins, Ray, and Boyle. Due to this recovery of the biblical doctrine of the cultural mandate, Calvinists no longer saw the world as something evil from which man should flee, as the medieval Roman Catholic monks had tended to do. Rather, they believed that God has placed man in this world to develop its potentialities {57} to the best of his ability, that he might thereby better glorify God and better serve his fel- low men. It is not only the scientist’s business to think God’s thoughts after Him, but it is also his duty to reveal the value of scientific discovery for human life. As part of his great cultural mandate, the Calvinist scientists also believed that man is called to serve God in whatever sphere or station of life he finds himself. From this great Reformation doctrine of the call- ing, there has been derived the moral and spiritual dynamic which helped to bring about, first, the scientific revolution of the seventeenth century, and then the industrial revolution of the eighteenth. By endowing com- mon labor with Christian dignity and worth, Luther and Calvin gave the workers of Reformed lands a sense of their dignity and importance. 129. Francis Nigel Lee, The Central Significance of Culture (Nutley, NJ: Presbyterian and Reformed Publishing Co., 1976), 1–20. 76 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 As an example of what this meant in practice, we may cite the exam- ple of Isaac Beeckman, who was born of Huguenot parents in Middle- burg, Holland. His father, Abraham Beeckman, was a manufacturer of candles and water conduits for breweries, aqueducts, etc. With his younger brother Jacob, Isaac went to Leyden University to study theol- ogy. In the meantime, he also found occasion to return for some months to Rotterdam to learn mathematics and nautics. Isaac returned to Middelburg in 1601. Instead of going out preaching, he became an apprentice in his father’s business and afterwards settled on his own account as a chandler at Zierikzee in 1611. According to Hooykaas, Dr. Beeckman founded a Mechanical College in Rotterdam whose mem- bers were Beeckman himself, together with a silk-dyer, a merchant, a millwright, a shipwright, a carpenter, a physician, a mathematician, and a surgeon. 130 A generation earlier, Gresham College in London, known as “a hot- bed of Puritanism,” was founded as a similar meeting place for the learned and the mechanicians. Of this Puritan influence upon the rise of modern science Christopher Hill writes in The Century of Revolu- tion: 1603–1714: Puritan ways of thought had influence far outside the circle of religious ideas. Puritan divines insisted on the duty of actively serving God, mankind, the Commonwealth, by working faithfully in one’s calling.... The Puritan doctrine of the calling ceased to maintain “degree” and became its opposite, a doctrine of individualism. Calvinism liberated those who believed themselves to be the elect from a sense of sin, of helplessness; it encouraged effort, industry, study, a sense of purpose. It prepared the way for modern science. His- torians have noted the Protestant origins of many of the early scien- tists. The Puritan preachers insisted that the universe was law-abiding. The Reverend George Hakewill published in 1627 An Apologie or Dec- laration of the Power and Providence of God in the Government of the World. This raised the standard of the Moderns against the Ancients, and argued that scientific observation was more {58} important than traditional authority. It was man’s duty to study the universe and find out its laws. This would help to restore the human mind to the primi- tive vigour which it had enjoyed before the Fall.... Bacon called men to study the world about them, the activities of craftsmen rather than the 130. Hooykaas, Religion, 91. The Role of Puritan-Calvinism in the Rise of Modern Science 77 A Chalcedon Publication [] 3/30/07 speculations of philosophers. He referred specifically to the new industries—dyeing, glass-making, gunpowder, paper-making, agricul- ture—as proper objects of scientific investigation. He pleaded for a restoration of “the commerce of the mind with things.” “The empire of man over things depends wholly on the arts and sciences. For we can- not command nature except by obeying her.” ... Even Bacon’s method had forward-looking implications. “My way of discovering sciences goes far to level men’s wits”; it depended on the cooperative activity of many researchers. The end of knowledge was “the relief of man’s estate,” “to subdue and overcome the necessities and miseries of humanity,” “to endow the condition and life of man with new powers and works.” Learning and power were identical. Acceptance of this novel doctrine constituted the greatest intellectual revolution of the cen- tury. 131 From the practical experience of life which these practical men of science as well as craftsmen gained, there grew an increasing number of inventions and technical discoveries. It was a Dutch optician, Johann Lippersheim, who in 1605 invented the telescope and thus suggested to Galileo the means he needed for making astronomical observations. In 1590 the optician Zacharias Jansen invented the compound micro- scope. The former invention increased the scope of man’s knowledge of the macrocosm while the latter has greatly expanded his knowledge of the microcosm: between these two inventions, man’s naive conceptions of space were completely upset. 132 By uniting the logic of science with its experimental practice by means of their doctrine of the calling, the lead- ers of the Reformation perhaps rendered their greatest contribution to the advancement of modern science. The material potentialities of the new scientific attitude towards the world might have waited in vain for their fulfillment, as Benjamin Farrington has shown to be the case with ancient Greek science, 133 had it not been for Martin Luther’s recovery of the biblical doctrine that 131. Christopher Hill, The Century of Revolution: 1603–1714 (New York: Norton Library, W. W. Norton & Co., 1966), 92–94 (emphasis added). 132. Lewis Mumford, Technics and Civilization (London: Routledge and Sons, 1947), 126. 133. Benjamin Farrington, Greek Science, vol. 1 (London: Pelican Books, 1949), 141– 49. 78 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 man serves God just as much at his workbench as on his knees in God’s house on the Lord’s Day. Edgar Zilsel has indeed found the key to the rise of modern science in this alliance between the thinker and the manual workers during early modern times; a conjunction which was made possible only by the Protestant {59} doctrine of the calling. In his article, “The Sociolog- ical Roots of Science,” Zilsel pointed out that: The university scholars and the humanistic literati of the Renaissance were exceedingly proud of their social rank. Both disdained unedu- cated people. They avoided the vernacular and wrote and spoke Latin only. Further, they were attached to the upper classes, sharing the social prejudices of the nobility and the rich merchants and bankers and despising manual labor. Both, therefore, adopted the ancient dis- tinction between liberal and mechanical arts: only professions which did not require manual work were considered by them, their patrons, and their public to be worthy of well-bred men. The social antithesis of mechanical and liberal arts, of hands and tongue, influenced all intellectual and professional activity in the Renaissance. The university-trained medical doctors contented them- selves more or less with commenting on the medical writings of antiquity; the surgeons who did manual work such as operating and dissecting belonged with the barbers and had a social position similar to that of midwives. Literati were much more highly esteemed than were artists. In the fourteenth century the latter were not separated from whitewashers and stone-dressers, and, like all craftsmen, were organized in guilds.... These superior craftsmen made contacts with learned astronomers, medical doctors, and humanists. They were told by their learned friends of Archimedes, Euclid, and Vitruvius; their inventive spirit, however, originated in their own professional work. The surgeons and some artists dissected, the surveyors and navigators measured, the art- ist-engineers and instrument makers were perfectly used to experimentation and measurement, and their quantitative thumb rules are the forerunners of the physical laws of modern science. The occult qualities and substantial forms of the scholastics, the verbosity of the humanists were of no use to them. All these superior artisans had already developed considerable theoretical knowledge in the fields of mechanics, acoustics, chemistry, metallurgy, descriptive geometry, and anatomy. But, since they had not learned how to pro- ceed systematically, their achievements form a collection of isolated discoveries. Leonardo, for example, deals sometimes quite wrongly The Role of Puritan-Calvinism in the Rise of Modern Science 79 A Chalcedon Publication [] 3/30/07 with mechanical problems which, as his diaries reveal, he himself had solved correctly years before. The superior craftsmen, therefore, can- not be called scientists themselves, but they were the immediate predecessors of science. Of course, they were not regarded as respect- able scholars by contemporary public opinion. The two components of scientific method were still separated before 1600—methodical training of intellect was preserved for upper-class learned people, for university scholars, and for humanists; experimentation and observa- tion were left to more or less plebeian workers.... As long as this separation persisted, as long as scholars did not think of using the disdained methods of manual workers, science in the modern meaning was impossible. About 1550, however, with the advance of technology, a few learned authors began to be interested {60} in the mechanical arts, which had become economically so important, and composed Latin and vernacular works on the geo- graphical discoveries, navigation and cartography, mining and metal- lurgy, surveying, mechanics and gunnery. Eventually the social barrier between the two components of the scientific method broke down, and the methods of the superior craftsmen were adopted by academi- cally trained scholars: real science was born. This was achieved about 1600 with William Gilbert (1540–1603), Galileo (1564–1642), and Francis Bacon (1561–1626).... On the whole, the rise of the methods of the manual workers to the ranks of the academically trained schol- ars at the end of the sixteenth century is the decisive event in the gene- sis of science. 134 While agreeing with Zilsel’s analysis, I would point out that he has completely ignored the Reformation doctrine of the calling, which alone provided the psychological and philosophical motivation or knot tying the two components of modern science together, nor does he link Gilbert’s and Bacon’s contributions to the development of science to their Cal- vinist-Puritan presuppositions. The doctrine of the calling provided the religious sanction for both manual and experimental work. Of the signif- icance of this union of theory and practice in scientific work, Hooykaas writes: It goes without saying that this co-operation of artificers and scholars led to a rapid development and refinement of the experimental method. Manual skill and acute methodical thinking now went 134. E. Zilsel, “The Sociological Roots of Science,” American Journal of Sociology (1941–1942): 544–60. 80 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 together. Experimental work could become respectable once the mechanician’s labour became accepted as honourable. The social emancipation of the artisan class, especially in typical burgher societ- ies such as Nürnberg, Antwerp, London and Amsterdam, developed alongside a religious emancipation, which furthered an ethics of labour in which every calling, and not only that of a priest, was con- sidered as “divine.” Undoubtedly, the general familiarity with the Bible in Reformation circles stimulated this conception. The sixteenth century Puritan theologian William Perkins considered a manual trade, performed to the glory of God and the benefit of mankind, to be as blessed before God as that of a magistrate or a minister of religion. Hugh Latimer told his audience that nobody should disdain to follow Christ, the car- penter, in a “common calling,” as all occupations were blessed by His example.... The wedding service of the Netherlands’ Reformed Churches speaks of the “divine calling” of the husband. It was recog- nized that it was not manual work as such, but its toilsome nature, which was the penalty for sin. Technological improvements were sometimes considered as part of a Christian restoration, precisely because they lessened the burdensome character of manual labour. 135 The sixteenth-century medical writer, Richard Bostocke, held the view {61} that the reform of religion had been indispensable to the reform of medicine, and that Copernicus and Paracelsus had restored the sciences just as Calvin and Luther had restored religion. Referring to the new iatrochemistry, Bostocke wrote that Paracelsus “was not the author and inventor of this arte as the followers of the Ethnicks phys- icke doe imagine, ... no more than Wickliffe, Luther ... Swinglius, Calvin, etc., were the authors and inventors of the Gospell and religion in Christes Church when they restored it to his puritie, according to God’s word.” 136 135. Hooykaas, Religion, 92. 136. Quoted by S. F. Mason in “The Scientific Revolution and the Protestant Reformation,” in The Annals of Science (Philadelphia, 1953). Cf. S. F. Mason, Main Currents in Scientific Thought (New York: Abelard-Schuman, 1956). The Role of Puritan-Calvinism in the Rise of Modern Science 81 A Chalcedon Publication [] 3/30/07 The Religious Origins of Modern Scientists It might be argued by secular humanist historians and sociologists that these Calvinist-Puritan attitudes and values did not directly con- tribute to the rise of modern science, and that if they had any effect at all, it was fortuitous. In reply to this argument, I refer the reader to a study made by Alphonse de Candolle, Historie des sciences et des savants in 1885, which has since been enlarged to include a study of the religious origins of American scientists by R. H. Knapp and H. B. Goo- drich in their book, Origins of American Scientists. Both works leave lit- tle doubt that statistics show that “scientists have been drawn disproportionately from American Protestant stock.” 137 During the nineteenth century, when statistics came into vogue, de Candolle, who came of a Huguenot family of French scientists, pointed out that of the ninety-two foreign members elected to the Paris Acad- emy of Sciences from 1666 to 1883, there were only eighteen Roman Catholics as against eighty Protestants. But as Candolle himself sug- gested, this comparison is not conclusive, since it omits French scien- tists who may have been Catholic. To correct this error, he took the list of foreign members of the Royal Society of London at two periods when there were more French scientists included than at any other time: 1829 and 1869. In the former year, the total number of Protestant and Catholic scientists (who were foreign members of the Society) was about equal, while in 1869 the number of Protestant scientists actually exceeded that of the Catholics. But, outside the kingdom of Great Brit- ain and Ireland, there were in that year in Europe as a whole 139.5 mil- lion Roman Catholics and only 44 million Protestants. In other words, though in the general population there were more than three times as many Roman Catholics as Protestants, there were actually more Protes- tant than Roman Catholic scientists. 138 {62} Nor should we forget that even in the nineteenth century, when the antireligious bias of many American and European scientists was in its heyday, a large proportion of the outstanding natural scientists of that 137. R. H. Knapp and H. B. Goodrich, Origins of American Scientists (Chicago: University of Chicago Press, 1952), 274. 138. A. de Candolle, Historie des sciences et des savants (Geneva-Basel, 1885), 329–30. 82 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 century were firm believers in the God of the Bible. According to Marxist historian of science, J. G. Crowther, in The Social Relations of Science, the four most eminent British physicists of the nineteenth cen- tury were Davy, Faraday, Joule, and Clark Maxwell, all of whom were devout Christians. 139 The Relation of Calvinist-Puritanism and 17th-Century English Science Max Weber’s suggestion of a relation between Calvinism and mod- ern science, made specifically in connection with the Calvinist Puri- tans of seventeenth-century England, was taken up by Robert K. Merton, an outstanding American sociologist, and put to a careful empirical test. In his famous paper first published under the title, Science, Technol- ogy and Society in Seventeenth Century England in 1938, and now reprinted with the title “Puritanism, Pietism and Science,” in Social Theory and Social Structure, 140 Merton specifically claims that modern science is an outgrowth of the life-and-world views contained in early Protestantism and especially in Calvinist-Puritanism. Max Weber saw capitalism coming from Calvinism; Merton sees science as yet another contribution of ascetic Protestantism and its ethic. He summarizes the character of his argument with the following statement at the begin- ning of his essay: It is the thesis of this study that the Puritan ethic, as an ideal-typical expression of the value-attitudes basic to ascetic Protestantism gen- erally, so canalized the interests of the seventeenth-century English- men as to constitute one important element in the enhanced cultivation of science. The deep-rooted religious interests of the day demanded in their forceful implications the systematic, rational, and empirical study of Nature for the glorification of God in His works and for the control of the corrupt world. 141 139. J. G. Crowther, The Social Relations of Science (New York: Macmillan, 1941), 25– 45. 140. Robert K. Merton, Social Theory and Social Structure (New York: Free Press, 1967). Cf. R. K. Merton, The Sociology of Science: Theoretical and Empirical Investigations (Chicago: University of Chicago Press, 1973). 141. Merton, Social Theory, 574–75. The Role of Puritan-Calvinism in the Rise of Modern Science 83 A Chalcedon Publication [] 3/30/07 Merton isolated several facets of the Puritan ethic and practice that stimulated interest in science. He surveyed the attitudes of the contemporary scientists and concluded that these seventeenth-century scientists were indeed functioning as innovators. While they still held to the ethical values and religious goals of Calvinist-Puritan doctrine, they were engaged in a modification of the means whereby such goals were to be attained. Specifically, they were in the process of turning to nature itself rather than {63} to theological inspiration or speculation as a means of attaining Calvinist-Puritan goals. Merton examined the set of religious beliefs and attitudes which constituted seventeenth-century Calvinist Puritanism, beliefs expressed in theological writings, in ser- mons, and in books of moral guidance for the layman. It was this set of beliefs which in Merton’s view made the difference in the propensity to scientific activity. What were some of these beliefs and goals? First among the goals was the endeavor to serve and glorify God by means of scientific activity, experiment, and research. If Puritanism instilled in man the desire to glorify God in all His works, and if Puri- tanism had some bearing on the development of early modern science, then the seventeenth-century English scientist would evaluate his work in terms of the extent to which it worked toward the greater glorifica- tion of God in such scientific research. This, claims Merton, is what did in fact happen. Seventeenth-century English scientists not only pref- aced their works as being dedicated to the greater glory of God, but saw the true ends of scientific endeavor as being directed toward the glori- fication of the Creator. Merton writes of this religious sanction for sci- entific work amongst seventeenth-century English scientists as follows: Even a cursory examination of these writings suffices to disclose one outstanding fact: certain elements of the Protestant ethic had per- vaded the realm of scientific endeavour and had left their indelible stamp upon the attitudes of scientists toward their work.... Thus, in Boyle’s highly commended apologia for science it is maintained that the study of Nature is to the greater glory of God and the Good of Man. This is the motif which recurs in constant measure.... Earlier in the century, this keynote had been sounded in the resonant eloquence of that “veritable apostle of the learned societies,” Francis Bacon.... As one would expect from the son of a “learned, eloquent, and religious woman, full of puritanic fervour” who was admittedly influenced by his mother’s attitudes, he speaks in the Advancement of Learning of the 84 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 true end of scientific activity as the “glory of the Creator and the relief of man’s estate.” Since, as is quite clear from many official and private documents, the Baconian teachings constituted the basic principles on which the Royal Society was patterned, it is not strange that the same sentiment is expressed in the charter of the Society. In his last will and testament, Boyle [the founder of modern chemis- try] echoes the same attitude, petitioning the Fellows of the Society in this wise: “Wishing them also a happy success in their laudable attempts, to discover the true Nature of the Works of God; and pray- ing that they and all other Searchers into Physical Truths, may cor- dially refer their Attainments to the Glory of the Great Author of Nature, and to the Comfort of Mankind.” John Wilkins proclaimed the experimental study of Nature to be a most effective means of begetting in men a veneration for God. Francis Willoughby was prevailed upon to publish his works—which he had deemed unworthy of publica- tion—only when Ray insisted that it was a means of glorifying God. Ray’s {64} Wisdom of God ... is a panegyric of those who glorify Him by studying His works. 142 This motivation for early modern English scientific research has been confirmed independently of Merton by the researches of R. Hooykaas in Religion and the Rise of Modern Science, where he writes: The central theme of Reformed theology was “the glory of God.” Kepler wrote in 1598 that the astronomers, as priests of God to the book of nature, ought to keep in their minds not the glory of their own intellect, but the glory of God above everything else.... The same con- ception of the Two Books [of Scripture and Nature] and their parallel- ism is found in the work of Francis Bacon. 143 The Calvinist-Puritan ethic in England was also strongly utilitar- ian—that is to say, it emphasized social welfare. The early modern Cal- vinist scientists were as eager to indicate the social merit and worth of their work as they were to make it an effort dedicated to God’s glory. Moreover, scientific studies promoted discipline, hard work, and seri- ous rather than idle tongues, all good Calvinist-Puritan values. Mere abstract thinking about the world, such as Plato and Aristotle had advocated as the ideal of the scientific theorist, the Calvinists roundly rejected. Instead, they demanded that the value of science for the 142. Ibid., 575–77. 143. Hooykaas, Religion, 105. The Role of Puritan-Calvinism in the Rise of Modern Science 85 A Chalcedon Publication [] 3/30/07 improvement of man’s estate be shown. Under the Lord’s direct orders, man has been given the tremendous task of developing a material and social culture which would manifest the goodness and love of God, thus providing man with the material conditions for living the Christian life. By virtue of this religious motive, the Calvinist-Puritans, instead of running away from human culture in the interests of saving their own precious souls, sought to conquer it in the power of the Holy Spirit for Christ’s sake. Such an approach to man’s social and material environment pro- vided another religious sanction and psychological motivation for the emergence of the modern scientific attitude towards life. It broke down the centuries-old fatalism which had been content to accept man’s lot upon this earth as decreed by Fate. The Calvinist-Puritans thus rejected the medieval idea of ascetic withdrawal from the world as being unbib- lical and un-Christian. At the same time they also rejected the Renais- sance humanist ideal of man using God’s gifts in the creation merely for the satisfaction of his own selfish wants and pleasure. Instead, the Cal- vinist-Puritans insisted that man has the duty and responsibility to apply the results of his scientific research for the benefit of meeting human needs. This meant use in moderation and in accordance with the standards of righteousness, sobriety, and love for one’s neighbor which God demands of His people. {65} Of this religious motivation for scientific work, Abraham Kuyper has written in Lectures on Calvinism: ... Calvinism puts an end once and for all to contempt for the world, neglect of temporal and undervaluation of cosmical things. Cosmical life has regained its worth not at the expense of things eternal, but by virtue of its capacity as God’s handiwork and as a revelation of God’s attributes.... It is deserving of notice that our best Calvinistic Con- fessions speak of two means whereby we know God, viz., the Scrip- tures and Nature. And still more remarkable it is that Calvin, instead of simply treating Nature as an accessorial item as so many Theolo- gians were inclined to do, was accustomed to compare the Scriptures to a pair of spectacles, enabling us to decipher again the divine Thoughts, written by God’s Hand in the book of Nature, which had become obliterated in consequence of the curse. Thus vanished every dread possibility that he who occupied himself with nature was wasting his capacities in pursuit of vain and idle things. It was perceived, on the contrary, that for God’s sake, our attention may not be withdrawn 86 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07. This also explains the close relation existing between Cal- vinism and Humanism. In as far as Humanism endeavored to sub- stitute life in this world for the eternal, every Calvinist opposed the Humanist. But in as much as the Humanist contented himself with a plea for a proper acknowledgment of secular life, the Calvinist was his ally. 144 There was, then, a congruence between some of the basic tenets of Calvinist-Puritan thought and practice and those of the early men of science. For this reason, no Calvinist today need have any fear of mod- ern science, as his own spiritual forebears were mainly responsible for bringing it into existence. Calvinist values provided the religious sanc- tion and motivation for truly experimental science. The scientists could feel justified in their scientific work in the belief that such activity was meaningful, not only to the scientist as an individual but also in a much greater context—science was an entry into the works of the Cre- ator Himself and a means of service in the kingdom of God as well as the kingdom of Man. There was a greater purpose to a scientific formu- lation than the mere statement of an empirical regularity or scientific hypothesis. In the third place, the Calvinist-Puritans in England as on the Conti- nent placed a high value on human reason because God had chosen man alone to possess it and because it restrains laziness and idolatry. The Puritans {66} did not esteem the empirical world for its own sake but rather as the stage on which rational, orderly activity—so useful for science—was approved by God. The congeniality of these religious views for scientific activity is obvious. Of this Puritan stress on the importance of reason, Robert K. Merton writes as follows: The exaltation of the faculty of reason in the Puritan ethos—based partly on the conception of rationality as a curbing device of the pas- sions—inevitably led to a sympathetic attitude toward those activities 144. Abraham Kuyper, Lectures on Calvinism (Grand Rapids, MI: Eerdman’s, [1898] 1961), 119–21 (emphasis added). Cf. Abraham Kuyper’s further exposition of his views on science in his Principles of Sacred Theology (Grand Rapids, MI: Eerdmans, 1963), 56–210. The Role of Puritan-Calvinism in the Rise of Modern Science 87 A Chalcedon Publication [] 3/30/07 which demand the constant application of rigorous reasoning. But again, in contrast to medieval rationalism, reason is deemed subservi- ent and auxiliary to empiricism. Sprat is quick to indicate the pre-emi- nent adequacy of science in this respect. It is on this point probably that Puritanism and the scientific temper are in the most salient agree- ment, for the combination of rationalism and empiricism which is so pronounced in the Puritan ethic forms the essence of the spirit of modern science. Puritanism was suffused with the rationalism of Neoplatonism, derived largely through an appropriate modification of Augustine’s teachings. But it did not stop there. Associated with the designated necessity of dealing successfully with the practical affairs of life within this world—a derivation from the peculiar twist afforded largely by the Calvinist doctrine of predestination and certitudo salutis through successful worldly activity—was an emphasis upon empiri- cism. These two currents brought to convergence through the logic of an inherently consistent system of values were so associated with the other values of the time as to prepare the way for the acceptance of a similar coalescence in natural science. Empiricism and rationalism were canonized, beatified, so to speak. It may very well be that the Puri- tan ethos did not directly influence the method of science and that this was simply a parallel development in the internal history of sci- ence, but it is evident that through the psychological compulsion toward certain modes of thought and conduct this value-complex made an empirically-founded science commendable rather than, as in the medieval period, reprehensible or at best acceptable on sufferance. This could not but have directed some talents into scientific fields which otherwise would have engaged in more highly esteemed profes- sions. 145 Christopher Hill in The Century of Revolutions: 1603–1714 confirms Merton’s thesis of the contribution made by Calvinist-Puritans, espe- cially during the Commonwealth of Oliver Cromwell, when they held power. While discussing the relationship between “Religion and Ideas, 1640–1660,” Hill writes of the period as an “intoxicating era of free dis- cussion and free speculation,” and even speaks of “The Victory of Sci- ence” as follows: In this atmosphere Baconian science came into its own. Harvey’s dis- covery of the circulation of the blood, though published in 1628, obtained no prominence until after 1640. The two sides in the Civil {67} War, Miss Nicolson tells us, correspond to the two camps in 145. Merton, Social Theory, 579 (emphasis added). 88 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 astronomy. But by the sixteen-fifties the ideas of Ptolemy were dead, though those of Copernicus and Tycho Brahe still strove for the suc- cession. “The late times of the civil war,” wrote Bishop Sprat later, “... brought this advantage with them, that they stirred up men’s minds from long ease, ... and made them active, industrious and inquisitive.” This led to “an universal desire and appetite after knowledge.” Royal- ists were purged from Oxford, and a group of Baconians, the nucleus of the later Royal Society, moved into the university behind the Parlia- mentary armies. Wilkins, Cromwell’s brother-in-law, became Warden of Wadham; Goddard, Cromwell’s physician, Warden of Merton; Wal- lis, who had decoded Royalist cyphers during the Civil War, Professor of Geometry; Petty, Commonwealth surveyor of Ireland, Professor of Anatomy. For the first time in its history (and the last until very recent years) Oxford became a leading center of scientific activity. These scholars, who valued “no knowledge but as it hath a tendency to use,” attracted to Oxford men later to become famous, like Christopher Wren, Thomas Sydenham, Thomas Sprat, Robert Boyle, Robert Hooke, John Locke. Even Clarendon had to admit that revolutionary Oxford “yielded a harvest of extraordinary good and sound knowl- edge in all parts of learning” From 1650 “self-conscious science began to determine the main direc- tion of technology.” Robert Boyle disposed of the medieval theories of the alchemists, and founded the modern science of chemistry. Whereas before 1640 Bacon’s had been a voice crying in the wilder- ness, by 1660 his was the dominant intellectual influence. To this, given freedom of discussion, Puritanism had continued to contribute. The quest for personal religious experience, to which so many Puritan diaries and spiritual autobiographies are dedicated, is closely akin to the experimental spirit in science. 146 Merton’s Empirical Testing of His Hypothesis The fact that Calvinist-Puritan thought thus emphasized the reli- gious values of working unto “the glory of God,” utilitarianism, empiri- cism, and rationality might have led, says Merton, only to a fortuitous relationship to the rise of modern experimental science. Merton there- fore suggested that a significant empirical test would be to determine whether or not Puritan-Calvinists, in the early days of scientific discov- ery, were more often found within the ranks of scientists than we 146. Hill, Century, 179–80. The Role of Puritan-Calvinism in the Rise of Modern Science 89 A Chalcedon Publication [] 3/30/07 would expect on the basis of their representation in the total popula- tion of England during the seventeenth century. To determine this, Merton investigated the first-generation member- ship of the Royal Society, an “invisible college” of scientists, in its early formative years. He made a detailed and quantitative study of scientific activity in England, using chiefly the papers in the Philosophical Trans- actions of the Royal Society as his evidence. On the basis of his research Merton {68} was able to demonstrate that the number of Calvinist- Puritans who were active in science and the extent of their contribu- tions toward it were disproportionately greater than those of other reli- gious groups and particularly of the Roman Catholics. Of this investigation of the Royal Society, which he carried out not only by examining its own journal but also statistical analyses of 6,000 biogra- phies in the Dictionary of National Biography of those who comprised the intellectual elite of seventeenth-century England, Merton reports: The inception of this group is found in the occasional meetings of devotees of science in 1645 and following. Among the leading spirits were John Wilkins, John Wallis, and soon afterwards Robert Boyle and Sir William Petty, upon all of whom religious forces seem to have had a singularly strong influence. Wilkins, later an Anglican bishop, was raised at the home of his maternal grandfather, John Dod, an outstanding Nonconformist theo- logian.... Wilkins’ influence as Warden of Wadham College was pro- found: under it came Ward, Rooke, Wren, Sprat and Walter Pope ... all of whom were original members of the Royal Society.... It is hardly a fortuitous circumstance that the leading figures of this nuclear group of the Royal Society were divines or eminently religious men.... It is quite clearly true that the originative spirits of the Society were markedly influenced by Puritan conceptions. Dean Dorothy Stimson ... has independently arrived at this same con- clusion. She points out that of the ten men who constituted the “invisible college,” in 1645, only one, Scarbrough, was clearly non- Puritan. About two of the others there is some uncertainty, though Merret had a Puritan training. The others were all definitely Puritan. Moreover, among the original list of members of the Society of 1663, forty-two of the sixty-eight concerning whom information about their religious orientation is available were clearly Puritan. Considering that the Puritans constituted a relatively small minority in the English population, the fact that they constituted sixty-two percent of the ini- 90 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 tial membership of the Society becomes even more striking. Dean Stimson concludes: “that experimental science spread as rapidly as it did in seventeenth-century England seems to me to be in part at least because the moderate Puritans encouraged it.” 147 Merton then points out that this relationship between Calvinist- Puritanism and modern science was not only evidenced among the members of the Royal Society. It was also found in the new types of schools and colleges which the Puritans founded in England and America. Of this relationship between Puritan centers of higher education in grammar schools and colleges and seventeenth-century English-Amer- ican science, Merton writes: The emphasis of the Puritans upon utilitarianism and empiricism was {69} likewise manifested in the type of education which they intro- duced and fostered. The “formal grammar grind” of the schools was criticized by them as much as the formalism of the Church. Prominent among the Puritans who so consistently sought to intro- duce the new realistic, utilitarian, and empirical education into England was Samuel Hartlib. He formed the connecting link between the various Protestant educators in England and in Europe.... it was Hartlib who was instrumental in broadcasting the educational ideas of Comenius and in bringing him to England. The Bohemian Reformist, John Amos Comenius, was one of the most influential educators of this period. Basic to the system of education which he promulgated were the norms of utilitarianism and empiri- cism: values which could only lead to an emphasis upon the study of science and technology.... But the marked emphasis placed by the Puritans upon science and technology may perhaps best be appreciated by a comparison between the Puritan academies and the universities. The latter, even after they had introduced scientific subjects, continued to give an essentially classical education.... The academies, in contrast, held that a truly lib- eral education was one which was “in touch with life” and which should therefore include as many utilitarian subjects as possible. As Dr. [Irene] Parker [in Dissenting Academies in England] puts it: “... the difference between the two educational systems is seen not so much in the introduction into the academies of “modern” subjects and methods as in the fact that among the Nonconformists there was a 147. Merton, Social Theory, 583–85. The Role of Puritan-Calvinism in the Rise of Modern Science 91 A Chalcedon Publication [] 3/30/07 totally different system at work from that found in the universities. The spirit animating the Dissenters was that which had moved Ramus and Comenius in France and Germany and which in England had actuated Bacon and later Hartlib and his circle.” This comparison of the Puritan academies in England and Protestant educational developments on the Continent is well warranted. The Protestant academies in France devoted much more attention to scientific and utilitarian subjects than did the Catholic institutions. When the Catholics took over many of the Protestant academies, the study of science was considerably diminished. Moreover, ... even in the predominantly Catholic France, much of the scientific work was being done by Protestants. Protestant exiles from France included a large number of important scientists and inventors. 148 This emphasis of Calvinist-Puritans upon a scientific education may help to explain the disproportionate representation of Protestants within the ranks of scientists which has continued from the seven- teenth century. Merton adduces statistical evidence to indicate that this disproportionate participation in science by Protestants as against Catholics holds right up to modern times for the European continent, as well as for Great Britain and the United States. {70} One of the consequences or latent functions of Calvinist-Puritanism in seventeenth-century England, then, was to set the stage for the develop- ment of rational and empirical science. Merton summarizes his argu- ment by making four main observations. First, the relationships between the emerging natural science and religion were indirect and probably unintended. Second, science, once the ideological orientation and religious sanctions for its original emergence was set, then acquired a degree of functional autonomy. It acquired a character of its own, which eventually would lead to the point where science would appear to be completely removed from religious modes of thought. Third, Merton suggests that the process of the institutional modifica- tion of Christian thought and the development of new secular institu- tional forms may have been so subtle as to occur below the threshold of awareness of many of those involved in it. Fourth, the more dramatic conflict between science and religion—particularly during the nine- 148. Ibid., 585–87. 92 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 teenth century—has possibly obscured the more significant relation- ship which exists between the two. Merton was explicitly aware that his study followed in the path of Max Weber. In The Protestant Ethic and the Spirit of Capitalism, Weber had been concerned with the influence of ascetic Protestant thought upon the development of modern capitalism. But he had also sug- gested, in a very sketchy manner, that ascetic Protestantism, that is Cal- vinist-Puritanism, might be shown to have had a similar influence on the development of science. 149 Merton elaborated what Weber had left implicit and backed up his thesis with empirical evidence to prove his thesis. A Reformational-Biblical Critique of Merton’s Thesis But what exactly has Merton proved? He has proved that seven- teenth-century Calvinist-Puritanism contributed greatly to the devel- opment of a secular humanist rather than a reformational-biblical modern science. He admits as much in the following words: “The fact that science today is largely if not completely divorced from religious sanctions is itself of interest as an example of the process of seculariza- tion.” 150 But how and in what ways did such a secularization of modern sci- ence and of modern men’s conception of the universe take place? Were there elements in the Calvinist-Puritan ethos and goals, as these related to scientific activities and values, which contained within themselves the seeds of their own decay? Had the Calvinists really succeeded in bringing about {71} the reformation of science as they had in the refor- mation of religion, as Thomas Sprat claimed when he noted “the agree- ment that is between the present design of the Royal Society, and that of our Church in its beginning. They both may lay equal claim to the 149. Max Weber, The Protestant Ethic and the Spirit of Capitalism (New York: Scribner, 1958). Weber concluded his 1904-05 essay by describing one of “the next tasks” as that of “searching out the significance of ascetic rationalism, which has only been touched in the foregoing sketch ... for the development of philosophical and scientific empiricism, and for ... technical development” (182–83). 150. Merton, Social Theory, 579. The Role of Puritan-Calvinism in the Rise of Modern Science 93 A Chalcedon Publication [] 3/30/07 word Reformation; the one having compassed it in Religion, the other purposing it in Philosophy.” 151 Was this new philosophy of nature and of science as reformational and as biblical as it claimed? If so, why did it succumb so easily and so quickly to the apostate spirits of first Platonism in the seventeenth cen- tury, then Deism in the eighteenth century, and finally idealism- romanticism and scientific materialism in the nineteenth century? Was there not a fatal flaw in the Calvinist-Puritan theory and practice of natural science which doomed it from its very beginnings? Merton hints at some answers to our questions in the following passage: The beginnings of such secularization [of science], faintly perceptible in the latter Middle Ages, are manifest in the Puritan ethos. It was in this system of values that reason and experience were first markedly considered as independent means of ascertaining even religious truths. Faith which is unquestioning and not “rationally weighed,” says Baxter, is not faith but a dream or fancy or opinion. In effect, this grants to science a power which may ultimately limit that of theology. Thus, once these processes are clearly understood, it is not surprising or inconsistent that Luther particularly ... execrated the cosmology of Copernicus and that Calvin frowned upon the acceptance of many scientific discoveries of his day, while the religious ethic which stemmed from these leaders invited the pursuit of natural science. 152 Time does not permit us in the rest of this article to deal at any great length with the reasons for the secularization of Calvinist-Puritan eco- nomics, politics, and science in their intimate interdependency. How- ever, let us suggest a few factors which may have been responsible. In the first place some of the Calvinist-Puritans succumbed to the old medieval nature-grace religious ground motive, while others sur- rendered the biblical religious ground motive of creation, fall, and redemption to the new modern nature-freedom religious ground motive which grew out of the Renaissance. In either case a disastrous dualism was introduced into the Christian life. Calvinist-Puritans who returned to the nature-grace ground motive now continued to divide up human life into the realms of the sacred and the secular, looking to the Bible for guidance about religious matters and to their natural rea- 151. Mason, “Scientific Revolution,” 64. 152. Merton, Social Theory, 579–80 (emphasis added). 94 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 son and natural law for guidance about the economic, political, and scientific matters, often involving a return to Aristotelianism. Calvin- ist-Puritans who surrendered to the modern nature-freedom religious ground motive also looked to their natural reason {72} and the natural laws of the universe for a basis of their secular activities. Both camps, in short, chose to be guided by the autonomy of the natural reason and the “inner light,” at least as far as the mundane activities of life were con- cerned. The issue facing both groups was ultimately one of God’s sover- eignty and will or of man’s autonomy and rational will. In theory, both types of Calvinist-Puritans in the late seventeenth century no doubt still accepted the sovereignty of God over their lives. In actual eco- nomic, political, and scientific practice, however, they had come to adopt the traditional appeal to reason. In short, they made human reason and the appeal to experience and natural law, rather than the Word of God, the ordering principle of their scientific activities and criterion of truth. Having received little guidance from Calvin and Luther in just how to develop a biblically oriented sci- entific research and methodology, these later Calvinist-Puritans per- force had to turn to secular humanist models and paradigms. Hence the enthusiasm with which many of the Calvinist-Puritan scientists received Galileo’s doctrine that nature may best be explained in terms of the analogy of a great machine rather than in terms of a great organ- ism. But the trouble with the mechanistic picture of the world is that it is no more biblical than the classical Greek analogy of nature being thought of as a huge organism. 153 In fact the mechanistic picture of the world positively invited a deistic explanation of the world. Having built his vast machine, the Creator then simply left it to run by itself, a con- clusion the deists of the eighteenth century were only too happy to draw. In spite of Hooykaas’s acceptance of the mechanistic analogy, it should be pointed out that according to God’s revelation in the Bible, nature is thought of neither as an organism nor as a machine, but as the Lord’s creation continually dependent upon Him for every moment of its 153. Thorlief Boman, “History and Nature,” in Hebrew Thought Compared with Greek (London: SCM Press, 1960), 168–75. Cf. Robert E. D. Clark, “Creation’s Critics,” chap. 2 of The Universe: Plan or Accident (London: Paternoster Press, 1949); and Gordon H. Clark, The Philosophy of Science and Belief in God (Nutley, NJ: Craig Press, 1964). The Role of Puritan-Calvinism in the Rise of Modern Science 95 A Chalcedon Publication [] 3/30/07 existence (Jer. 10:13; Ps. 65:9; 104:27; 145:15; 147:8–9, 16–18; Isa. 28:23–29). H. Wheeler Robinson points out in Inspiration and Revela- tion in the Old Testament: No doubt this continued maintenance of Nature is effected through established ordinances and inherent energies.... But these ordinances and energies are nowhere conceived as in any sense rivals of God, or limitations on His will; they remain wholly dependent upon His con- stant support. 154 Sir Edmund Whittaker, the British historian and philosopher of sci- ence, also supports this biblical view, in The Beginning and End of the World: {73} It is necessary to guard against the deistic conception of a God who having constructed the world, left all subsequent happenings to be determined by invariable scientific laws, much as a watchmaker might construct a watch and leave it to run by its own mechanism. 155 Taking hold of whatever there was available in the scientific heritage of the Western world, the Calvinist-Puritans of the seventeenth century helped to construct a secular humanist rather than a specifically biblical- Christian paradigm or model of God’s creation, not realizing that in so doing, they had helped to secularize science by making man’s rational will rather than God’s Word the ultimate court of appeal and key to knowledge. Nowhere was this more evident than the constant appeal made by Puritans to Natural Law. In his article published in the Princeton Theological Review, titled “The Reformation and Natural Law,” in 1909, the German scholar August Lang discussed the part played by this appeal to natural law by Protestant thinkers in the secularization not only of modern econom- 154. H. Wheeler Robinson, Inspiration and Revelation in the Old Testament (Oxford: Clarendon Press, 1950), 24. 155. Sir Edmund Whittaker, The Beginning and the End of the World (Oxford: Oxford University Press, 1942), 64. Cf. Whittaker’s Space and Spirit (London: Thomas Nelson and Sons Ltd., 1946), in which he criticizes Newtonian mechanistic determinism in physics in the light of the new evidence from quantum physics. For a similar critique of scientific materialism also consult Karl Heim’s The Transformation of the Scientific World View (London: SCM Press, 1953) and C. A. Coulson, Science and Christian Belief (Oxford University Press, 1954), and Marjorie Grene’s Approaches to a Philosophical Biology (already cited in this article). 96 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 ics and politics but also of modern science. In his article Lang exam- ined the relation between the Reformation and Natural Law. He pointed out that “natural law was one of the principal historical factors in the formation of the modern spirit ... it became also the starting point for natural theology,” the broad religious basis of the religion of the English Deists and Cambridge Platonists as well as of the European movement of thought known as the “Enlightenment.” 156 How, Lang asked, “could this natural law spring up on the ground of the Reformation, take such deep root and put forth such wide-spread- ing branches?” Later in his article Lang asked the more specific ques- tion, “How did it happen that it was precisely Calvinists who first among the men of evangelical faith, and so early as the sixteenth cen- tury, not merely developed Natural Law theoretically, but at the same time as political publicists, made it a weapon in the conflicts of the time?” 157 Lang answered his own question as follows: The Reformation at its very beginning found itself in the presence of problems and exigencies of indefinite range, first of all conflicts of {74} purely religious and theological character—doctrinal, liturgical and constitutional conflicts.... Much more dangerous however was the second adjustment, which lay more on the periphery of religious truth and yet was no less necessary —namely the adjustment to the general ethical, political, and social problems of the age, to science and art. The adjustment, I say, was unavoidable, for if Protestantism, over against the Medieval Catholic world, involves a new worldview, then there must of necessity be a Protestant science of politics, a Protestant philosophy and science, a Protestant art, etc.... For such an adjustment, however, in the very nature of things, time is required; it cannot be accomplished by one man or by one generation.... Calvin had inspired in his disciples that energy of piety which abhors all halfway measures, which boldly endeavours to make all the affairs of life subject to Christ, the Head and Lord.... But what was needed, viz., firm principles about the rela- tion of the Reformation to the forces of modern emerging culture—to the state, science and art—this was lacking, and how could it be 156. August Lang, “The Reformation and Natural Law,” in Calvin and the Reformation (New York: Revell, 1909), 72ff. 157. Ibid., 57ff. The Role of Puritan-Calvinism in the Rise of Modern Science 97 A Chalcedon Publication [] 3/30/07 attained all at once in the midst of all the unrest of the time? Regarded in this way, we believe the appearance of natural law doctrine becomes comprehensible 158 Lang then examined the development of a Protestant doctrine of the state in terms of this natural law doctrine, arguing that in the absence of any clear evangelical-biblical view of the state, Protestants had “recourse to the political theory taught in the traditional jurisprudence, without heeding the fact that that theory had an origin foreign to the Reformation, and involved tendencies and consequences which would lead away from the Reformation.” 159 According to Lang a similar accommodation or adjustment took place in other cultural spheres, especially education and science. He writes: Unless all indications are deceptive, the progress of events was similar in the case of other cultural questions. The desire for knowledge, the desire for activity, which was experienced by the individual after he had been liberated through the Reformation, plunged itself into all the problems of the spiritual life of man, became absorbed in the tradi- tional manner of their treatment, and was all too quickly satisfied with solutions which were not in agreement with the fundamental ethical and religious factors of the practical religious life of the Reformation. The reaction did not remain absent. The evangelical life of faith became shallower instead of deepening itself and developing in all directions.... If it is true that the religious spirit of the Reformation in passing through Deism, was moving on a downward path, the reason for its deterioration was that the adjustment between the Reformation and culture was neither brought to a satisfactory conclusion nor even earnestly enough attempted. 160 {75} As a result of this uncritical acceptance of contemporary concep- tions of the universe put forward by secular humanist scientists, and because of their failure to redefine the basic postulates of modern sci- ence in terms of the biblical view of creation, Calvinist-Puritans in the seventeenth century found themselves unable to withstand the onrush of the new secular humanist conceptions of nature and science which 158. Ibid., 94ff. 159. Ibid., 92. 160. Ibid., 83. 98 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 emerged in the writings of thinkers such as Thomas Hobbes, John Locke, and Spinoza. For a brilliant study of the effects of the mechanization of the scien- tific picture of the world which took place during the seventeenth and succeeding centuries, the reader is recommended to read Floyd W. Matson’s book, The Broken Image: Man, Science and Society, a work which has not received the attention it deserves. Matson describes the consequences of this mechanization of the scientific picture of the world as this affected man’s understanding of his place in the cosmos. The “broken image” as used by Matson refers to man’s understanding of himself, which was fractured by the adoption of classical, Newtonian physics, the “mechanist view” of reality, as this became the model for the interpretation of the biological, social, and behavioral sciences. 161 In his book, The European Mind: 1680–1715, Paul Hazard also shows the effects of natural law thinking upon the development of Western thought, of which he writes: “Natural law was the offspring of a philos- ophy which rejected the supernatural and the divine, and substituted, for the acts and purposes of a personal God, an immanent order of Nature.” 162 In their joint book, The Puritans, Perry Miller and Thomas H. Johnson write of the influence of natural law doctrine in America as follows: The Newtonian triumph established the concept of a necessary and inviolable system of law which God Himself cannot break even though he created it. All deists were followers of Newton, and there are deistic tendencies perceptible in Puritan writings, though the more central orthodoxy strove to reconcile God’s sovereign freedom and the reign of law. Perhaps the New England orthodox rationalism is most clearly seen in Cotton Mather’s The Christian Philosopher.... Mather therein attempts to show how divine order manifests itself throughout the phenomenal universe; he sees God as a creating force in the world of nature as well as a Divine Original for man’s spirit and mind.... He quoted erudite sources at second hand, but the resulting 161. Floyd W. Matson, The Broken Image: Man, Science and Society (New York: George Braziller, 1964). Cf. E. J. Dijksterhuis, The Mechanization of the World Picture (Oxford University Press, 1961). 162. Paul Hazard, The European Mind: 1680–1715 (London: Pelican, 1964), 310 (emphasis added). The Role of Puritan-Calvinism in the Rise of Modern Science 99 A Chalcedon Publication [] 3/30/07 compendium is enriched by observations of his own which enunciate the deistic principle that God’s benevolence is manifested in a well- ordered beauty of Nature, apparent to man through his Reason. Such a point of view marks the beginning in America of the “enlightenment” which, first {76} expounded by Franklin, Paine, and Jefferson, later flowered in Emerson and Thoreau. But Mather did not abandon his essentially Puritan view that Jehovah is a jealous God who can set all law aside to intervene directly in man’s affairs. If he realized the anti- nomy, he took no step to resolve it. 163 The Part Played by Puritan Academies, Schools, and Universities in the Secularization of Modern Education and Science What part did the Puritan academies, schools, colleges, and universi- ties play in the secularization of education and modern science? The answer is, a great deal, although perhaps unwittingly. The Puritans in England and America had inherited, quite involuntarily, the classical- humanist system of education in vogue during the sixteenth and seven- teenth centuries, and this eventually came to be the first principle of education in Puritan Calvinist circles as it had been in the case of Luth- eran higher educational institutions established by Melanchthon in Germany. The curriculum taught in America’s first common day schools and colleges was a sorry synthesis of biblical and classical elements. In his contribution, “Religion and Education,” in Religious Perspectives in American Culture, Will Herberg points this out: But from the beginning, in America, secularizing tendencies made themselves felt. Even Puritan orthodoxy was not quite single-minded in its educational outlook, for the Puritans were not only the apostles of the Reformation, but also the heirs of medieval scholasticism and the humanistic Renaissance. Harvard’s first curriculum, drawn up in 1642, plainly shows the influence of four different, and sometimes divergent traditions: (1) the liberal arts tradition of the medieval cathedral schools and universities; (2) the philosophical renascence of thirteenth-century Aristotelianism; (3) the classical-humanist “revival of letters” in the Renaissance; and (4) the Reformation conviction that the fundamental purpose of all human enterprises, including educa- 163. Perry Miller and Thomas H. Johnson, The Puritans, vol. 2 (New York: Harper Torchbooks, 1963), intro. to chap. 9, “Science,” 733. 100 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 tion, was to promote the Christian faith and advance the Christian life. In other colonies, but also before long in New England, the notion of “useful knowledge,” often understood in very practical vocational terms, emerged to modify quite drastically the original religious idea informing education.... As the eighteenth century wore on, the secu- larization of educational purpose and program became increasingly evident, though the external religious framework remained virtually intact. 164 {77} This tendency to synthesize Christianity and humanism may be found at work in nearly all varieties of Puritanism. They built an edu- cational system of materials inherited from their Calvinistic forebears as well as from the philosophical schools of their age. These schools of thought relied upon the classics, ancient morality, and a pagan concep- tion of self-realization as man’s chief purpose in life; in short, upon a whole system of non-Christian thought, since man’s chief purpose in life is “to glorify God and to enjoy Him forever.” In the introduction to The Puritans, Perry Miller and Thomas Johnson write of this Puritan synthesis as follows: There is another body of assumptions, besides those underlying the Puritan philosophy of religion and of religious learning, which Puri- tans shared in common with Anglicans and even with Catholics. They were the heirs not only of medieval Christianity and of the Reforma- tion, but also of the Renaissance—they were humanists.... That a Puri- tan writer could be no less devoted to classical literature than his opponent, in spite of his theology, is demonstrated most conspicu- ously by John Milton. The miraculous fusion of Puritanism and Helle- nism which he achieved is unique only in his grandeur of expression; the same combination of religious dogma with the classics, of Protes- tant theology and ancient morality, was the aim of the curriculum at Harvard College.... 165 Likewise, M. M. Knappen also writes of this Puritan educational sys- tem in Tudor Puritanism: There is no denying that the Puritans had a zeal for learning, but it was not according to knowledge. In spite of all their devotion to this 164. James Ward Smith and A. Leland Jamison, Religious Perspectives in American Culture, vol. 2 (Princeton, NJ: Princeton University Press, 1961), chap. by Will Herberg, “Religion and Education in America,” 14. 165. Miller and Johnson, Puritans, vol. 1, 20. The Role of Puritan-Calvinism in the Rise of Modern Science 101 A Chalcedon Publication [] 3/30/07 cause, they never produced anything like a logical Puritan curriculum. They glorified the Bible, but they never worked out a course of study for which the one book would be the basis. The chief end of man was to glorify God, but Puritan students spent most of their time reading heathen authors. Though they represented a cause quite different from Renaissance humanism, they progressed little beyond Erasmus on the grammar-school level, and scarcely reached humanistic stan- dards in the universities.... In the schools where Puritan influence was strongest, Cicero and Ovid, Demosthenes and Homer continued to dominate the course of study ... there is nowhere to be found the gen- uine Christian curriculum which readers of popular expositions of Calvin’s “thoroughgoing logic” might be led to expect.... On the university level also there was a surprising lack of innova- tion.... Aristotle continued to dominate the curriculum, as he had done for generations before the Reformation ... it seems clear that his works of natural, moral, and mental philosophy, taken either straight or paraphrased in some scholastic manual, constituted the basic pre- scription for the B.A. well into the Stuart period.... Where room was found in the curriculum for the newer learning, even in the most Puritan of colleges it remained classical and humanistic, after the grammar-school pattern.... The suggestion, therefore, that Puritanism was particularly hospitable to pure learning or scientific inquiry can only be made in the same sense {78} that the Weberian thesis of its relation to modern capital- ism can be maintained. It made the negative contribution of furnish- ing a less effective barrier than Catholicism, and some of the enthusiasms it generated could be redirected to educational ends when the original objectives lost their attraction. 166 It may well be asked at this point, did not the Reformation return to the Bible as the ordering principle of life? Was there never a reforma- tion in education, learning, and science as there had been in the insti- tutional church? In order to answer this crucial question, we must investigate the development of the Reformation, particularly with respect to education and learning. Both Calvin and Luther were fully aware of the impor- tance of reclaiming all areas of life for Jesus Christ, but unfortunately their immediate successors were not. The second generation of 166. M. M. Knappen, Tudor Puritanism (Chicago: University of Chicago Press, 1939), 473–78. 102 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Reformers, especially Philip Melanchthon, were mainly responsible for the organization of Protestant higher education. It fell to Melanchthon, who had come out of the biblical humanist movement, to organize the program of higher education for the universities that had become Prot- estant. Melanchthon, however, lacked sensitivity in philosophical and structural matters. He lacked a sense of the structure of God’s creation. He felt this lack and therefore did what most people do who feel this way; he became an eclectic. This means that he took a little bit from all kinds of philosophical viewpoints—a little bit from Plato, a smidgen from Aristotle, a snuff from the Stoics, and a substantial part of the gospel— and joined them together in a synthesis representative of all move- ments. But he did this without regard to an integrating or ordering prin- ciple, that is, a central principle which alone could put order into the curriculum and provide unity of thought to any of the systems of thought from which he took parts. This is where the Protestant Reformation went astray, at least as far as the development of a Christian curriculum and a Christian science was concerned. For man’s thinking is systematic, that is to say, any thinking that has any value. There must be some central principle which integrates and organizes our experience and our think- ing if we are to make sense of the so-called facts of God’s creation around us. It is not detailed thought which gives meaning and direc- tion to our thinking. As Cornelius Van Til and his disciple R. J. Rush- doony have both been at pains to point out, individual “facts” by themselves can have no meaning. Meaning is in thoughts and “facts” only when those thoughts and facts are organized, integrated, and structured by some central principle. 167 {79} So it came about, through the work of Melanchthon and others, that the Protestant Reformation, though it believed that one should live by the Light of the powerful Word of God revealed in the Bible, took in the whole tradition of thinking about God’s creation which we know as the classical Graeco-Roman mind. 167. Cornelius Van Til, The Defense of the Faith (Philadelphia: Presbyterian and Reformed Publishing Co., 1955), and R. J. Rushdoony, By What Standard? (Philadelphia: Presbyterian and Reformed Publishing Co., 1959). See also Rushdoony’s excellent book, The Mythology of Science (Nutley, NJ: Craig Press, 1967), especially his chapter on “Paradigms and Facts,” 85–93. The Role of Puritan-Calvinism in the Rise of Modern Science 103 A Chalcedon Publication [] 3/30/07 The new program of education was then not really new at all, since it was structured by the Graeco-Roman mind, just as the education and learning of the medieval schools and universities had been. That is to say, it was dominated by a whole body of concepts and ideas which were not biblical in origin but classical humanist. Therefore, the structura- tion of the education and science at the new Protestant universities and grammar schools was not a biblical structuration in terms of the order- ing principle of God’s Word, but a Graeco-Roman one in terms of the directing principle of man’s autonomous reason and of the a priori of the natural law. 168 Of this secularization of Protestant and Calvinist-Puritan science and learning, Herman Dooyeweerd sadly wrote in the International Reformed Bulletin for July 1966: The Reformation could offer no other credentials than the claim to be an inner reformation in a truly biblical sense of the doctrine of the church, of society, indeed all of life. It was not only a theological and ecclesiastical movement. In calling for a return to the pure spirit of the Holy Scriptures, it summoned forth the driving power of the central biblical ground motive (of creation, fall and redemption by Jesus Christ) in its integral and radical meaning, in which it embraces all the spheres of terrestrial life. In the domain of science, the Reforma- tion had, by the grace of God, a great opportunity to effect a basic reform of university instruction in the countries which had aligned themselves with it. Quite unfortunately the Reformation did not take hold of this opportunity. The magnificent program of Melanchthon for the reform of education was not at all inspired by the biblical spirit. On the con- trary, it had a humanistic philological spirit, which was accommo- dated to Lutheran doctrine and which gave birth to a new scholastic philosophy. The latter, in turn, prepared the way for the humanistic secularization at the time of the Enlightenment. In the Calvinistic uni- versities Theodore Beza restored Aristotelianism as the true phi- losophy, adapting it to Reformed theology. This Protestant reform of scientific knowledge cut a miserable figure when it again took up the dualistic maxim: “For faith one must go to Jerusalem; for wisdom one must go to Athens.” It was equally dis- couraging to see in the seventeenth century the celebrated Reformed 168. Robert Lee Carvill, ed., To Prod the “Slumbering Giant” (Toronto: Wedge, 1972), especially essays by J. C. Vander Stelt and John Van Dyk. 104 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 {80} theologian, Voetius, protesting as a champion of Aristotelianism against the innovations of Descartes. The truly biblical spirit which had inspired John Calvin’s Institutes of the Christian Religion was con- quered by the scholastic spirit of accommodation, which had been imbibed from the anti-biblical motive of nature and grace. It was the driving force of this dialectical motive, the heritage of Roman Catholi- cism, which stunted the force of the Reformation and which for more than two centuries eliminated the possibility of a serious adversary to the secularization of science. This secularization was accomplished entirely under the religious influence of modern humanism. It is true that humanism categorically affirmed that the process of secularization was nothing more than a logical outworking of the genius of science itself! That was, however, a very uncritical dogma.... There has never existed a science that was not founded on presuppositions of a religious nature, nor will one ever exist. This is to say in effect that every science presupposes a certain theo- retical view of reality which involves an idea of the mutual relationships which exist between its various aspects, and that this idea, on its own part, is intrinsically dominated by a central religious motive of thought.... Modern humanism, which after the Renaissance more and more dominated the conception of science, itself has a cen- tral religious motive, which since Immanuel Kant has been called the motive of nature and freedom.... This disastrous process (of the secularization of science) was directed by anti-biblical religious motives, and neither Roman Catholicism nor Protestantism can absolve itself of its share of responsibility for the development of this secular scientific spirit. They are both responsible for this secularization in so far as they have forgotten the integral and radical nature of the biblical motive and because they have followed the Scholastic motive of nature and grace.... There are only two ways open, that of Scholastic accommodation, which by reason of its dialectical unfolding results in secularization, or that of the spirit of the Reformation, which requires the inward, radical refor- mation of scientific thought by the driving power of the biblical motive…. Let us remember the words of our Savior, “No man can serve two masters.” And let us pray to God that He will send faithful workmen into the harvest field, which is the entire earth, and which therefore includes also the domain of scientific knowledge. 169 169. Herman Dooyeweerd, “The Secularization of Science,” International Reformed Bulletin, no. 26 (July 1966): 11–17 (emphasis added). The Role of Puritan-Calvinism in the Rise of Modern Science 105 A Chalcedon Publication [] 3/30/07 To that prayer of a great and good Christian philosopher of the world under God’s law let us all repeat a hearty Amen. Conclusion: The Need for the Reformation of Modern Science What lessons can we twentieth-century Christians learn from the seventeenth-century Calvinist-Puritan involvement in the rise of mod- ern science? Standing on their shoulders it is all too easy and simplistic to {81} criticize their weaknesses while failing to recognize their great achievements. Amongst these achievements we must include: (1) the Calvinist-Puritan emphasis on conducting scientific research to the glory of God and for the benefit of mankind; (2) their obedience to the Cultural Mandate and a recovery of the biblical doctrine of the calling; (3) the Calvinist-Puritan vision of the power of science to improve “man’s estate” and elimination of sickness, famine, and misery. We can applaud Francis Bacon for writing the following passage: If therefore there be any humility towards the Creator, any reverence for or disposition to magnify His works, any charity for man and anx- iety to relieve his sorrows and necessities, any love of truth in nature, any desire for the purification of the understanding, we must entreat men again and again to discard these preposterous philosophies, which have led experience captive and triumphed over the works of God, and to approach with humility and veneration to unroll the Vol- ume of Creation. May God, the Founder, Preserver and Renewer of the Universe, in His love and compassion to men, protect the work of modern science, both in its ascent to His glory, and in its descent to the good of Man. 170 Thus we can follow the example of seventeenth-century Calvinist- Puritan scientists where they remained faithful to the biblical view of creation. But we must reject their teaching when this went astray from the biblical map of the world. For this reason we must reject their over- emphasis upon rationality and their acceptance of the mechanistic pic- ture of the creation. Such a mechanistic picture of the world inevitably led to scientific determinism and the reduction of reality to mathemat- ical equations and physical entities. It led to the scientistic notion that whatever cannot be weighed or measured is not real. Such scientific 170. Quoted by R. Hooykaas, in “A New Responsibility in a Scientific Age,” Free University Quarterly 8, no. 2 (October 1961): 9ff. 106 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 determinism and reductionism rejects the view of creation as being open to God’s intervention in either the past or the present. As Chris- tians we must always be aware of the miraculous in creation. No modern Calvinist natural scientist has expressed this sense of miracle in God’s works better than Johann H. Diemer in Nature and Miracle, wherein he speaks of the “absolute miracles of creation, providence and re-cre- ation.” Diemer then explains in his book what this means as follows: Within these miracles lie all the signs of the miraculous which appear in the course of time in various parts of the cosmos. Thus life phe- nomena have indeed a miraculous character. But their miraculous character does not lie in the breaking away from the laws of matter. It lies in their designed order, whereby the material processes are mean- ingfully directed in the service of the life processes that are in turn directed by a higher law, and finally by the law of the coming {82} of the kingdom of Christ. No single lower law can be loosened from this highest law. A miracle is not a breaking away from the lower law. It is a higher law which upholds the lower and directs it beyond itself to a higher pur- pose. The miracles of creation, providence, and re-creation are absolute. In the signs and wonders, however, there is a greater and a lesser. The miracle of creation reveals itself more in the structure of plants than in the structure of material nature and still more in the structure of the animal world. It is even greater in the structure of the human race in body, soul and spirit. But it is in the structure of the body of Christ, of the church, and of the Kingdom of God that the miracle of creation is revealed most resplendently. In the same way, the miracle of providence is revealed more in the designed relationship of organic and psychic living phenomena with the world of matter, where physical-chemical processes serve the development of life, than in the relationship of matter and space. It is even greater in the orderly interrelatedness of the human spirit with all of lower nature, whereby man’s spirit can guide and direct natural events according to higher laws. Greatest of all the signs and wonders of providence is the designed interrelationship of the Word of God with all that is created. In this relationship the Word directs the tem- poral events in accordance with the law of the Kingdom. Finally, we see the miracle of re-creation manifest itself to a larger degree in the regeneration in the plant and animal worlds than in the The Role of Puritan-Calvinism in the Rise of Modern Science 107 A Chalcedon Publication [] 3/30/07 configuration of crystals. An even greater sign of re-creation is the cure and restoration of human bodies. But the miracle of re-creation reveals itself most mightily in man’s conversion, the radical release from and cure of the sin-sickness of the soul. 171 Coming from the pen of a Dutch biologist murdered during World War II by the Nazis, such words beautifully express the religious full- ness of meaning of the whole creation as it arises out of Jesus Christ the Logos, the divine Word and Power upholding all creation. In other words, Christians today must recover the sacramental idea of the cre- ation to replace the mechanistic analogy of the universe being like a great machine. Such a sacramental conception of the creation has been ably expounded by William Temple in his Gifford Lectures, Nature, Man and God, and by L. S. Thornton in The Incarnate Lord, and in his trilogy, The Form of the Servant. 172 {83} In his book Temple tells us that he was concerned to find a concep- tion of the relation of spirit to matter which neither affirmed the supremacy of the one over the other nor denied the existence of spirit in the name of a false materialism nor rejected the existence of matter in the name of a false idealism or spirituality. Such a conception he found in the sacramental view of creation. He explains his reason for so doing as follows: ... Within the sacramental scheme or order, the outward and visible sign is a necessary means for conveyance of the inward and spiritual grace.... In many forms of religion, and conspicuously in the most extensive tradition of Christianity, prominence is given to rites in which the spiritual and the material are intimately intertwined. That proves nothing; but for those who on other grounds expect to find in religion guidance for the ultimate interpretation of reality it is sug- gestive. 171. J. H. Diemer, Nature and Miracle (Toronto: Wedge, 1977), 34–35. Cf. C. S. Lewis, Miracles (London: G. Bles, Centenary Press, 1946), especially the chapter on “Nature and Supernature,” 33–42. 172. William Temple, “The Sacramental Universe,” in Nature, Man and God (London: Macmillan, 1949), chap. 19, 473–95, and L. S. Thornton, The Incarnate Lord (London: Dacre Press, 1928). Cf. A. A. Bowman, The Sacramental Universe (Oxford, 1939), and G. C. Berkouwer, General Revelation (Grand Rapids, MI: Wm. B. Eerdmans Publishing Co., 1973), “The Nature Psalms,” 117–36. L. S. Thornton, The Form of the Servant (London: Dacre Press, 1951, 1953, 1956). 108 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Further, among those traditions which give most prominence to sacraments in the ordering of religious practice, the sacramental rite is regarded as effectual ex opere operato.... There is here an assertion—not indeed of identity, as that word is commonly understood—but of the unity of matter and spirit which is even more suggestive than the intimate relationship between them which is asserted by all use of sacraments whatsoever. But those who have clung to this conception as an interpretation of sacramental experience as an element of worship have seldom used it as a clue to the general interpretation of the universe. It is precisely this that we desire to suggest, always bearing in mind the constant and irreducible difference between man’s utilisation of existent matter and God’s cre- ation of matter ab initio. 173 Temple then went on to discuss the implications of this Christian sacramental conception of God’s creation for a Christian map of the world. He pointed out that in the Christian sacraments of Holy Bap- tism and Holy Communion it is none other than God Himself who imparts His grace to the soul of man. But how can God, who is infinite Spirit, mediate Himself to us by a material rite ex opere operato? Temple answered: ... The finite spirit can impart his thought through a physical, even an inorganic, medium; he cannot so impart himself. But the divine spirit can so impart Himself, because He is the omnipresent. All things are present to Him, and are what they are by His creative will. In and through all of them He is accessible; there is therefore no contradiction in the supposition that in and through certain physical elements, by meth- ods which He has chosen because of their appropriateness to our psycho- physical nature, He renders Himself in a peculiar degree accessible to those who seek Him through such media. 174 Temple warned of two dangers with which Christians may be con- fronted. {84} On the one hand there are those who from the scientific side insist that all physical phenomena shall be accounted for in physi- cal categories alone, and that reference to spirit or purpose shall be excluded from physical inquiry. The result is that “spirit is made to appear an alien sojourner in this material world.” On the other hand, from the religious side there is constant pressure to keep the spiritual 173. Temple, in ibid., 482–83 (emphasis added). 174. Ibid., 485 (emphasis added). The Role of Puritan-Calvinism in the Rise of Modern Science 109 A Chalcedon Publication [] 3/30/07 free from what is felt to be the contamination of the material world, which is regarded as in some way gross and unworthy. Neither view can be acceptable to the Christian in the view of Temple, who writes: In either case the unity of man’s life is broken; the material world with all man’s economic activity, becomes a happy hunting-ground for un- curbed acquisitiveness, and religion becomes a refined occupation for the leisure of the mystical. It is in the sacramental view of the universe, both of its material and of its spiritual elements, that there is given hope of making human both politics and economics and of making effectual both faith and love. 175 Earlier in the lecture on “The Sacramental Universe,” Temple made perhaps one of the most profound remarks of his amazing career when he said: It may safely be said that one ground for the hope of Christianity that it may make good its claim to be the true faith lies in the fact that it is the most avowedly materialist of all the great religions. It affords an expectation that it may be able to control the material, precisely because it does not ignore it or deny it, but roundly asserts alike the reality of matter and its subordination. Its own most central saying is: “The Word was made flesh,” where the last term was, no doubt chosen because of its specially materialistic associations. By the very nature of its central doctrine Christianity is committed to a belief in the ulti- mate significance of the historical process, and in the reality of matter and its place in the divine scheme. 176 The sacramental paradigm of the universe both avoids the pitfalls of the mechanistic and the evolutionary organic model while it includes within its own view the good elements of each. The mechanistic para- digm unwittingly witnesses to the great fact that the world is under God’s law and word and that men and women are His creatures and subject to finite-hood and limitation. The organic paradigm witnesses to the life energies with which the Creator has endowed His creation. The creation is alive and throbbing with the activities of God the Holy Spirit. The whole creation exists by the will of God the Father, Son, and Holy Spirit, and hence all other entities within it are only truly intelligi- ble and explicable by reference to the One Blessed and Holy Trinity. 175. Ibid., 486. 176. Ibid., 478. 110 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Christ is “Lord {85} over all things,” as the Greek church fathers loved to put it. 177 The whole universe is the expression of His will and design: Hence nature is “the moving image of eternity.” Such a sacramental conception of the universe also helps us to realize what Russell Maat- man has aptly termed “the unity of creation.” He writes of this idea as follows: The understanding that there is but a single power that causes all events is common to all men, and therefore the most basic fact of physical science, the existence of but a single power, guarantees that all men, Christians and non-Christians, can do science. The existence of only a single power also proves that we need not look for non-order: Non-order is not possible with God, who does not contradict Himself. Finally, Christ is King just because He has created and because all things are brought together in Him. Christ is king of all creation, not just of some part which might be labeled “spiritual.” 178 Once we begin to think and act in terms of this Christian sacramen- tal conception of the universe, we shall be motivated to develop a truly biblically founded science, not in any fundamentalistic or biblicistic sense, but in the sense of using the Word of God in the Bible as the key to all human knowledge about God’s creation and about who we are: As Diemer eloquently concluded, in Nature and Miracle: A christian science will come into being only when it begins by radi- cally banishing all philosophical ideas which are not scriptural. A christian science will come into being when it makes Revelation its starting-point. It will take concepts such as miracle, totality, design, purposefulness, potentiality, freedom of the will, and the like and test them against its own fundamental motive (grondmotief) of creation, fall, and re-creation. These concepts, which at present are found in the literature more and more, may possibly be accepted but never without testing them. In most cases these concepts have been detached from the miracle of creation, providence, and re-creation and therefore also from the root of all things, from the central absolute miracle of Reve- lation: Jesus Christ, for whom, through whom, and to whom are all things. 179 177. For a good discussion of the thought of the Greek Church Fathers, the reader should consult John Meyendorff, Christ in Eastern Christian Thought (New York: St. Vladimir’s Seminary Press, 1974), and Vladimir Lossky, The Mystical Theology of the Eastern Church (London: James Clark & Co. Ltd., 1957). 178. Maatman, Unity, 84. The Role of Puritan-Calvinism in the Rise of Modern Science 111 A Chalcedon Publication [] 3/30/07 May the Lord of heaven and earth by His Holy Spirit help all evan- gelical and Reformed scholars to become busy with the task of reclaim- ing the realms of modern education and science for the Lord Jesus Christ, so that His name may be glorified in all our Christian schools, colleges, laboratories, and universities and that Christian scientists by means of their research may witness to the wonders, miracles, and beauty of the Lord’s marvelous creation. {86} The reformation of modern natural and social science will require the concerted efforts of every available evangelical and Reformed scholar throughout the world. I plead with my fellow Christian schol- ars not to allow theological differences to stand in the way of achieving this great task of bringing modern science into subjection to the Lord Jesus Christ. Upon the successful outcome of this venture will depend nothing less than the survival of all Christians’ right and opportunity to worship God on His day and serve Him in their various occupations during the other six days of the week. The time is getting short. Nicho- las N. Kittrie warns us in The Right to Be Different: Deviance and Enforced Therapy of the growing threat posed to our freedoms by the application of behavioristic science based upon the mechanistic view of the world in controlling human conduct not only in the Soviet Union, but also here in the United States and Canada. 180 Kittrie ably docu- ments what C. S. Lewis warned us of in his lecture, The Abolition of Man, 181 as well as in his novel, That Hideous Strength. Only the refor- mation of science in terms of the sacramental conception of the uni- verse will save us from such a fate. 179. Diemer, Nature, 35. 180. Nicholas N. Kittrie, The Right to Be Different: Deviance and Enforced Therapy (New York: Penguin Books, 1977). 181. C. S. Lewis, The Abolition of Man (London: G. Bles, 1947); now obtainable from the Christian Studies Center, 314 South Goodlett St., Memphis, TN 38117. For an account of what has been done in reforming biology the reader should consult my Evolution and the Reformation of Biology (Nutley, NJ: Craig Press, 1967), in which I describe the biological thought of Herman Dooyeweerd and of J. J. Duyvene de Wit, late professor of zoology at the University of Bloemfontein, South Africa. Both scholars reject both the mechanist and vitalist view of the living cell. For a further description of this new Christian biology the reader should also consult T. Wolfe’s A Key to Dooyeweerd (Nutley, NJ: Presbyterian and Reformed Publishing Co., 1977). A Chalcedon Publication [] 3/30/07 THE EMERGENCE OF POSTMILLENNIALISM IN ENGLISH PURITANISM James R. Payton Jr. In the century between 1550 and 1650, an explicitly optimistic escha- tology developed among the English Puritans. The study and analysis of this phenomenon, with which this paper will be concerned, are complicated by two factors. First, of those who wrote systematic theol- ogies during this period, almost no one, whether on the continent of Europe or in England, included a separate locus dealing with the doc- trine of the last things. 182 Treatments of eschatological matters might appear in sections dealing with the doctrines of God, of Christ, of sal- vation, or of the church. In addition, the Puritans’ eschatological opin- ions must often be ferreted out of unexpected places in commentaries, sermons, and occasional correspondence. Because of this, one must rely upon the researches of others to a greater degree than is often oth- erwise the case in historical investigations. 183 Secondly, simply because their expectations for the future were in process of development during this period, the use of contemporary eschatological designations such as “premillennial” or “postmillennial” might seem to be an attempt to bring order where the Puritans had little or none. However, that would be an exaggeration of the situation. Although their eschatological view- 182. Dr. Richard B. Gaffin Jr., in his April 24, 1979, inaugural lecture as professor of New Testament at Westminster Theological Seminary, entitled, “The Usefulness of the Cross,” noted that separate loci on eschatology were very rare in treatments of systematic theology prior to the early nineteenth century. One of the few exceptions near the period with which this paper is concerned was Francis Turretin’s Institutio Theologiae Elencticae (Geneva, 1688). 183. Especially helpful in this regard are Iain H. Murray, The Puritan Hope (London: Banner of Truth Trust, 1971), and the work edited by Peter Toon, Puritans, the Millennium, and the Future of Israel (London: James Clarke & Company Ltd., 1970), to both of which I am indebted. The Emergence of Postmillennialism in English Puritanism 113 A Chalcedon Publication [] 3/30/07 points were rarely thoroughly integrated, systematic presentations, the Puritans nonetheless gave clear indications as to what they expected in the future. The majority of them favored an eschatological outlook which has come to be known as postmillennialism, as this paper will proceed to show. The Continental Reformers’ Influence The foundations of the Puritans’ optimistic eschatology were laid by the continental Reformers. It was not, however, to Luther that the Puri- tans {88} looked in this regard, for Luther presents a pessimistic out- look on what the church can yet expect to experience. Having undergone strife with Anabaptists and those whom he called “sacra- mentarians,” Luther reflected on the progress of the gospel and the church during his ministry as follows: At the outset of the preaching of the Gospel there were very many to whom our doctrine was appealing and who had a sincere desire and respectful attitude toward us; and powerful deeds and the fruit of faith followed upon the preaching of the Gospel. What is happening now? Suddenly there arise fanatical spirits, Anabaptists, and Sacramen- tarians; and in a short time they subvert everything that we had been building for such a long time and with so much sweat.... The devil is the author of this wickedness.… 184 This problem, to Luther, was not merely a disappointing interval which would nonetheless give way to a happy ending: those who had fallen from their pristine purity in doctrine would “never stop falling, erring, and seducing others ad infinitum.” 185 For the Saxon Reformer, the multiplication of such “sects” was a “sign of the times,” a harbinger of the grievous days into which the world was headed: Luther... states that after the fall of the Antichrist [the pope] the world will live freely and assert that there is no God. The world will become so epicurean that public preaching will be silenced and the Gospel will be contained within private houses as it was with the apostles before the destruction of Jerusalem. 186 184. Martin Luther, Lectures on Galatians (chaps. 1–4, 1535), trans. Jaroslav Pelikan, in Luther’s Works, vol. 26 (St. Louis: Concordia Publishing House, 1963), 221. 185. Ibid., 176. 114 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The only prospect for the beleaguered church would be the return of her Lord for the judgment at the Last Day—a history-ending event to which she would look with ever-increasing desire. Before then, however, the church would see nothing but increasing trouble. Such an outlook hardly fosters optimism for the course of the gospel in history. In the writings of the earliest leaders of the Reformed branch of Protestantism, on the other hand, one finds a certain degree of opti- mism with regard to the future of the church and the gospel. Calvin, indeed, seems in agreement with Luther’s pessimistic outlook in a ser- mon preached in 1558, in which he declares: Let us reckon with this fact, that the world will never be so entirely converted to God that there will not be a majority possessed by Satan and remaining stupidly in his power, who would rather perish than accept the blessing that is offered to us.... And thus let us take note {89} that the number of believers is small. But yet we must not be led astray by that. Rather we ought to realize that God is bringing to pass what He declared with His mouth.... When the Prophet cries: Who shall believe our report? ... he presupposes that they will be few in number, and that when the Gospel is proclaimed everywhere, if we take note of how many it has profited, we will find very few who have a living root and who have humbled and reformed themselves, who change their life, who renounce themselves that they may dedicate themselves wholly to God; we shall see, I say, that their number will be small. 187 Nevertheless, Calvin seems to express a very different sentiment at the close of that sermon when he says the following: Let us all come with a true humility to embrace this Redeemer who is offered to us; and let us be so mortified within ourselves that we may be raised up in the majesty given to Him, to be partakers in the life He has won for us: And that He may grant this grace, not only to us, but to all peoples and nations of the earth.... 188 What is true in the microcosm of this sermon is likewise true of the macrocosm of the Calvin corpus: he is not totally unconcerned with 186. John M. Headley, Luther’s View of Church History (New Haven, CT: Yale University Press, 1963), 252. 187. John Calvin, Sermons on Isaiah’s Prophecy of the Death and Passion of Christ, trans. T. H. L. Parker (London: James Clarke & Company Ltd., 1956), 42–43. 188. Ibid., 44 (emphasis added). The Emergence of Postmillennialism in English Puritanism 115 A Chalcedon Publication [] 3/30/07 eschatology, but he does not attempt to present a unified, coherent eschatology, either. Calvin nonetheless found encouragement and comfort in the face of that which caused Luther such grief. In 1541, after the failure of the Colloquy of Regensburg to achieve ecclesiastical reunion, he stated: Our chief consolation is... that this is the cause of God and that He will take it in hand and bring it to a happy issue. Even though all the rulers of the earth were to unite for the maintenance of our Gospel... still we must not make that the basis of our hope. So, in the same way, what- ever resistance we see offered today by almost all the world ... to the progress of the truth, we must... not doubt that our Lord will finally break through all the undertakings of men and make a passage for His word.... Let us hope boldly, then, even more than we can understand; He will surpass our thoughts and our hope! 189 Although kings and confessions might fail to unite in the gospel, Calvin was sure that the sovereign King of all nations would overcome. This emphasis on Christ’s kingship, which pervades Calvin’s teaching (without, however, becoming an integrating principle for his eschato- logical outlook), was that in the great Genevan Reformer upon which the English Puritans seized. With it as the integrating principle for their eschatology, they came to an explicitly optimistic viewpoint: 190 {90} If Calvin did not consciously focus attention upon unfulfilled proph- ecy he certainly laid foundations in regard to the understanding of the mediatorial reign of Christ which governed Puritan thought in this area. The success of the Gospel for which they yearned was bound up with their trust in Christ.... If what was predicted seemed impossible, the remedy was to contemplate more closely the authority and glory which now belongs to the Head of the Church. 191 Calvin’s emphasis upon the majesty and omnipotence of the sovereign Lord of history thus traced out the general blueprint for the eschatological edifice which the Puritans subsequently erected. Calvin was not the only Reformed leader whose outlook helped to foster eschatological optimism in subsequent generations, however. Martin Bucer (1491–1551), who had exercised formative influence on 189. John Calvin, Opera Omnia, vol. 5 (1866), 684. 190. Peter Toon, “The Latter-Day Glory,” in Toon, Puritans, 26. 191. Murray, Puritan Hope, 90. 116 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the young Calvin, played a considerable role in the drama of the Puri- tans’ eschatological development. 192 “His eschatology was less quiet- istic and more dynamic, leaving more room for the renewal of this world and for the realization of the will of God in history, than that of Luther.” 193 He asserted, on the basis of Romans 11, that the nation of the Jews was yet to be converted within history, and that their return to their true Lord would entail blessing for the entire world. 194 Peter Mar- tyr Vermigli (1500–1562), who was converted in Italy through the reading of some of Bucer’s works, came to agree with his spiritual father that Romans 11 taught a future national conversion of the Jews, which would be attended by the fulfillment of many other prophetic words not yet seen in their fullness in history. 195 As will be seen below, the English Puritans adopted and elaborated upon the understanding Bucer and Vermigli shared of Romans 11, a passage which became very important for the eschatological outlook which the Puritans ultimately came to espouse. To continue the archi- tectural metaphor, Romans 11 became the cornerstone of the structure of their eschatological expectation. The Geneva Bible The elements of eschatological hope found among the early leaders of the Reformed faith developed into a complete viewpoint among the English {91} Puritans. That development was stimulated by an attempt to destroy everything the Reformers had attempted to do. Bucer and Vermigli were both appointed to professorships in England, at Cambridge and Oxford, respectively, in the late 1540s. With these two respected leaders instructing the coming leaders of the 192. I have tried to demonstrate this in my unpublished Th.M. thesis, “The Influence of Martin Bucer upon the Development of Puritan Postmillennialism” (Westminster Theological Seminary, 1975). 193. Johannes Van den Berg, Constrained by Jesus’ Love (Kampen: J. H. Kok, 1956), 10. To date, no one has published a thorough study of Bucer’s eschatology. 194. Bucer expressed this view in his 1536 Commentary on Romans, but intimations of it appear in his Commentary on the Psalms (1529, 1532). 195. Vermigli taught this in his 1558 Commentary on Romans, written in Latin and translated into English and published in 1568. The Emergence of Postmillennialism in English Puritanism 117 A Chalcedon Publication [] 3/30/07 English church, the future must have seemed unusually bright, espe- cially since the young monarch, Edward VI (1537–1553), had shown himself far more inclined to serious reform of the church than had his father, Henry VIII. However, when the sickly Edward died, his half-sis- ter Mary (1516–1558), who was still loyal to Rome, came to the throne. She lost no time displaying her antipathy to the reform movement, and many of the Protestant leaders went into voluntary exile on the Conti- nent. The opposition of “Bloody Mary” actually served to strengthen their theological convictions as well as give them the opportunity to produce a powerful weapon used to attack the influence of Rome and anything which smacked of that influence. That weapon, which became as well a tool for the erection of an optimistic eschatology, was the Geneva Bible. Its Impact upon England Many of the English exiles went to Geneva, where they came directly under the influence of Calvin, the great leader of the Reformed move- ment in Europe. In the 1550s, Geneva was a center of biblical scholar- ship, and those who now suffered exile for the faith of the Scriptures naturally turned their hearts to that place where much was being done to further the cause of evangelical truth. New editions of the Greek New Testament, the Hebrew Old Testament, and the Vulgate appeared from Genevan presses, as well as translations of the Bible into Italian, Spanish, and French. In that environment, it is hardly surprising that the leaders of the English community set about translating the Scrip- tures into their native tongue. In 1560, their efforts were crowned with the publication of that version which came to be known as the Geneva Bible. 196 This Bible exerted great influence on the piety and theological development of England in subsequent generations. It ran through some two hundred editions between 1560 and 1644, and it was during that century that the English people emerged from biblical illiteracy to become a nation thoroughly conversant with the Scriptures. 197 196. Lloyd E. Berry, intro., The Geneva Bible—A Facsimile of the 1560 Edition (Madison, WI: University of Wisconsin Press, 1969), 7. 197. Lewis Lupton, A History of the Geneva Bible, I (London: The Olive Tree, 1966), 14. 118 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Although other versions were available in England, it was preeminently the Geneva Bible which was read and studied. A number of reasons account for this. First, the Geneva Bible, unlike {92} its predecessors, was published in a portable size rather than only in large, unwieldy volumes. Secondly, it progressed beyond previous English translations by dividing the books not only into chapters, but the chapters into verses. Further, this version included illustrative woodcuts, maps, indices of names and subjects, and calculations of the years from Adam to Christ as well as dates of the early church from Paul’s conversion onwards. On each page concise summaries indicated the contents of the page, and at the beginning of each book and chapter a description of the argument contained in it appeared. The most sig- nificant reason for the Geneva Bible’s popularity, however, was its mar- ginal notes, 198 the purpose of which the translators themselves explained: godly and learned brethren, to gather brief annotations upon all the hard places, as well for the understanding of such words as are obscure, and for the decla- ration of the text, as for the application of the same as may most appertain to God’s glory and the edification of his Church. 199 The annotations were later attacked by some Anglican leaders, and they were directly opposed by King James I 200 as factious, but in a later 198. Berry, Geneva Bible, 12–15. 199. “To our Beloved in the Lord” (the reader’s preface), iiiib, The Bible and Holy Scriptures Contained in the Old and New Testament. Translated according to the Hebrew and Greek, and conferred with the best translations in diverse languages (Geneva: Rowland Hall, 1560). Both here and in subsequent references to the Geneva Bible the spelling has been modernized. 200. Berry, Geneva Bible, 15, reports the direction King James gave to those who would eventually translate the Bible version which he authorized: “...he gave this caveat … that no marginal notes should be added, having found in them which are annexed to the Geneva translation ... some notes very partial, untrue, seditious, and savoring too much of dangerous, and traitorous conceits” (spelling modernized). The Emergence of Postmillennialism in English Puritanism 119 A Chalcedon Publication [] 3/30/07 age Bishop Westcott described them in a more sober manner as “pure and vigorous in style, and, if slightly tinged with Calvinistic doctrine, yet on the whole neither unjust nor illiberal.” 201 The men who trans- lated and annotated this version were, although “neither unjust nor illiberal,” zealous and thoroughgoing Protestants of Reformed stripe, and those who followed in their paths were known in England as Puri- tans. Significantly, the Geneva Bible came to be looked upon as “the Puritan Bible,” 202 both by the Puritans and by their opponents. This version was never officially authorized in {93} England, but “it was only the opposition of those who disliked the Puritans which pre- vented it....” 203 Its reception and use by so many of the laity and the clergy amounted to a popular authorization, however, and it is not unreasonable to suggest that many Englishmen were probably either brought to a Puritan position or were confirmed in it by their diligent study of this Bible and its marginal notes. An Anglican clergyman of a later period supported this idea when he stated: This country was overrun by Puritanism in the reign of Elizabeth. This Puritan spirit was fostered and encouraged by the Calvinistic notes which appeared in the margins of the Genevan Bible. Its use will at least go far to account for the almost uniformly Calvinistic tone of all English Divinity during the time of Elizabeth and James I. This was the system of doctrine adopted by quite all the reformers of Elizabeth’s reign. 204 The widespread acceptance and use of the Geneva Bible in England 205 makes a study of its theological perspectives an important 201. B. F. Westcott, A General View of the History of the English Bible (London: Macmillan & Company, 1872), 93. 202. This is the title W. J. Heaton gives to his study of the Geneva Bible (London: Francis Griffiths, 1913). 203. Lupton, History, 19. 204. The Rev. N. Pocock, as quoted in Charles Eason, The Geneva Bible—Notes on Its Production and Distribution (Dublin: Eason & Son Ltd., 1937), 1 205. The popularity of this version was not confined to England: it became the most widely used translation in the rest of the English-speaking world, as well. In Scotland, the Geneva Bible was set apart as the version to be read in the churches, and in the American colonies, it was the favorite version in Virginia and appears to have enjoyed exclusive use in the Plymouth plantation (Berry, Geneva Bible, 20–22). 120 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 part of the attempt to understand and appreciate the whole theological development of English Puritanism, including its eschatological out- look. Surprisingly, no such study has appeared, and it would certainly be beyond the scope of this paper. It is nevertheless possible for us to note the fact that one of the main elements of optimism in the thought of the early Reformed leaders found its way into the marginal notes of the Geneva Bible, and that the viewpoint espoused in those notes became the cornerstone of the eschatological edifice of English Puri- tanism. Its Annotations at Romans 11 In the 1560 edition of the Geneva Bible, the marginal comments at Romans 11 express the translators’ expectation that the nation of the Jews would yet be converted in history and that their conversion, in conjunction with the “fullness” of the Gentiles, would mean great blessing for the world at large. When Paul stated in 11:26 that “all Israel shall be saved,” the annotators commented, “He showeth that the time shall come that the whole nation of the Jews though not every one par- ticularly shall be joined to the Church of Christ.” The comment on the apostle’s declaration in 11:15 that the Jews’ reception into the church would be “life from the dead” said that “the Jews now remain, as it were, in death for lack of {94} the gospel: but when both they and the Gentiles shall embrace Christ, the world shall be restored to a new life.” 206 What is startling about this note is that it does not represent the viewpoint of their distinguished host in Geneva, for Calvin did not expect a future conversion of Israel. Rather, the understanding expressed in the notes was almost certainly borrowed from Martin Bucer, with whose whole theological position, in general, and 1536 Commentary on Romans, in particular, several of the translators of the Geneva Bible were well acquainted. 207 In later editions of the Geneva Bible, these annotations were further expanded and came to express, even more forthrightly, a sure confi- 206. Emphasis added. 207. Peter Toon suggested that the source may have been Theodore Beza (Puritans, 6), and Iain Murray argued that it was probably Vermigli (Puritan Hope, 42). In my Th.M. thesis (see note 192), however, I have shown that the source was, rather, almost certainly Martin Bucer (65–72). The Emergence of Postmillennialism in English Puritanism 121 A Chalcedon Publication [] 3/30/07 dence in a tremendously fruitful future for the gospel, the church, and the world. For these expansions, the views of Theodore Beza (1519– 1609), expressed in the various versions of the New Testament which he published in 1565 and in subsequent years, were formative: In 1576 the Puritan Lawrence Tomson ... brought out an edition of the Genevan New Testament. Although there were some revisions in the text, mainly from Beza’s later work, the substantial changes were in the marginal notes, which were based on those of Beza.... In 1587 a quarto edition of the Geneva Bible was brought out with Tomson’s New Tes- tament and notes substituted for those in the 1560 edition, and from this time on some editions had the Tomson and some the original notes. 208 At Romans 11, the Beza-Tomson New Testament augmented the previous notes by asserting that the expected conversion of Israel was an event clearly predicted by the Old Testament prophets. 209 It should hardly be surprising that “life from the dead,” the promised result of the Jews’ future conversion, also came to be viewed from the perspective of the prophetic descriptions of the universal, glorious work of God in the latter days. The early Puritan leaders used the Geneva Bible, since it was obvi- ously superior to the other available English versions and because its marginal notes expressed outlooks with which they agreed. Although other means of arriving at a common understanding of Romans 11 must not be discounted, the Geneva Bible certainly exercised consider- able influence on the consensus which emerged among the English Puritans that Paul had prophesied, in accordance with other passages of Scripture, a glorious future for the gospel. {95} The Influence of William Perkins Some of those who had labored in the translation and annotation of the Geneva Bible, having returned to England subsequent to Elizabeth I’s accession (in 1558), grew dissatisfied with certain aspects of official policy and outlook within the English church—among them were Miles Coverdale, William Whittingham, William Cole, and Thomas 208. Berry, Geneva Bible, 15. 209. Toon, Puritans, 24. 122 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Sampson. Their opposition became known and they thus became the nucleus of the Puritan party that subsequently developed. 210 Their leadership within the incipient movement, coupled with their eschato- logical expectations as expressed in the “Puritan Bible,” ensured that the early Puritan movement would be disposed to eschatological opti- mism. Several of the leading Puritans of the next generations clearly and forthrightly expressed their agreement with the exegesis of Romans 11 found in the Geneva Bible’s annotations. William Perkins (1558–1602), Richard Sibbes (1577–1635), Thomas Brightman (1562–1607), Elnathan Parr (?–1632?), John Cotton (1584–1652), Thomas Goodwin (1600–1680), and John Owen (1616–1683), in addition to a multitude of lesser lights, all expected Israel’s future conversion and attendant blessing. The figure who towered over the rest, as regards the influence he exercised on Puritan thought, was William Perkins. Perkins was the dominant theological influence in Puritanism for forty years beyond his death. 211 The most influential Calvinist of his day, 212 Perkins was one of the select few whose works were so pro- found, yet simple, so powerful, yet winsome, that those who read them were almost inevitably moved, no matter what their station in life or their educational background. Perkins’s works were so well received that they were translated into French, Dutch, Italian, Spanish, 213 and Latin, going through numerous editions, both in England and abroad. 214 Of the above-mentioned leaders of Puritanism, Parr, Sibbes, Cotton, and Goodwin either were students of Perkins or else studied under those at Cambridge who carried on Perkins’s influence in the years immediately following his retirement from his duties at Cam- bridge in 1595. 215 Thus, these other Puritan stalwarts imbibed the 210. Peter Toon, Puritans and Calvinism (Swengel, PA: Reiner Publications, 1973), 13. 211. Christopher Hill, Puritanism and Revolution (London: Secker & Warburg, 1965), 216. 212. Thomas F. Merrill, intro., William Perkins, 1558–1602, ed. Thomas F. Merrill (Nieuwkoop: B. De Graaf, 1966), ix. 213. Hill, Puritanism. 214. August Lang, Puritanismus und Pietismus (Neukirchen: Erziehungsverein, 1941), 108–9. The Emergence of Postmillennialism in English Puritanism 123 A Chalcedon Publication [] 3/30/07 teachings of Perkins and passed them on to those who came under their {96} tutelage. Consequently, Perkins’s eschatological views were doubtlessly very influential upon those of very many other Puritans. In a treatise specifically concerned with certain eschatological ques- tions, written in 1587 but not published until several years later, Per- kins expressed his views at an early stage in his own teaching career. In the work he engages in dialogue a person who believed that the return of Christ would occur in 1588. Perkins first distanced himself from his companion’s attempt to set the approximate date for that event and then proceeded to argue that certain of the “signs” of Christ’s coming had not been fulfilled. Their fulfillments, according to Perkins, would precede, not attend, the Lord’s return. 216 Two of the signs Perkins then went on to list as yet awaiting fulfillment were the proclamation of the gospel to every nation (which he noted was being more and more accomplished every day) and the conversion of the Jews (which had not taken place and would require a substantial amount of time). 217 Perkins’s expectation for the future did not change, for in his Commentary on Galatians, published early in the seventeenth century, he spoke again of Israel’s future conversion. In commenting on the cov- enantal promise to Abraham in Genesis 12:3, he said, .” 218 By means of the Geneva Bible’s influence and William Perkins’s dominance, this understanding of national Israel’s future and that of the church of which she would become a part became a commonplace among the English Puritans. 219 215. Hill, Puritanism, 216–17. 216. William Perkins, A Fruitful Dialogue Concerning the End of the World, in Works, vol. 3 (printed for W. Welbie, 1613), 467–70 (spelling modernized). 217. Ibid., 470. 218. Quoted in Murray, Puritan Hope, 42. 219. Ibid., 43. 124 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The Puritans’ Optimistic Eschatology The Puritans were, of course, too careful in theological and exegeti- cal matters to base any firmly held conviction upon a single verse or short passage from Scripture when that verse or passage could be explained in another manner. The Beza-Tomson notes on Romans 11 affirmed and the Puritans agreed that not only Romans 11, but many other passages of Scripture as well, taught a future conversion of the people of Israel. Romans 11 may have afforded the clearest statement of that which they believed, but they found the concept taught in many other places in the Bible. From the {97} New Testament, they looked upon the following passages as supporting their teaching: Matthew 23:38–39— “Behold, your habitation shall be left unto you desolate. For I say unto you, ye shall not see me henceforth til that ye say, Blessed is he that cometh in the Name of the Lord.” Luke 21:24— “And they shall fall on the edge of the sword, and shall be led captive into all nations, and Jerusalem shall be trodden under- foot of the Gentiles, until the time of the Gentiles be fulfilled.” 2 Corinthians 3:15–16— “But even unto this day, when Moses is read, the veil is laid over their hearts. Nevertheless when their heart shall be turned to the Lord, the veil shall be taken away.” In the Old Testament, the Puritans found a spate of passages speak- ing of Israel being turned to the Lord, of nations falling before Him in worship, and of the great blessings upon the entire earth which would surely come as a result of God’s bestowing His riches of grace upon multitudes of peoples who would turn unto Him. 220 Among these Old Testament references, one cited very often was Isaiah 11:9, which promised, “the earth shall be full of the knowledge of the Lord, as the waters cover the sea.” By viewing such prophecies as forerunners of the teaching of Paul in Romans 11, teaching further confirmed by other New Testament passages, the Puritans believed they had a very solid basis for holding to an optimistic view of the future of the gospel and of the church in the world, all because of the sure blessing of their sover- 220. Among the ones used by the Puritans were Job 8:7; Psalm 2:8; 22:27; 67:2, 5; 72:7–8; 86:9; Isaiah 2:2–4; 11:7–9; 22:12–14; 24:21; 26:11; 45:22; 49:6; 60:9, 17–18; Ezekiel 38:8; 40:3; 45:8; Zephaniah 2:11; Haggai 2:7; Zechariah 4:10; and Malachi 1:11. The Emergence of Postmillennialism in English Puritanism 125 A Chalcedon Publication [] 3/30/07 eign God. Therefore, a closer examination of two very influential expo- sitions of Romans 11 is necessary. The Puritan Exegesis of Romans 11 In exegeting Romans 11, Thomas Brightman, who was a contempo- rary of William Perkins, pressed beyond previous English expositions of the chapter by arguing that the “fullness” of the Gentiles (v. 25) con- verted before the conversion of the nation of Israel (v. 26) did not pre- clude the idea of a further ingathering of Gentiles, since Paul had already argued that “life from the dead” would accrue to the church and the world at large because of the Jews’ entrance into the Body of Christ. 221 Brightman thus left the length of time between the full entrance of the majority of Israel and the end of the world at Christ’s return an open question. In so doing, at the very least, he paved the way down which an eschatology could travel which posited a lengthy period of time subsequent to the conversion of the Jewish nation, before the return of Christ. As will be seen below, Brightman himself traversed that path. {98} Although Brightman’s exposition was influential among the English Puritans, the Commentary on Romans published by Elnathan Parr in 1620 became the most popular Puritan treatment of that epistle. 222 In it he strictly defended the exegesis of the 11th chapter which foresaw a future national conversion of Israel, but he also addressed himself explicitly to the question which had arisen among the Puritans regard- ing what might transpire between the conversion of the Jews and the end of the age. Parr divided the 11th chapter into two parts: the “principal matter,” he said, with which the apostle is concerned is treated in verses 1–32, and the conclusion is given in verses 33–36. Within the main argument of verses 1–32, Parr distinguished the apostle’s arguments that the rejection of the Jews is not total (vv. 1–11) and that it is not final (vv. 12–33). 223 In commenting on the “fullness of the Gentiles” (v. 25) to be brought into the church, Parr emphasized that this would, of course, take place through the proclamation of the gospel, “whereby many of 221. Murray, Puritan Hope, 46. 222. Ibid. 126 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 all nations shall be converted to God.” 224 Israel would come into the church (v. 26) by the same manner, according to Parr: they would be “converted by the preaching of the Gospel.” 225 Parr had to answer a question which had been raised by the Reform- ers of the sixteenth century and could consequently modify one’s understanding of what Paul taught in the chapter and any eschatologi- cal hopes built thereupon. He distanced himself in his answer, from that of Calvin and that of Melanchthon, when he strongly objected to interpreting “all Israel” (v. 26) as referring to the sum total of the elect of both the Jews and the Gentiles (the “spiritual Israel” concept). For Parr, that interpretation did not do justice to Paul’s description of what he was saying as a “mystery” (v. 25). His telling objection was, “Paul saith that he would not have the Gentiles ignorant; of what? That all the elect should be saved? Whoever doubted it? But of the Calling of the Jews there was a doubt. He calls it a secret or mystery; but that all the elect should be saved is no secret.” 226 To the question regarding the proximity of the end of the age, Parr could not give a definite answer from Romans 11. He said, “The end of this world shall not be till the Jews are called, and how long after that none yet can tell.” 227 This did not mean, however, that Parr thought Paul had not given perspectives on the question within the chapter— only that the {99} chapter did not specifically deal with the final events of history. He asserted that “life from the dead” (v. 15) certainly spoke of the fulfillment in history of the many prophetic declarations regard- ing the blessings of God upon the nations bowing before Him. 228 In expositing that phrase, Parr noted that it could not have reference to the resurrection at Christ’s return, for Paul was dealing in the context with the mercy proclaimed in the gospel and experienced in its recep- 223. Elnathan Parr, A Short View of the Epistle to the Romans, in Workes of that faithfull and painefull preacher, Mr. Elnathan Parr, 3rd ed. (London: G. P. for Samuel Man, 1633), 149. 224. Ibid., 197 (spelling here and in subsequent references modernized). 225. Ibid. 226. Ibid. 227. Ibid., 199. 228. Ibid., 177. The Emergence of Postmillennialism in English Puritanism 127 A Chalcedon Publication [] 3/30/07 tion. To assert that Paul spoke, then, of the resurrection was for Parr impossible to maintain, since the resurrection of the dead at Christ’s second coming “is the time of revealing judgment, not of preaching mercy.” 229 Since it would be “absurd” 230 to think of a further proclama- tion of the gospel in some period subsequent to the return of the Lord for judgment, “life from the dead” had to speak of what would occur in history prior to the second coming. He noted that others had backed away from affrrming such a viewpoint, since they “would deny that ever there shall be a more glorious face of the Church than is now at this present: this can be by no means admitted.” 231 What was inadmissi- ble for Parr was not only the exegesis, but especially the idea that the church would not see better days before the return of her Lord. Those better days were exactly what Paul had prophesied, according to Parr, when he spoke of “life from the dead.” The expositions of Brightman and Parr exercised great influence among the Puritans of England, for both men were recognized leaders and authorities. 232 To be sure, no Puritan would agree with every point of interpretation of every other Puritan, but they were in real agree- ment on their basic comprehension of Romans 11 and the eschatologi- cal expectation to be derived from it. 233 Puritan expositions of Romans 11 held at least the following five factors in common: 1..... 3. In the economy of salvation there is an interaction appointed by God between Jew and Gentile; gospel blessing came to the world by Israel’s fall, yet a greater blessing will result from her conversion. 229. Ibid., 176. 230. Ibid. 231. Ibid. (emphasis added). 232. Murray, Puritan Hope, 45–46. 233. A fuller treatment of Puritan expositions of Romans 11 can be found in ibid, 61– 76. 128 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 4. Nothing is told us in Romans 11 of the duration of time between the calling of the Jews and the end of history.... {100} 5. The quotations from Isaiah and Jeremiah [in vv. 26–27], confirming Paul’s teaching, indicate that the full extent of gospel blessings predicted by the Prophets is yet to be realized. 234 An optimistic eschatology was, thus, the viewpoint of the English Puritans. Convinced as they were that the Antichrist had been revealed (as the pope in Rome), that God had been at work in history (as could be seen in the Reformation of the sixteenth century) and that He would certainly continue to be, encouraged as they were that their spreading movement was a harbinger of better things to come, both in England and in the world, the Puritans did not build their hopes for the future upon their exegesis of events they were experiencing. Rather, the cor- nerstone of their eschatological edifice of sure hope was their common understanding of Romans 11, to which the elements just mentioned played a confirmatory role. The English Puritans expected Israel to be converted after a great multitude of the other nations of the world had embraced the gospel. By means of Israel’s turning to her Lord, still oth- ers from among the nations would confess Him as their Lord, as well. Upon all this, the Ruler of the nations and Savior of the church would pour out nearly unimaginable blessing, so that an era would surely come, within history, the like of which had never before been experi- enced. Premillennial or Postmillennial? This optimistic eschatology could be structured in either of two ways: 235 one could opt either for what would today be called “premil- lennialism” (with the return of Christ being the cause of Israel’s conver- 234. Ibid., 76. 235. Within Reformed circles in recent years, a variety of eschatology has arisen which calls itself “optimistic” amillennialism. A glaring difference exists between this type of “optimism,” however, and that of the Puritans. For “optimistic” amillennialism, the optimism consists in a hope that the gospel will yet enjoy great success before the return of Christ, but the proponents of this eschatological viewpoint admit that they are not convinced that such will be the case from scriptural arguments. The Puritans’ optimism arose from their conviction that Scripture promised that such advance would take place. The Emergence of Postmillennialism in English Puritanism 129 A Chalcedon Publication [] 3/30/07 sion as the beginning of the period of blessing) or for “postmillennialism” (with the return of the Lord coming after the period of blessing upon the world). As a matter of fact, both views, in their embryonic forms, found supporters within English Puritanism, but one clearly predominated over the other, and it consequently devel- oped more fully. Thomas Brightman was a leader within the latter school of thought. In his Commentary on Revelation, published in Latin in 1609 and in English translation in 1615, he asserted that the Jews would be won to their true Messiah by the preaching of the gospel, that the Gentiles would further be drawn by that same gospel, that there would follow a great increase in {101} the understanding of the Scriptures, and that this would all usher in the “latter-day glory” of the church. This period of glory he called the “Kingdom of Christ” because then Christ’s Word in the Scriptures would increasingly become the scepter used in the government of the nations of earth. 236 According to Brightman, such submission and its consequent blessing would be the fulfillment of many biblical prophecies which yet awaited their historical accom- plishment: Now shall the end of all the prophets come, when all the enemies shall be utterly and at once abolished, and when there shall be one sheep- fold made upon earth, of all the Elect both Jewes and Gentiles under one shepheard Jesus Christ. It is certain that this Kingdom of Christ that is thus begun, shall be eternall, and shall never be broken off againe, and discontinued.... 237 The fulfillment of these prophecies would take place during the “Kingdom of Christ,” an extended period subsequent to the conversion of the nation of Israel, at the close of which Christ would return. 238 Clearly, Brightman’s is an early but relatively well-developed form of postmillennialism. In his opinion, Scripture taught a “latter-day glory” for the church within history, and that not only in Romans 11, but also in the Apocalypse. In this matter, Brightman was a leader to many other English Puritans. 239 236. James A. De Jong, As the Waters Cover the Sea (Kampen: J. H. Kok, 1970), 21–22. 237. Quoted in ibid., 19. 238. Toon, Puritans, the Millennium, and the Future of Israel, 31. 130 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The leader and primary authority in the premillennial school of English Puritan eschatology was Joseph Mede (1586–1638). In his study of the Apocalypse (published in Latin in 1627, enlarged in 1632, and published in English translation in 1642) he posited a future mil- lennial reign of the saints upon earth, in which the church would indeed know great security and blessing. How this reign would be inaugurated, however, was a matter upon which Mede differed from Brightman. For Mede, both the conversion of the Jews and the initial erection of the kingdom would be accomplished by a visible appear- ance of Christ. 240 Mede supported this idea by a detailed comparison he developed between the conversion of Paul and the future conversion of Israel, in which the experience of Paul became normative for that of his fellow Israelites. 241 The third of the ten points of similarity which Mede set forth said, “The Jews not to be converted unto Christ by such means as were the rest of the {102} Nations, by the Ministry of Preachers sent unto them; but by the Revelation of Christ Jesus in his glory from Heaven....” 242 He elaborated upon this point in his fifth comparison, which declared, “The Jews, together with their miraculous Calling, shall be illuminated also with the knowledge of the Mysteries of the Christian Faith, without any Instructors from them or conference with them....” 243 Thus, according to Mede, the Jews would see Christ in a visible appearance, would be converted individually and nationally by that sight, and would be brought by that vision to a reception of the whole of the Christian faith, all without any influence of the Gentiles. In fact, as his eighth point of similarity indicated, Mede expected the Jews, not the Gentiles, to be the evangelizing force in the erection of the kingdom. 244 “Till the Calling of the Jews, the general Conversion of the Gentiles not to be expected; but the receiving of Israel shall be the 239. Ibid., 31–32. 240. R. G. Clouse, “The Rebirth of Millenarianism,” in ibid., 56–60. 241. Joseph Mede, “The Mystery of S. Paul’s Conversion: or, The Type of the Calling of the Jews,” in The Works of the Pious and Profoundly-Learned Joseph Mede, 4th ed. (London, 1677), bk. 5, 891–92. 242. Ibid., 891. 243. Ibid. The Emergence of Postmillennialism in English Puritanism 131 A Chalcedon Publication [] 3/30/07 riches of the world, in that by their restitution the whole world shall come unto Christ.” 245 Both Brightman and Mede influenced English Puritan eschatology, but not as many Puritans sympathized with Mede. 246 This is hardly surprising, for Mede’s position is in conflict with the history of Puritan interpretation of Romans, in that he denied Israel would come to Christ through the proclamation of the gospel. Further, his position doubtlessly appeared to many Puritans inconsonant with the very bases of their whole theological approach, since they affirmed the sov- ereignty of Christ as King and the mighty power He exercised through the Holy Spirit unto the conversion of the entire number of His elect. Thus, Mede’s position would appear to sully the emphasis on the medi- atorial kingship of Christ, as well as that on covenant theology. In the framework of covenant theology, espoused by the English Puritans, God the Father exalted Christ to His right hand and gave Him the Holy Spirit to pour forth upon the church. Through the Spirit’s power, the church proclaimed the gospel of Christ. Since it is the gospel which is the “power of God unto salvation” (Rom. 1:16) for both Jew and Gentile, a gospel which cannot be heard “without a preacher” (Rom. 10:14), it is only by the gospel that any could be drawn to Christ. Since, further, Christ as King now rules over all the nations and disposes all for the good {103} of His church (Eph: 1:22), and the Holy Spirit who applies the redemption of Christ does so only by means of that gospel, to expect any other means or to rely upon any- thing else than the Spirit-accompanied proclamation of the gospel for the ingathering of either Jews or Gentiles would amount to abandon- ment of covenant theology! 244. Mede’s position is thus substantially different from that of many contemporary premillennialists, in that the erection of the kingdom is not accomplished by an abiding physical presence of Christ in His regal splendor and power. 245. Mede, “Mystery,” 892. 246. Clouse notes that Mede exercised influence on some Presbyterian Puritans and several Independent Puritans (“Rebirth,” 62). B. S. Capp suggests that the Fifth Monarchy Men may have their eschatological roots in the writings of Mede, as well, in “Extreme Millenarianism,” in Toon, Puritans, the Millennium, and the Future of Israel, 66. 132 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Thomas Brightman, on the other hand, stood in the line of Perkins and the Geneva Bible in expecting the Jews’ conversion to take place through the proclamation of the gospel, and Elnathan Parr, in the most popular Puritan exposition of Romans, espoused the same position. Consequently, Brightman’s position proved much more attractive than that of Mede, and the majority of the Puritans embraced a postmillen- nial eschatology. Whether they followed Brightman in every detail of his expectations—comparatively few of them did 247 —or merely adopted the basic outlines of the eschatology he set forth, most English Puritans came to hold to postmillennial opinions in the 1630s and 1640s. They had learned from Calvin to find comfort and confidence in Christ’s mediatorial kingship, they structured their theology in a covenantal framework, and a postmillennial viewpoint best fit with these two emphases. Nearly every Puritan expected Israel’s conversion and a subsequent period of extensive and intensive blessing for the church and the world. Most of them expected this to occur before the return of Christ, and the way in which it would eventuate was no great theological problem: The kingdom of Christ would spread and triumph through the power- ful operations of the Holy Spirit.... inevi- table progress in history ... but asserted that the sovereign purpose of God in the gospel, as indicated by the promises of Scripture yet unful- filled, points to the sure hope of great outpourings of the Spirit in the future. 248 Confessional Status It is hardly surprising that the eschatological viewpoint espoused by the majority of the Puritans found expression in their confessional documents. Concerned as they were at the time of the Westminster 247. Brightman held, for example, to a continuing special significance of the land of Palestine and the city of Jerusalem, an idea uncongenial to many, but not to all, of his fellow Puritans. 248. Murray, Puritan Hope, 51. The Emergence of Postmillennialism in English Puritanism 133 A Chalcedon Publication [] 3/30/07 Assembly for a unified church in England which would profess empha- ses the Puritans had elicited from Scripture, they would be cautious about structuring confessional statements in such a manner that other Puritans would immediately {104} feel excluded. Consequently, one should not expect to find in the Westminster standards an explicit dis- avowal of premillennialism. Nevertheless, with the help of the above historical background, one can easily discern a basically postmillennial approach. In The Directory for the Publick Worship of God, issued by the West- minster divines and approved and established by Parliament in early 1645, the minister is encouraged to lead the congregation in praying for “the propagation of the gospel and kingdom of Christ to all nations; for the conversion of the Jews, the fullness of the Gentiles, the fall of Antichrist, and the hastening of the second coming of our Lord....” 249 The inclusion of the prayer for the hastening of Christ’s return could readily be countenanced by premillennialists then, indeed, but it was not inconsonant with the postmillennialism to which the majority of the Puritans held: none of them would pray for a delay of that return, and all of them would have affirmed that any prayer must be guided by understanding of what Scripture taught. Consequently, such prayers would not preclude a postmillennial viewpoint, and it can be readily seen that both eschatological positions could be reconciled with the suggested petitions. More significantly, however, the means empha- sized in the prayer for conversion of Jew and Gentile was the propaga- tion of the gospel. This is, as we have seen, one of the main strands of traditional Puritan thought that had been in evidence since the time of the 1560 Geneva Bible, had been explicitly affirmed by Perkins, Bright- man, and Parr, and had flown directly into explicitly postmillennial eschatology among the English Puritans. In The Larger Catechism, Question 191 asks what is requested in the second petition of the Lord’s Prayer. The answer in part is, “we pray, that the kingdom of sin and Satan may be destroyed, the gospel propa- 249. The Confession of Faith, the Larger Catechism, the Shorter Catechism, the Directory for Publick Worship, the Form of Presbyterial Church Government, with references to the proofs from the Scriptures (London: William Blackwood & Sons Ltd., 1969), 141–42. 134 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 gated throughout the world, the Jews called, the fulness of the Gentiles brought in....” 250 Again, premillennial viewpoints are not explicitly excluded, but the views of Mede and his followers found no clear sup- port, whereas postmillennial eschatology did: it is again the gospel by means of which Jews and Gentiles are to come to Christ, not a visible appearance of the Redeemer. All of this is very significant, for William Twisse (ca. 1578–1646), who had served as prolocutor of the Westminster Assembly, was a strong and forthright premillennialist. He had written commendatory prefaces to two of Mede’s eschatological works, including his study on the Apocalypse, {105} in both of which he affirmed his agreement with Mede. 251 Although certain others among those who took part in the deliberations at Westminster likewise favored premillennialism, that viewpoint is much less easily discerned in the productions of the assembly than one might expect. Rather, the most straightforward understanding of the eschatological outlook of the Westminster Assembly’s documents, seen in their historical perspective, is postmil- lennialism: The document is silent ... on all those points which set premillennial- ism off from other, milder versions of millennialism. Rather, in the context of the views current then, Westminster’s formulation must be seen as a deliberate choice of mild, unsystematized postmillennial expectations. 252 Ten years after Parliament adopted the Westminster documents, the Independent churches adopted the Savoy Confession of Faith. By this time, the desired unity of faith and ecclesiastical organization had 250. Ibid., 109. 251. Clouse, “Rebirth,” 62. 252. De Jong, As the Waters, 38n11. It ought to be pointed out at this point that the Westminster standards, given their historical context, do not advocate that view of eschatology which has subsequently arisen and appears to be flourishing in Reformed theology called “amillennialism.” To be sure, an amillennialist might be able to interpret the statements in the Directory and the Larger Catechism in the same manner as he usually would the mention of “Israel” in Romans 11:26, as a reference to the “spiritual Israel” of the entire body of the elect (either of all nations or of all physical Jews converted in the whole of history). Nevertheless, the very inclusion of the terms, “Jew” and “Gentile,” ought to strike the typical amillennialist as unusual, at the very least. The Emergence of Postmillennialism in English Puritanism 135 A Chalcedon Publication [] 3/30/07 become a chimera, and the Puritans of the Independent party were less reticent than their predecessors in the Westminster deliberations had been to declare their eschatological position with utter clarity. By and large, the Savoy document is the Westminster Confession of Faith with certain relatively minor modifications suited to portraying various Independent distinctives. 253 This document is quite explicit in its advocacy of a basic postmillennial outlook, as can be seen from the last section of its twenty-sixth chapter, “Of the Church,” which states: As the Lord in his care and love towards his Church, hath in his infinite wise providence exercised it with great variety in all ages, for the good of them that love him, and his own Glory: so according to his promise, we expect that in the later days, Antichrist being destroyed, the Jews called, and the adversaries of the Kingdom of his dear Son broken, the Churches of Christ being enlarged and edified through a free and plentiful communication of light and grace, shall enjoy in this world a more quiet, peacable and glorious condition than they have enjoyed. 254 {106} Conclusion It has been our purpose in this paper to trace the development of English Puritanism’s optimistic eschatology. In broad strokes, we have accomplished that, noting a gradual but sure progression from Calvin’s emphasis on the sovereign King of all nations and Bucer’s exegesis of Romans 11 to confessional declarations espousing the simple postmillennialism held by the majority of English Puritans during the 1630s and 1640s. It has not been part of our purpose to assess how this eschatology affected the Puritans’ views of society, economics, or political endeavor. That the Puritans drew connections between their eschatological out- look and their expectations for these other areas can scarcely be doubted by anyone familiar with the Puritan mind. An attempt to sketch out such influences, however, would have unduly enlarged the scope of this already generalizing study. An examination of the interre- 253. For a helpful, concise discussion of the differences between the Westminster and Savoy documents, see Peter Toon, Puritans and Calvinism, 77–84. 254. The Savoy Confession of Faith, in The Creeds and Platforms of Congregationalism, ed. Williston Walker (Philadelphia: Pilgrim Press, 1969), 396 (emphasis added). 136 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 lationships would certainly be a valuable contribution, both to histori- cal research and to the attempt to advise contemporary heirs of the Puritans how to integrate their own eschatological expectations with the various areas of their life, that of the church, and that of the nation. It is certainly to be hoped that others will undertake such studies. In the meantime, however, let it be noted that the English Puritans expected progress to be made by the gospel and the church throughout the whole world—progress which would lead to the fulfillment of many more prophetic declarations in history than had been seen to that point. They entertained no doubt that the Word of their covenant Lord, the sovereign King of all nations and of history, demanded of them that optimistic eschatology we know as postmillennialism. A Chalcedon Publication [] 3/30/07 PURITY AND PROGRESS: NEW ENGLAND’S FIRST GENERATION Aletha Joy Gilsdorf [The essay’s subheads have been added by the editor] The times required reformation. At the end of Queen Elizabeth’s reign, a Protestant England had conceded this. Antichrist had to be repudiated; the man of sin had to be struck down once and for all. The fruition of God’s plan for the redemption of His elect demanded it. But what was anti-Christian and what was not? Men searched the Word of God and, striving to recreate a primitive purity, created controversy. Nearly all were agreed that a sufficient reformation of doctrine had been achieved by the Elizabethan settlement. The controversy was over other matters—specifically the ordinances of worship and church gov- ernment. Did the Scriptures justify the wearing of vestments, the use of set prayers in God’s worship? Who was to exercise the power of church discipline, particularly the ordinance of excommunication—the pas- tors of each congregation or the bishops? And what was the proper relationship between church and state? Should those who governed the church be granted civil authority too, as were the bishops? Some insisted that all these problems had been rightly solved at the beginning of good Queen Bess’s reign. The established Anglican Church did not conserve anti-Christian corruptions but godly tradi- tions sanctified by age—old usage. But other men—Puritans—were convinced that a more complete reformation was necessary. In particu- lar they demanded a purer discipline in the churches—one under the control of godly ministers who would be denied magisterial powers and thus freed from the temptations of politics. As all men knew, the degeneracy of the Church of Rome had come about because the pope had greedily engrossed great temporal as well as spiritual power. Chris- tians must be wary of believing that “this honour is given unto us, either to trouble the civile State, or els to intermingle Church-governe- 138 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 ment with civile.” 255 Still other men, Separatists, insisted that only a total departure from the institutions of Antichrist would suffice to ful- fill the requirements of the times. The visible church should properly be constituted of believers only—men prepared to acknowledge {108} the regiment of Christ by voluntarily placing themselves under the dis- cipline of His church. Only congregations thus created could be sure of having left the ways of the beast completely behind. Another group, perhaps even fewer in number than the Separatists, felt that this kind of congregational reform could and should take place within the Church of England. This they believed was necessary to preserve the continuity of the church throughout history. All of these different opinions on the amount of reformation required by the exigencies of the times did agree in one respect, namely, that the most strenuous of efforts to purify the church neces- sarily had to be limited to externals. Worship could be pared to the bare bones of sermons and sacraments; censures and admonitions could be used to exclude the obviously profane and profligate from communion; churches could be covenanted out of godly professors. But in every case it was beyond the power of men to create a church that was as pure in substance as it was in form. No church on earth could require its members to be absolutely regenerate. God alone knew the constituency of His elect; and until the second coming of the Son of Man, the earthly church and the heavenly church would never be iden- tical. In time one of these groups—by far the most conservative—gained ascendancy in the English church and began to entrench the kind of reform that stretched only as far as doctrine. With a king on the throne whose sympathies were anything but Puritan, the hope for further ref- ormation seemed dim indeed. A handful of Puritans—those who believed the Church of England should be purified from within along congregational lines—decided to try their method in America. There, to the consternation of their colleagues at home, they came to the con- clusion that a virtually pure church could be created in this world sim- ply by excluding all but the visibly regenerate from membership. 255. Thomas Brightman, The Revelation of S. John Illustrated with an Analysis and Scholions, 3rd ed. (Leyden, 1616), 19. Purity and Progress: New England’s First Generation 139 A Chalcedon Publication [] 3/30/07 Assuming as a calculated risk that a certain number of hypocrites would slip through their rigid screening process, they were still pre- pared to maintain that they could discern the workings of grace or the lack thereof within the hearts of other men. In Massachusetts the invis- ible church was about to solidify before the skeptical eyes of the world. The obvious question, of course, is why they suddenly became con- vinced that a visibly regenerate church membership was both neces- sary and possible in the campaign against Antichrist. There was no precedent for their decision in English reform. In fact, when they first arrived, they were apparently committed at most to no more than churches composed of professing believers—men and women whose godly conversation and affirmation of a “historical faith” distinguished them from obviously profane and obstinate sinners. During the first few years of the colony’s existence, church membership required no confession of saving grace. Of course, {109} the people who came to Massachusetts were highly familiar with the process by which a man acquired such grace. Their ministers in England had been educating them in the mysterious operations of the Spirit upon human minds and hearts for at least a generation. By 1630 the answer to that burning question of the Reformation, “How can I know whether I am saved?” had been scaled down to a last, irreducible nubbin of uncertainty by Puritan preachers. But while the New England Way was inconceivable without such knowledge, by itself, it was no warrant for insisting upon a regenerate church membership. Nobody in England up to this time— for all their preoccupation with the process of regeneration—had felt called upon to advocate such a step. In New England the innovation seems to have been introduced by John Cotton, a highly respected leader of Congregationalist reform in the old country. Cotton, who had been associated with the Massachu- setts venture from its inception, did not actually arrive in the colony until 1633, whereupon the newly founded churches—apparently under the influence of his preaching—soon began to require evidence of regeneration before admitting new members. But the most interesting thing about Cotton’s innovation is that only three years before he had held an entirely different view of church membership. In 1630 he cer- tainly would not have denied admittance to people whose only qualifi- cations were an understanding of church doctrine and a good 140 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 conversation. 256 Sometime between 1630 and 1633 Cotton had come to the conclusion that saving faith, which he considered the essence of the invisible church, should also be made the essential ingredient of the earthly church. Cotton’s reasons for changing his mind will probably never be known. He himself attributed the change to a further study of the Scriptures—which passages he did not specify—that convinced him participation in the covenant of grace was the sine qua non of church membership. “The Covenant of Grace doth make a People, a joyned People with God, and therefore a church of God.” 257 The aspiration toward purity in a man or in a nation, in other words, was genuine only if it sprang from a principle of grace. Mere rigidity in externals was not a manifestation of grace but of a false and legal righteousness. “When men have received ease from God, and then are straightlaced towards their Brethren, then doth the Lord revoke his Pardon. So that Reforma- tion is no assurance that God hath made an everlasting Covenant with us. And mind you further, All the Graces that you have laid hold upon, have sprung from your own Righteousness.” 258 If men in this reform- ing age wished to remake the church on earth, they {110} must per- force begin with the pure in heart—the visible saints. Indeed, it might well be that the next step in the divine plan to defeat Antichrist would be just such a manifestation of Christ’s kingdom in visibly regenerate churches. If reformation proceeded by degrees from one age to the next toward ultimate consummation and if this were truly the last age—as the existence of Antichrist implied—then it stood to reason that the purification of forms already achieved should logically be followed by a purification of the substance of the church. Thomas Goodwin Whether or not Cotton actually reasoned in this way during the three years before he came to America, we shall probably never know. But there is evidence that by 1639 he was specifically associating the 256. Edmund S. Morgan, Visible Saints: The History of a Puritan Idea (New York: New York University Press, 1963), 64–112. 257. John Cotton, A Sermon Preached ... at Salem, 1636 (Boston, 1713), 21. 258. Ibid., 31. Purity and Progress: New England’s First Generation 141 A Chalcedon Publication [] 3/30/07 idea of a visibly regenerate church with the second coming. In that year he preached a long series of sermons expounding Revelation, some of which were taken down in shorthand and eventually published in Lon- don. The series, however, is not complete; and before we examine Cot- ton’s writings in greater detail, therefore, it might be useful to look at an exposition on Revelation written by another important advocate of the New England Way—Thomas Goodwin. Goodwin was a Puritan cler- gyman who became a leader of congregational reform—or Indepen- dency, as it was called—during the Civil Wars and the Interregnum. Outside of America, he was probably the foremost theologian of the New England Way. His analysis of the Apocalypse, which like Cotton’s was written in 1639, is of particular interest for our problem since he was converted to Independency by Cotton in 1633, just before the lat- ter sailed to New England. In Goodwin’s eyes the book of Revelation was a coherent, logical, and tightly constructed piece of work, comparable in fact to a well- written play. God, revealing the story of His kingdom within history, had done so as skillfully as the greatest playwright. In St. John’s vision—just as in ordinary plays—the stage was set, a chorus provided to give judgment and approbation (“the custom in comedies of old”), and a prologue read. The history of the kingdom thus began with a description of the church—the stage upon which the true meaning of man’s sojourn on earth would become apparent. The chorus was pro- vided by its members, who throughout the ages “upon any great or sol- emn occasion [gave] their plaudite or acclamation of glory unto God.” 259 All of this was represented to St. John in the vision of the throne, the four beasts, and the twenty-four elders described in the fourth chapter of Revelation. Like his predecessors, Goodwin too regarded this chapter as depicting the church sub species aeternitatis. It was “a representation of the church (wherein God hath his throne) {111} of men on earth, universal in all ages; set forth according to the form or pattern of institution of a church, into which all saints on earth should be moulded.” 260 Naturally this universal pattern was a simple 259. Thomas Goodwin, The Works of Thomas Goodwin, ed. John C. Miller, 12 vols. (Edinburgh, 1861–66), vol. 3, 1. 260. Ibid., 2. 142 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 one. In the ideal church there were but two components—the congre- gation and its officers. The elders represented the brethren who held “the radical power,” while the four beasts were the officers who, “though nearest the throne, yet are mentioned after the elders; for though their place be nearer, yet they are but the church’s servants.” 261 Once the stage was set, the prologue showed how Christ had taken upon Himself the work of redemption of the elect, having the power and providence not only to know but to execute the decrees of God for all time. Finally, after the prologue had been read, “God’s design and project upon the world” began to unfold, and the drama of the church in the world—from Christ’s ascension to His return—was played out for the edification of all ages. Goodwin saw the church’s story in much the same way that his predecessors had seen it. Essentially it was a tale of gradual decline from primitive godliness to the depths of anti-Christian corruption and equally gradual ascent into the light of the Reformation. Above all, it was a description of the execution of Christ’s government in history, “first, in putting down all opposite rule and power that stand in his way ... and, secondly, in a visible taking the kingdom to himself and his saints, which makes the fifth monarchy.” 262 The rough outline of the story went like this. Upon His ascension to heaven, Christ had found the Roman Empire—the fourth monarchy—spread throughout the world. Everywhere He was to seat His kingdom and church, He found the dominion of Satan. Hence He began the conquest of the world by preaching the gospel and within three hundred years had subjected the empire to Himself by converting it and its rulers to Christianity. But in revenge for previous persecutions against His saints, Christ brought down Rome’s imperial power and divided the empire into two parts by means of the wars of the Goths in the west and those of the Saracens in the east. The western empire was divided again into ten kingdoms, all of which consented to give their power to the pope, who thus restored the Roman monarchy to its full glory. In both east and west during this period of dissolution, Christ had sealed up 144,000 saints—men who 261. Ibid., 4. 262. Ibid., 27. Purity and Progress: New England’s First Generation 143 A Chalcedon Publication [] 3/30/07 had opposed, however unsuccessfully, the rising tide of corruption and degeneracy. But now, with the pope on one hand and the Turk on the other, “Christ [had] a new business of it yet, to come unto his kingdom, and as difficult as ever.” 263 Therefore, He brought forth seven vials—con- taining the seven last plagues—to dispatch the pope and the Turk and wholly root them out. With the appearance of these vials, the world entered into its last age— {112} the time in which Christ would bring His earthly kingdom to perfection through the total destruction of His enemies. Here the Apocalypse told the story of the church “both in respect of the progress of its separation further and further off from Rome, and so of its increase of light, purity, and reformation; as like- wise in respect of persecutions and judgments upon it, and its restitu- tion and deliverance again from under them.” 264 The first vial had been poured out upon Antichrist by the Walden- sians, who about the year 1100 had erected true churches and preached a doctrine of both law and gospel. Their persecution and consequent dispersal throughout Europe had been the means of furthering the spread of truth and light. From their descendants, Wyclif, Huss, and Jerome of Prague had learned that the pope was Antichrist and had been inspired to advocate reforms in the church. Their work had marked the pouring out of the second vial. The third one was embod- ied in the preaching of Luther. He had shown beyond a doubt that sep- aration from Rome was mandatory for God’s saints and had thus prepared the way for the fourth vial, which was the present period of “glorious peace and sunshine of the gospel.” After the grievous perse- cutions of earlier ages, the church was now enjoying a time of harvest during which the elect were being converted and gathered in by the preaching of the gospel. Most important of all, “this preaching of the gospel, that hath reaped this corn, hath been authorized by the chief magistrates, and by kingly power, even whole kingdoms professing.... Jesus Christ, the Son of man, is visibly set in the throne, ruling by Christian magistrates, they using their power for him.” 265 But after har- 263. Ibid., 28. 264. Ibid., 80. 265. Ibid., 89. 144 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 vest comes vintage, and the vintage which even now was following the harvest of the elect was one of vengeance. God was cutting down the wild grapes in His vineyard and casting them into the winepress of His wrath: And these grapes are those carnal Protestants and professors of religion, who together with the elect, have enjoyed the heat of this fair long summer, and hung like to grapes in the sun, but retaining their sourness, have been ripened indeed, but only for wrath and ven- geance. And lo, how this sharp sickle hath gone up and down in Ger- many for well-nigh these twenty years, being such a winepress of fierce wrath, and such a treading down to an overflowing of blood and misery, as hath scarce been paralleled in any age! For it is the ven- geance of the temple, not so much destroyed, as defiled and disho- noured by their mixture; which as much provokes God unto wrath as the persecution of his temple would have done. 266 All of this—both harvest and vintage—was contained within the fourth vial. There were three yet to go, and these three would encom- pass the final destruction of the powers of darkness. The fifth, which would strike at the seat of Babylon (i.e., Rome), Goodwin thought was just beginning. {113} It would be completed about 1666 and would be followed by the destruction of the Turks (the sixth vial). Then the remnants of the forces of the pope and Turk would unite with all the evil kings of the world and fight against the Christians and Jews—who would have been converted in 1650—until “Christ himself comes and makes but one work of it, with his own hand from heaven destroying them.” 267 This victory would initiate the millennial reign of Christ, and Goodwin pre- dicted that it would take place in 1700. This, then, was the outline of the story of the church from Christ’s ascension to the end of time. But the part of it which most interested Goodwin was the part that applied to his own age. “The main thing I aimed at, both in my first studying this book, and also in this my expo- sition of it, was to search into such passages therein as did concern and fall upon the last days, especially the present times of the church; and to inquire and find out under which of these constellations our own 266. Ibid. 267. Ibid., 28. Purity and Progress: New England’s First Generation 145 A Chalcedon Publication [] 3/30/07 times do fall, and what is certainly yet to come.” 268 And to the end that he might properly present his findings concerning the last days, Good- win devoted over half of his book to a detailed analysis of the period from “the Church’s separation from Popery” to the appearance of New Jerusalem. The whole of this period Goodwin divided into three “ref- ormations,” each corresponding to certain vials and each described in a separate chapter of Revelation. The first of these was the “separation of the church from Antichrist in several degrees”—the reformation of doctrine and worship already accomplished by the first reformers. It corresponded to the first four vials and, as we have seen, brought the church up to Goodwin’s time. The second reformation was just begin- ning with the end of the fourth and the start of the fifth vials. It was to be a purification of the membership of the church. Finally, the last ref- ormation—which would bring history to a close—was to be a “refor- mation personal, of the saints themselves in it, as then with might and main preparing and adorning themselves for the marriage of the Lamb, which then they shall evidently see approaching, now when the whore is cast off and burnt; and there you may see them getting all the fine linen they can—that is, of holiness and growth in grace, ‘the righteous- ness of the saints.’ ” 269 Before this glorious third reformation could be consummated, how- ever, the membership of the church had to be purified from its present “profane mixture.” The second reformation, in other words, was the work now required of the saints in God’s plan for the church, and Goodwin took care to expound the chapter in which it was described— chapter 11—at length. This chapter, more than any other in Revelation, Goodwin felt exactly represented “the present face, the affairs, stirrings and alterations now {114} a-working in the churches of Europe.” 270 In this part of his vision, St. John is commanded by an angel to measure the temple, the altar, and the worshippers which appear before him, expressly omitting the outer court of the Gentiles. Goodwin inter- preted this act as a representation of the “face of the church” in the age “wherein Antichrist’s reign is drawing near its end”—”(this age, as I 268. Ibid., 78. 269. Ibid., 82. 270. Ibid., 124. 146 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 take it).” 271 The temple, of course, was the church, and St. John’s mea- surement of it the reformation that would make it “more answerable to the pattern in the mount.” Omitting to measure the outer court meant that the church was to be purified of its profane mixture of carnal and unregenerate professors. For even though true churches had already been set up during the first reformation—by virtue of the elect hidden within them—they were yet defiled by the presence of this outer court “into which all sorts came.” They were, therefore, more outward courts than inward temples, and their promiscuous mixture of regenerate men with carnal professors permitted great corruptions both in church fellowship and in church worship. Hence it was the duty of the saints to carry reformation one step further by purging the visible church of its unregenerate members. And observe the glorious wisdom that is in God’s proceeding herein, as the reason of it. For God intending to have a church most holy unto himself, under the seventh trumpet, in which “the ark shall be seen”…and his manner being to carry on his church unto perfection by degrees,—he doth therefore, about the midst of that time, between the first reformation long since made and that seventh trumpet, in an age or so foregoing it, set his builders to work (whom John here rep- resents) to endeavour to erect a new frame, and a reformation of that reformation; and to take the reed, and measure over anew both tem- ple, altar, and worshippers, and to cast out that outward court of wor- shippers, with those corruptions of theirs which hindered that thorough reformation; and so to contract his temple into a narrower compass, as the proportion of the inner temple to the outward was, yet purer and more refined, he delighting more in truth, and purity of worship, than in magnitude or multitude of sacrificers and worship- pers: and so to make himself a church that shall consist of priests, and an inward temple separated from that outward court, into which the true worshipers are called up from the other, which before lay com- mon to both. 272 Goodwin was careful to point out that by the inner temple he did not mean the invisible communion of God’s elect, which existed apart from any visible church. The imagery of the inner temple and the outer court was not a type of the old distinction between the visible and invisible 271. Ibid., 122. 272. Ibid., 128. Purity and Progress: New England’s First Generation 147 A Chalcedon Publication [] 3/30/07 churches. The temple, in fact, represented “churches or congregations of public worshippers considered as such; church-fellowship, as you call it.” 273 {115} The altar represented the ordinances of worship, and the worshippers, of course, were the saints. The act of measuring was simply: By the word exactly putting a difference between them that fear God and them that fear him not; measuring out who fear him by marks, signs, and spots upon his people, (as in Deuteronomy God speaks,) which the word gives. And this distinguishing and putting a difference between men and men, the word calls excluding or leaving them out. Which, accordingly, to make way for the right constitution of churches, in discerning the true matter of them, hath been the chief work of the godly ministers in England in this last age; who, though they wanted the ordinance of excommunication in their churches, yet in lieu of it they had excommunicating gifts, and were forced, because of that profane mixture in churches, to spend most of their ministry in distinguishing men, by giving signs and marks of men’s natural and regenerate estates, and convincing and discovering carnal men to themselves and others: which God in providence ordained, to make way for the erection of more pure churches. For by this light was set up in godly men’s hearts a spirit to discern between the clean and the unclean; and so to hew and set apart the materials for this temple, as the stones for Solomon’s were. 274 But in spite of his emphasis on the necessity of constructing churches out of pure (i.e., regenerate) members, Goodwin did not believe the church would become absolutely pure before the advent of the New Jerusalem. Until that time there would always be hypocrites in the church—despite the most stringent requirements for admissions. “For though their second reformation, and the reed thereof, keeps out men civil and profane, whom John here represents, may judge visibly so to be; yet many a hypocrite, that maketh a lie, may scape and crowd into this inward temple still, whilst the judgment of men, who often err, applies the reed. But into the other temple to come, under the new Jerusalem, shall none of these enter.” 275 In the meantime, a church that denied entrance to the unregenerate to the best of its knowledge would 273. Ibid., 129. 274. Ibid., 130–31. 275. Ibid., 128. 148 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 be the most adequate means of protecting the saints from the degeneracy which was an inevitable concomitant of the world’s old age. “To get into this temple is the greatest preservative to keep the saints from the overgrowing corruptions and defilements of these Gentiles [i.e., carnal Protestants]; and it may unto many prove a protection and sanctuary from their power, as to those churches in New England it may be hoped it shall. ‘God will create a defense upon his glory.’ And, however, they shall hereby be reserved for that resurrection which afterward is to come.” 276 Goodwin did not doubt that this second reformation would take place in the midst of degeneracy and corruption. In fact, it seemed likely that its raison d’etre was to line up those who could be trusted in the coming {116} fight against the forces of Satan, and in Goodwin’s judgment—being “not swayed unto it through affection only”—the purest professors were to be found in his own land. England, therefore, must hasten to prepare for its leading role in the coming struggle by erecting the kind of churches the New Englanders already had founded. Only in this manner could the challenge of these perilous times be met. On this note, Goodwin ended his exposition of the Apocalypse: But, however, let an indefinite warning that these things are approach- ing, and we within reach of them, suffice for to move us to prepare for them, which is the only use of knowing them.... [For] we are to con- sider that we live now in the extremity of times, when motions and alterations, being so near the centre, become quickest and speediest; and we are at the verge, and, as it were, within the whirl of that great mystery of Christ’s kingdom, which will, as a gulf, swallow up all time; and so, the nearer we are unto it, the greater and more sudden changes will Christ make, now hastening to make a full end of all. 277 John Cotton If Goodwin believed that England should prepare for a leading role in the tumultuous days ahead, John Cotton was willing to give his native land more than a little credit for reformation already accom- plished. In one of the three published parts of his sermons on the 276. Ibid., 130. 277. Ibid., 204. Purity and Progress: New England’s First Generation 149 A Chalcedon Publication [] 3/30/07 Apocalypse, The Powring Out of the Seven Vials, he assigned England a major role in bringing about the reforms which any day now would complete the destruction of Antichrist. These reforms he thought were the antitypes of the seven vials described in Revelation—just as had Goodwin. Unlike Goodwin though, he did not think that the vials could be correlated with the appearance of the Waldensians five centu- ries ago. 278 Instead Cotton believed the first vial had been poured out as recently as the reigns of Henry, Edward, and Mary, when English martyrs had announced the theme of reformation. These men and women had been “such as did convince [men] of the Damnable estate of a Catholike, and taught them, that by their Religion they could go not beyond a Reprobate; ... that all their Religion was but the worship of God after the devises of men, even Will-worship, such as they were led into by the Man of Sinne.” 279 Their work was reinforced soon after by “Chemnitius, and Junius, Chamier, Whitaker, and Reignolds, Perkins and Ames, and the rest of the holy saints of God, that have poured out this [second] {117} viall of Gods wrath, that is, by their doctrine and writings from the word have poured out such clear conviction, and ref- utation of [Catholic] doctrine and worship.” 280 Thus, just as corruption had crept into the church by degrees, the vials of God’s wrath were pro- gressively discovering the “pollution in Religion.” 278. Cotton did, however, believe that reformation had begun with the Waldensians and had continued and spread throughout Europe until it had openly broken forth with Luther. He merely did not think these events could be correlated with the seven vials. See his An Exposition upon the Thirteenth Chapter of Revelation. 279. John Cotton, The Powring Out of the Seven Vials (London, 1642), “The First Viall,” 4–5. 280. Ibid., “The Second Viall,” 20. The men referred to by Cotton are Martin Chemnitz (1522–1586), German theologian known for his work against the Council of Trent; Franciscus Junius (1545–1602), French Reformed theologian who wrote against Bellarmine; Daniel Chamier (1565–1621), French Reformed preacher who presided over the synod which added an article to the Reformed confession of faith declaring the pope to be Antichrist; William Whitaker (1548–1595), English theologian who wrote against Bellarmine; John Reynolds (1549–1607), Puritan divine, author of several works against Catholics; William Perkins (1558–1602), English theologian greatly revered by New England Puritans; and William Ames (1576–1633), another English theologian who profoundly influenced New England Puritanism. 150 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Queen Elizabeth—with the aid of Parliament—had been responsible for the third vial. This one, which turned rivers and fountains to blood, had been “effectually accomplished” when a law was passed in 1581 requiring that any Jesuits or Catholic priest found within the realm be judged guilty of high treason. In this manner, the “rivers and fountains” of Catholic propaganda had—quite literally—been turned into blood. 281 The angel who declared the righteousness of the Lord in visit- ing this plague upon Catholicism Cotton thought was none other than William Cecil. His book, Justitia Britanniae, had made it clear that what had been decreed in Parliament was just according to the law of God and the true principles of “the Christian State Policie.” The Netherlands had followed England’s example in 1586, and together these laws had “raised all Christendome in combustion, the wars of eighty eight, the Spanish invasion had speciall respect to this, and had not the Lord borne witnesse to his people and their Law, in defeating the intend- ments of their enemies, against both the Nations, it might have been the ruine of them both.” 282 Cotton gave his listeners a choice when it came to the fourth vial. It could be taken either as the defeat of Austria by Sweden, or the break- ing of the pope’s civil supremacy by Queen Elizabeth when she defied his bull of excommunication. Since then, as everyone knew, his power had greatly decreased—even in Catholic nations. The fifth vial, which was supposed to be poured out upon the seat of the beast, Cotton did not interpret as a visitation threatened against Rome. Rather, since the seat of the beast really existed in the papal and episcopal forms of church government, this prediction would be fulfilled in an attack upon these corruptions. Indeed, the first drops of this vial had already been sprinkled by Beza, Cartwright, {118} Baynes, and Parker, and even now the rest of it was descending full force in Scotland. You now see whole Vialls full of wrath powred out by the whole Church of Scotland, who have engaged themselves, and their state for ever in this quarrell, and have beene carried along herein, not in a way 281. See the account of the executions of three Catholic priests which took place in Cotton’s hometown when he was a young boy, in Larzer Ziff, The Career of John Cotton: Puritanism and the American Experience (Princeton, NJ, 1962), 3–4. 282. Cotton, The Powring Out of the Seven Vials, “The Third Viall,” 7. Purity and Progress: New England’s First Generation 151 A Chalcedon Publication [] 3/30/07 of popular tumult, but with such wisedome, courage, judgement and Piety, that you may see and say that it is not a Viall poured out by an unadvised multitude, but by an Angell of God, by the Heavenly Minis- ters of his wrath. 283 From Scotland the wrath of God against these degenerate church governments was pouring into England. Men questioned the episcopacy—let alone the papacy—as they never had before, and Cotton believed this growing doubt would spread from Great Britain through the Catholic countries to the very gates of Rome itself. The fifth vial would be followed very shortly by the sixth, which was to dry up the river Euphrates. Cotton conceived this river to be the idolatry and revenues which nourished both the pope and the Turk. The ten Christian kings of Europe, converted under the fifth vial (Cot- ton did not identify them), would “dry up all these [papal] revenewes.” This would deprive the Turks by encouraging the conversion of the Jews, who would invade the East and thus cut off the maintenance of the Turkish rulers. But the sixth vial was not to affect Europe alone. Its appearance—which in some degree had already begun—had implica- tions for New England as well, since the drying up of idolatry referred not only to graven images but to the idols Mammon erected in the hearts of all men. And so will God deale with our Cattell if they be our Gods, they shall either be worth little, or else he will deny us fodder for them; if they devoure our spirits, and take off our minds from the Ordinances of God; he will rend away anything that standeth between him and our soules; Therefore as ever we desire that we may prosper, and that their [sic] may be a ready way prepared for our comfort, let no streams of Idolatry, be found among us, ... Only let us take part with this Angell in powring out Vialls upon the corruptions that are found in our own hearts; look that their be no corruptions in us, but such as are stil dry- ing and drying up, and see if God be not faithfull and gratious to us aboundantly; stir we up our selves therefore, and one another here- unto, then shall we see Gods ancient people [the Jews] brought home and the Lord shall be one over al the Earth, and his name one, which wil prove a Resurrection unto all the Churches of the Saints. 284 283. Ibid., “The Fifth Vial,” 4. 284. Ibid., “The Sixth Viall,” 26. 152 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 In other words, if New Englanders would turn from the pursuit of earthly goods to the cultivation of greater righteousness, they would be rewarded with the blessed spectacle of the conversion of the Jews and the reign of Christ through the world—nothing less than the beginning of {119} the millennium. For Cotton, like Goodwin, thought that Christ, “by his Spirit and in his Servants,” would reign a thousand years on earth and that His reign would begin just as soon as the power of the Word, breaking forth throughout the world in the seventh vial, had finally defeated Antichrist. Whether or not New England dried up its own streams of idolatry, Cotton thought all of this would probably hap- pen very soon. “I know not what you that are young may live unto, for the neerer these things come unto their accomplishment, the swifter their motion will be, as it is with all naturall motions.” 285 The question for New England, therefore, was whether it would be rewarded or pun- ished by the millennium. Cotton put these alternatives to his colonial listeners in blunt terms in his sermons on the verses in Revelation which speak of the first resurrection. 286 The first resurrection—which would be spiritual, not bodily—would take place about the time of Antichrist’s fall and would consist of two parts—the first being the resurrection of particular per- sons “restored and renewed by regenerating Grace” and the second being a resurrection of the churches “when as they are recovered againe from their Apostatical and dead estate in Idolatry and Supersti- tion.” 287 Naturally the two parts were interdependent: The particular members of the church rise by regeneration and the work of God’s grace in their hearts working in them by his spirit all grace to salvation: Faith, Hope, Patience, Humility, etc. Now they ris- ing againe, not into a loose frame, but a state rising into a Church body, and the Church body so reformed as may beare witnesse against all Antichristianisme in doctrine, Worship and government; This is the first resurrection. 288 285. Ibid., “The Fourth Part upon the Sixth Viall,” 11. 286. Rev. 20:5–6. 287. John Cotton, The Churches Resurrection (London, 1642), 8. 288. Ibid., 9. Purity and Progress: New England’s First Generation 153 A Chalcedon Publication [] 3/30/07 Cotton was careful to emphasize that the particular members making up these reformed churches would be “sincere members,” for otherwise “it could not bee said those men are blessed and holy that have part in the first resurrection, if they had part only in outward reformation.” 289 Such reformed churches therefore would truly constitute a “sincere and spirituall community.” The first part of this resurrection-reformation—the conversion of particular members—had clearly already begun, but the second part would be fully accomplished only upon the ruination of Antichrist. “I cannot speake according to my Text, and say there is a first resurrec- tion of Churches yet. Though there be a resurrection of Christians, and a yawning towards further reformation in these Churches.” 290 When Antichrist did fail, though, {120} there would be “a fresh supply of notable reformation, and notable judgements upon wicked men.” 291 Nations all over the world would then be blessed with the opportunity to reform. The “beauty of the Ordinances,” the allure of “so many Sin- cere hearted Christians in the Church,” would bring multitudes into the fold. For those who did not succumb to the attractions of godliness at that time, however, there would be a terrible punishment. They and their posterity would be given no opportunity to partake of reforma- tion during all the years when Christ’s servants would rule the earth. “Such Nations and people as are not renewed and restored in the first resurrection, upon the destruction of Antichrist and the ruine of Rome, they shall not recover the like liberty, either of Reformation of themselves, or of persecution of the Churches, for a thousand Yeeres after.” 292 The moral for New England was obvious: The use of this point is First a serious and strong warning unto all the people of God that shall live when Antichrist shall be abolished, and Rome ruinated. Take heed how you slip such opportunities of turning unto God. If men grow not more sincere and pure in seeking after God (whether they be publick States or private persons:) If men be not brought on, but will stand out such glorious reformation then, and such powerfull providences then; If men stand out then, and not bee 289. Ibid., 10. 290. Ibid., 19. 291. Ibid., 12. 292. Ibid., 11–12. 154 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 awakened, it is to bee feared they will not be awakened, (nor men of their Spirits) for a thousand yeares together. 293 God might yet bear with New England for a while, but if the colonists did not now “strike a fast Covenant with our God to be his people,” then they would be cast into outer darkness when Christ’s kingdom was established on earth. Surely this was the time to remember that “we are not like to see greater incouragements for a good while than now we see.” 294 But, however much Cotton was prepared to question the “sincerity” of New England’s reformation, he was still convinced that it was mov- ing in the right direction. His description of the millennium, which he thought might begin as soon as 1655, sounds very like the holy com- monwealth already established in Massachusetts. These thousand yeares therefore doe most properly begin from the throwing down of Antichrist and destruction of Rome; The Lord will then send such powerfull Ministers into the Church, that by the power of the keyes they shall take hold on Satan that is to say, convince him and his instruments of all Popish, and Paganish Religion and binde him by the Chaine, that is to say, the strong chaine of Gods ordi- nances, Word and Sacraments, and Censures. They shall not take hold of Satan in his own Person, for I doe believe Satan will ever be at lib- erty to tempt the Sonnes of men; and he is never so cast into the bot- tomless pit, but he hath a power to vexe the Sonnes of men to the end of the {121} world. But he speakes of Satan in his instruments, that not one of them shall appeare, but the Lord in his word shall take hold on them and abandon them; and if they be Church members will bind them in chaines of the Ordinances of God, as Admonition, and Excommunication and hold them so close to it, that such wickednesse shall not abide uncontrouled on the face of the Earth chiefly by Church Censures, and partly also by punishment from Civil Magis- trates as need shall be. 295 Moreover, men would then “clearely know that the true Church is not a Catholike visible, nor a Cathedrall, nor a Diocesan, nor a Provinciall Church.” 296 They would realize, in other words, that true churches 293. Ibid., 14–15. 294. Ibid., 16. 295. Ibid., 5–6. 296. Cotton, The Powring Out of the Seven Vials, “The Seventh Vial,” 11. Purity and Progress: New England’s First Generation 155 A Chalcedon Publication [] 3/30/07 were particular congregations made up of visible saints, exercising discipline according to God’s ordinances, and they would establish such churches throughout the world. When this was accomplished, the millennium would have arrived. Then it could truly be said, “It is done; Even all that God hath to do in the world, for any further Reformation expect it not.” 297 By now the similarities between Goodwin’s and Cotton’s interpreta- tions of the Apocalypse should be evident. Both believed that the fall of Antichrist would probably take place within the lifetime of people then living, that this fall would be accompanied by a reformation of churches similar to that practiced in New England, that this reforma- tion would initiate the millennium, and that even now the way for all this was being prepared by the restoration of excommunication or “excommunicating gifts,” which served to separate the visibly regener- ate from the visibly profane. Neither man could be called a premillen- nialist since they expected this great reformation to develop out of a historical process that had already been in progress for several centu- ries. Nor were they prepared to claim absolute accuracy in the discern- ment of hypocrites short of Judgment Day. Satan—who was, of course, not identical with Antichrist—would merely be bound by the ordi- nances of God during the millennium, not destroyed. What Goodwin and Cotton envisaged was a great period within history during which it would be given to the saints to restrain evil through the righteous exer- cise of civil and ecclesiastical authority. It would, in other words, be a thousand-year extension of the New England Way. Yet this did not imply that the saints could bring the millennium on unaided. Even the beginnings that were being made in New England depended upon a divine covenant, and still there was a danger that that experiment might fail through the carelessness of the experimenters. But, as we have said, Goodwin and Cotton did not expect to establish the millen- nium through the action of the saints. Rather, the rule of the saints would become inevitable because a growing knowledge of the Lord would transform the hearts of men. As Cotton put it: {122} And when once the light of the Gospell is dispersed, it will bring in all Nations, it will thunder upon them, and never leave untill it have 297. Ibid. 156 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 changed them. If this knowledge of God come amongst an army of men, they will not touch any thing that is their brethrens, not meddle, not make with any to doe them harme, no mans purse shall be taken from him, no mans goods taken without due recompence, only they will not be deluded with shaddowes, nor suffer mountaines to overtop them, neither will they be encompassed with hands: they will raise such an earthquake first, in Church, and Commonwealth, as you will at length wonder at, for though it begin in a corner of the world, it will not cease till it have shaken all Christendome, for when men once begin clearely to see which is the true Church of God, that it is not Cathedrall, nor Provinciall, nor Diocesan, but congregationall only, the officers whereof are godly Pastors, and Teachers, and ruling Elders and Deacons. And when they see that the Saints which they have embraced, and esteemed, are not the true Saints of God, nor these the Churches, nor those the officers of Christ wherewith they have been gulled: but they see now who are the Saints of the most high; and can put a difference now between precious and vile. In this way men will goe on to raise such an earthquake (and that not besides the Law nei- ther) that if any City rise up against them, fall it must and stoop unto them, and at length Rome it self shall fall, and all the Cities of the Nations that cleave unto her, and every mountaine shall bee rooted up, and all their consecrated places shall lie levell with the common soile, this will the Lord bring to passe, and will not leave till he hath wrought his great work in the world. 298 John Davenport There were other ministers in New England besides John Cotton who thought along apocalyptic lines. Perhaps the one whose views were closest to those of Cotton was John Davenport, the first minister of New Haven. Davenport, like his close friend, Thomas Goodwin, was converted to the cause of congregationalism by Cotton in 1633, just before the latter sailed for New England. Incurring the displeasure of the bishops shortly thereafter, Davenport himself fled to Holland, where he became involved in an acrimonious controversy over baptism and soon returned to England. Cotton, meanwhile, had been encour- aging him to come to America by sending him reports—if we can take Cotton Mather’s word for it— “that the order of the churches and the commonwealth was now so settled in New-England, by common con- 298. Ibid., 15–16. Purity and Progress: New England’s First Generation 157 A Chalcedon Publication [] 3/30/07 sent, that it brought into his mind the new heaven and the new earth, wherein dwells righteousness.” 299 (Possibly to the embarrassment of his mentor, Davenport arrived in Massachusetts just in time to help settle the Antinomian Controversy.) By 1638 he was safely established in New Haven. There he set out to create a church of even {123} greater righteousness than those of Massachusetts. If the Bay Colony brought to mind the new heaven and earth, New Haven was intended to exem- plify the quintessence of purity. As Cotton Mather later put it, Daven- port’s objective was to do “all that was possible to render the renowned church of New-Haven like the New-Jerusalem.” 300 Davenport’s desire to model the church of New Haven upon the New Jerusalem is especially interesting in the light of his views upon the millennium; for, like Goodwin and Cotton, he too believed there would be an extended period on earth in which the church would enjoy as much “perfection of light, and holiness, and love, as is attain- able on this side of heaven.” 301 Unlike them, however, Davenport was a chiliast who believed Christ would reign on earth personally during the millennium, although he did not believe the saints would enjoy carnal pleasures at this time. These views, as he well knew, were dan- gerously close to those held by such millennial enthusiasts as the Fifth- Monarchy men. Yet, writing in 1667—seven years after the rule of saints in England had utterly collapsed—Davenport refused to renounce his chiliasm. “Concerning this his second coming, to set up his Kingdom on earth, some acknowledge no kingdom of Christ on earth, but spiritual and invisible in the hearts of the elect. The kingdom of Christ hath indeed been setup by his effectual operation of the spirit in the Ministry of the Gospel, from the first publishing of the Gospel .... But there is another, a Political Kingdom of Christ to be set up in the last times.” 302 The Fifth-Monarchy men had erred in two ways: “First, By 299. John Cotton, quoted in Cotton Mather, Magnalia Christi Americana, vol. 1 (Hartford, CT, 1855), 325. 300. Ibid., 328. 301. John Davenport, “An Epistle to the Reader,” in Increase Mather, The Mystery of Israel’s Salvation Explained and Applyed (London, 1669). Unfortunately, this preface is the only extant writing of Davenport on the millennium. Cotton Mather, however, states that he “both preached and wrote” on the subject. Magnalia Christi Americani, vol. 1, 331. 158 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 anticipating the time, which will not be till the pouring out of the sixth and seventh Vials. Secondly, By putting themselves upon a work which shall not be done by men, but by Christ himself.” 303 In spite of his stric- tures against the Fifth Monarchists for “anticipating the time,” Daven- port apparently believed the second coming was near, for he noted “constant reports from sundry places and hands” that the Israelites were converging upon Jerusalem from all over the world, “carryed on with great signs and wonders by a high and mighty hand of extraordi- nary providence.” This seemed to him to indicate that the Jews were being assembled by God preparatory to their long-prophesied conver- sion. Since Davenport thought they were not to be converted before “Romes ruine” and Christ’s appearance to judge Antichrist, it seems likely that he thought the millennium was near. Moreover, Davenport supported his views by citing Goodwin, {124} Alsted, and Mede— “(who was no phanatick, as the Prelates themselves will grant)” —all of whom thought the millennium might begin in the seventeenth century. Although there is no direct evidence for it, Davenport’s apocalyptic views probably dated at least from his early days in New Haven. Mede and Alsted were both published before he left for America, and he apparently maintained a correspondence with Thomas Goodwin. Nor in New England could he have failed to keep in contact with his old friend John Cotton. Certainly Davenport’s conception of the millen- nium was close to that of his two colleagues, apart from his insistence upon Christ’s personal rule. He too was fascinated by the vision of a coming earthly perfection of the church, and it may well be that his strictness in the admission of church members was directly linked to this vision. William Hooke Davenport’s associate at New Haven, William Hooke, was apparently also a chiliast. Hooke, who came to Massachusetts in 1636, was a minister at Taunton until he moved to New Haven in 1644. He remained there twelve years, returning to England in 1656 to become Oliver Cromwell’s chaplain. In 1662 he was ejected from his living, and 302. Ibid. 303. Ibid. Purity and Progress: New England’s First Generation 159 A Chalcedon Publication [] 3/30/07 from then until his death in 1678, he led the rather precarious existence of a nonconforming minister. All of Hooke’s apocalyptic writings date from after the fall of the Protectorate. Thus, although he was sure that “the world is now drawing towards its end,” 304 he was understandably primarily concerned with reconciling his readers to a difficult time in the immediate future. His emphasis was on hope and faith in the face of adversity. Occasionally, however, he did suggest that in more propi- tious times he might have been an outspoken defender of millennial- ism. For instance, in a passage reminiscent of John Cotton, he spoke of “a great effusion of the Spirit of God” to be expected in the last times: Hence it followeth, That there will be a very great light of Knowledge in this Day, so that there shall not be so much need, as now there is, for one to teach another; saying, Know the Lord, for they shall all know him from the least to the greatest.... This Light of Knowledg shall have a great influence into the Hearts and Lives of Men, who shall shine eminently in Holiness; ... Even Carters, Cooks, and Kitchen-Maids shall then shine in purity of life, and there shall be no more the Canaanite in the House of the Lord of Hosts 305 In 1664 he wrote to Davenport that “I lissen much after ye mocions of ye {125} Turke, wreof ye Intelligencer, every weeke, writes something. For his slaying of ye 3d pt of men (viz: Antichrians) Rev. 9.18, 19, 20, 21 and ye slaying of ye witnesses by ye Beast yt ascendeth out of ye bottomles pit Rev. 11.7 (I say) these are ye two grte things mentioned to be done under ye 6th Trumpet, wch some are of opinion is drawing on to its last blast.” 306 It seems very likely that Hooke shared Davenport’s views on the millennium and church membership. Thomas Parker Davenport, Cotton, and presumably Hooke combined strict views on church membership with anticipation of the imminent arrival of the millennium. At the other extreme was someone like Thomas Parker, 304. William Hooke, A Discourse Concerning the Witnesses, Relating to the Time, Place, and Manner of their Being Slain (London, 1681), 33. 305. William Hooke, A Short Discourse of the Nature and Extent of the Gospel-Day (London, 1673), 145–46. 306. Letter to John Davenport, 1664 (from MS copy made by G. Lyon Turner in Beinecke Library, Yale University). 160 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 son of the well-known Robert Parker who had been an early advocate of Puritan reforms in England. Unlike his father, who had leaned toward congregationalism, Thomas inclined toward a presbyterian form of church government. At the church in Newbury, Massachusetts, over which he and his cousin James Noyes presided, members were admitted according to a rule, “so large, that the weakest Christians may bee received.” 307 Parker’s views on the millennium were as flexible as the ones he held on church membership. In a book on the prophecies of Daniel, he set forth two possible systems of apocalyptic chronol- ogy—one putting the end of Antichrist and the beginning of New Jerusalem at 1650 and the other at 1860. And when it did come, Parker did not expect New Jerusalem to exist on earth for more than forty-five years. “As concerning the opinion of many Worthyes, affirming, that the reign of the Saints a 1000 yeers, is to be expected in the glory of New Jerusalem at the end of the yeers of Antichrist. I cannot possibly bring my judgement to incline unto it.” 308 According to Parker, the expressions of “temporall felicity” which described New Jerusalem in the Bible were “either to be understood of its state of inchoation, ... especially from after the end of the years of Antichrist through the space of 45 years... or being applied to its state of heavenly perfection immediately ensuing, they are to be understood in a mysticall sense.” 309 Parker thus gave an Augustinian interpretation to the thou- sand-year period of Satan’s binding. As he saw it, it had begun either in 620 or in 840 and accordingly would end roughly a millennium later in the day of Judgement. Parker’s main concern, however, was with Daniel’s seventy weeks and not the millennium. As was usual, he interpreted the seventy weeks as a period of 490 years during which the true church would be gathered out of {126} the “Spiritual Babylon of Antichrist.” This work could date from either 1160 (the Waldensians) or 1370 (Wyclif). In either case, this was the time when the church would be “restored and edified by the Ordinances of Christ and Word of truth.” At its end (either in 1650 or 1860), there would be established “the Kingdom of 307. Thomas Parker, The True Copy of a Letter (London, 1644), 4. 308. The Visions and Prophecies of Daniel Expounded (London, 1646), 147. 309. Ibid., 148. Purity and Progress: New England’s First Generation 161 A Chalcedon Publication [] 3/30/07 Saints, wherein they shall dwell in safety, their enemies rooted out in the space of 45 years, Verse 12: and the elect remnant of them con- verted, ... then many shall rise to life, and many to shame. Thus the generall resurrection is compounded with the last plagues on Anti- christ.” 310 Quite clearly Parker did not go along with Cotton and Dav- enport when it came to the millennial rule of the saints. Whether this was related to his more lenient views on church membership, it is impossible to say. He did suggest that during the forty-five-year period preceding the last judgment, “the Ministers as Angels, letting in the elect by conversion through the gates of particular Churches, into the community of the whole Church of New Jerusalem shall hereby be instruments of bringing them into the heavenly perfection, and shall therein be glorified with their converts.” 311 Thomas Shepard Somewhere in between Davenport and Parker stood Thomas Shep- ard, the minister at Cambridge. Shepard, who was quite strict in the admission of church members, was much less certain in his views on apocalyptic matters than either Davenport or Parker. Indeed, at one point, after speculating about whether one of Brightman’s interpreta- tions could be applied to the conversion of the Indians, he wrote, “but I have no skill in prophesies, nor do I beleeve every mans interpretation of such Scriptures.” 312 It is not too surprising, therefore, to discover that Shepard rejected the idea of a millennial reign of the saints on earth, although he was still prepared to relate the New England Way to the coming of Christ. This comes out most clearly in his treatment of the parable of the ten virgins in a series of sermons preached between 1636 and 1640. A preacher who was known for his “melting” sermons on both sides of the Atlantic, Shepard was concerned in this series with the difference between the sincere Christian and “the most refined Hypocrite.” To distinguish between saving and common grace was an endeavor particularly helpful to a people striving to build regenerate 310. Ibid., 124–25. 311. Ibid., 148–49. 312. Thomas Shepard, The Clear Sun-shine of the Gospel Breaking forth upon the Indians in New-England (London, 1648), 30. 162 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 churches, and Shepard’s work enjoyed a long popularity in New England. For our purposes, however, the context into which he put his elaborate distinction between true and false regenerations is more interesting than the distinctions themselves. {127} He made this context clear at the very beginning of his exposition. The parable, he said, dealt with the churches’ preparation to meet with Christ and with the coming of the Bridegroom Himself. Shepard thought there would be not one but two comings of Christ. The first, a figurative rather than literal appearance, would be “to call the Jews, and to gather in the fulness of the Gentiles with them, which is called the brightness of his coming, 2 Thes. 2:8. When there shall be such a bright- ness of the Truth shining forth in the world, armed with such instru- ments as shall utterly destroy Antichrist, long before his second coming.” 313 The second coming, of course, would be at the time of the Day of Judgment. The parable, therefore, could be taken as applying to either coming. Of the two, Shepard considered it more likely that it referred to the latter coming. But this did not mean that it contained no useful morals for New England, particularly since these were the days when Christ’s first coming in “a brightness of the truth” was obviously wreaking havoc on Antichrist. So that although this Parable looks most directly unto those times which are yet to come, yet as all examples registred in holy Scripture for time past, are applicable and useful for us, so these that are yet to come are alike instructive to us, especially in these times and places, wherein the Lord (according to his manner of working great things usually) gives among us some small, yet lively resemblance of those dayes. 314 Moreover, the churches’ preparation for Christ would be the same no matter whether it was the first or the second time. They would become “virgin-churches”—fit spouses for their holy Bridegroom. The state of the Members of some Churches about the time of Christ’s coming, shall be this, they shall not be openly prophane, corrupt and scandalous, but Virgin-Professors, awakened (for some season) out of carnal security, stirring, lively Christians, not preserving their Chas- 313. Thomas Shepard, The Parable of the Ten Virgins Opened and Applied (London,1695), pt. 1, 9. 314. Ibid., 9–10. Purity and Progress: New England’s First Generation 163 A Chalcedon Publication [] 3/30/07 tity and Purity meerely in a way of works, but waiting for Christ in a Covenant of Grace, only some of these, and a good part of these, shall be indeed wise, stored with spiritual wisdom, fill’d with the power of Grace; but others of them, and a great part of them too, shall be found foolish at the coming of the Lord Jesus. 315 Obviously the lesson for New Englanders in this parable was the danger of considering themselves to be regenerate when in fact they were naught but foolish hypocrites. To lessen this possibility with a detailed description of the true “symptoms” of regeneration was the object of Shepard’s sermons. {128} John Eliot Of all the ministers who came to New England during the first years of settlement, probably the most forthright exponent of apocalyptical ideas was John Eliot, the famous missionary to the Indians. Eliot was one of the first arrivals in Massachusetts, landing in Boston in 1631. He was soon established as the minister at Roxbury and remained there until his death in 1690 at the age of 86. Sometime during the first years of his ministry, Eliot became determined to evangelize the Indians. He hired an English-speaking Indian to teach him the language, and was finally ready to begin his missionary work in 1646. Eliot labored dili- gently for the rest of his life among the Indians, often under very dis- couraging conditions. His perseverance in such a difficult work is all the more impressive since he made no concessions to Indian barbarity in the matter of church polity. The requirements for admission to membership in their churches, which were established only after years of preparation, were as high as those of the majority of the English churches. For our purposes, the most interesting thing about Eliot’s missionary activity is its clearly apocalyptic inspiration. In the numerous letters Eliot wrote to England describing the work and asking for funds, he repeatedly connects missions to the Indians with the advent of the millennium. In one letter Eliot wrote of the missions as “a day of small things,” and begged for the prayers of the saints and churches. “There is,” he continued, “the more eminent need of Faith and Prayer, that the 315. Ibid., 3. 164 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Lord himself, by his speciall grace, favour, and providence, would appear in this matter: for the Lord must raigne in these latter dayes, and more eminently, & observably, overtop all Instruments and meanes.” 316 Just a year later, in 1650, he maintained that “all those signes preceding the glorious coming of Christ are accomplishing,” and announced his determination to see that the Indians “be wholly gov- erned by the Scriptures in all things both in Church and State,” since “unto that frame the Lord will bring all the world ere he hath done, but it will be more difficult in other Nations who have been adulterate with their Antichristian or humane wisdome.” 317 By 1653, Eliot was con- vinced that the Lord had “raised and improved” Oliver Cromwell to overthrow Antichrist and informed the Protector that the conversion of the Indians confirmed the arrival of the time for the spread of Christ’s kingdom over all the world: In these times the Prophesies of Antichrist his downfall are accom- plishing. And do we not see that the Spirit of the Lord, by the word {129} of Prophesie, hath raised up men, instruments in the Lords hand, to accomplish what is written herein.... In like manner the Lord having said, The Gospel shall spread over all the Earth, even to all the ends of the Earth: and from the riseing to the setting Sun: all Nations shall become the Nations, and Kingdoms of the Lord and of his Christ. Such words of Prophesie hath the Spirit used to stir up the servants of the Lord to make out after the accomplishment thereof: and hath stirred up a mighty Spirit of Prayer, and an expectation of Faith for the Conversion both of the Jewes, (yea all Israel) and of the Gentiles also, all over the world. 318 Eliot, then, undertook his missionary work to the Indians in the firm conviction that these were the “latter dayes,” when the millennial king- dom of Christ would appear and spread to the ends of the earth. More- over, he had very definite ideas about the nature of the coming reign of the Lord. Sometime around 1650 he wrote a treatise entitled The Chris- tian Commonwealth: or, the Civil Policy of the Rising Kingdom of Jesus 316. John Eliot and Thomas Mayhew Jr., The Glorious Progress of the Gospel Amongst the Indians in New England, ed. Edward Winslow (London, 1649), 18. 317. John Eliot and Thomas Mayhew Jr., The Light Appearing More and More Towards the Perfect Day, ed. Henry Whitefield (London, 1651), 23. 318. John Eliot and Thomas Mayhew Jr., Tears of Repentance (London, 1653), “To the Reader.” Purity and Progress: New England’s First Generation 165 A Chalcedon Publication [] 3/30/07 Christ, which he dedicated to “the Chosen, and Holy, and Faithful, who manage the Wars of the Lord, against Antichrist, in great Britain.” 319 According to Eliot, Christ’s rule on earth would not be a personal one, but would consist simply of the supremacy of the Bible. “The Govern- ment of the Lord Jesus, ... by the Word of his Mouth, written in the holy Scriptures, shall order all affairs among men; And great shall be his Dominion.... all men submitting to be ruled by the Word, in civil, as well as Church-affairs.” 320 The work of the saints, therefore, in these tumultous days was to act as the Lord’s instruments in bringing about Christ’s rule— “whether by Councils or Wars, or otherwise.” In prose- cuting “that great business of changing the Government in England,” they should not search human polities and platforms of government, but should turn to the Scripture for “a Divine institution of civil Gov- ernment.” 321 Indeed, the Spirit would bless “every institution of the Word, to make it powerful and effectual to attain its end better, and more effectually then any Humane Ordinance and Institution in the World can do.” 322 The polity which Eliot thought the Word of God had instituted for the government of the world was a very simple one. It was based on God’s commandment “that a people should enter into Covenant with the Lord to become his people, even in their Civil Society, as well as in their {130} Church-Society.” 323 No law, statute, or judgment should be accounted valid “farther then it appeareth to arise and flow from the Word of God.” 324 Thus every covenanted nation should model its gov- ernment upon the pattern of Israel set forth in the Scriptures, organiz- ing itself into “myriads” or basic groups consisting of ten households each. Such “myriads” would be governed by an elected ruler who 319. The treatise was not published until 1659, when, on the eve of the Restoration, it caused the government of Massachusetts Bay Colony profound embarrassment. Eliot eventually made a public retraction. 320. The Christian Commonwealth (London, 1659), “To the Chosen, and Holy and Faithful, etc.” 321. Ibid. 322. Ibid. 323. Ibid., 1. 324. Ibid., 3. 166 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 would join with others rulers of ten in an ascending hierarchy of coun- cils. Thus five rulers of ten would join in a council which would govern under an elected ruler of fifty. Twenty rulers of fifty would form a council under a ruler of a thousand, and so on up to a million. The actual government would be carried on in periodic courts in which judgment out of the Scriptures would be passed on any matter requir- ing attention. Anything which could not be satisfactorily dealt with by a ruler of ten would be referred to the higher councils. In this manner the world would be governed by the Word of God only, and would par- take of no human laws or polities. Unfortunately, Eliot did not publish his views on the kind of “Church-Societie” appropriate to the rising kingdom of Christ until 1665, when he wrote the Communion of Churches, a treatise proposing “the Way of bringing all Christian Parishes to be Particular Reforming Congregationall Churches.” In this work he was primarily concerned with setting forth a system of church councils which would provide a means of uniting the Congregationalists and the Presbyterians and which would also serve as “an eminent Preparatory to these glorious dayes (when Christ shall be King over all the Earth).” 325 Eliot’s system of church councils was very like the platform of civil government he had advocated earlier, except that it was based on the number twelve instead of ten. Apart from defining “a Church of Believers” as “a com- pany of visible saints combined together, with one heart, to hold Com- munion in all the instituted Gospel-worship, Ordinances and Discipline,” 326 Eliot made no statement about the admission of church members. In 1657, however, in a letter to Richard Baxter, he did recom- mend extending church privileges in England to the whole con- gregation, excluding only “the ignorant and prophane and scandalous.” At the same time, a smaller group of saints, “called higher by the grace of Christ,” might enjoy “a more strickt and select communion” without disrupting the rest of the parish. 327 It is difficult to say whether Eliot 325. Communion of Churches (Cambridge, MA, 1665), 16. 326. Ibid., 1. 327. Some Unpublished Correspondence of the Reverend Richard Baxter and the Reverend John Eliot, the Apostle of the American Indians: 1656–1882, ed. F. J. Powicke (Manchester, 1931), 25. Purity and Progress: New England’s First Generation 167 A Chalcedon Publication [] 3/30/07 was merely advocating this measure as a temporary expedient, appro- priate to the circumstances in which the English Puritans then found themselves, or {131} whether he felt this would be an integral part of “Church-Societie” during the millennium. He himself never instituted this practice in his own church in Roxbury or in the Indian churches, in spite of the fact that he did set up the civil government of the Praying Indians according to his “myriad” system. Furthermore, in The Chris- tian Commonwealth he argued that “a willing subjection of a mans self to Christ in this [civil] Covenant, is some hopeful sign of some degree of faith in Christ, and love to God; and as a good preparative for a more neer approach to Christ in Church-fellowship, and Covenant.” 328 Obvi- ously when he wrote this, Eliot was envisaging a restriction of church membership, though it may not have been as strict as that employed by Davenport. Edward Johnson Perhaps the man who best expressed the apocalyptic preoccupations of the first colonists was a layman, Edward Johnson. Johnson, a car- penter, wrote the first history of Massachusetts Bay Colony ever to be published. Entitled The Wonder-Working Providence of Sion’s Savior in New England, Johnson’s history indicates the degree to which the apoc- alyptic conception of New England’s destiny had taken hold of the imagination of the rank and file of the colonists. As its title suggests, the history was meant to depict the triumph of Christ over Satan in His American colony. The settlers themselves were represented as an army called up by their Savior “for freeing his people from their long servi- tude under usurping Prelacy.” 329 The army’s commission was a large one. As described by Johnson, it included instructions in the demeanor of church officers, the behavior of the people in the wilderness, the kind of civil government that was to be set up, and finally, “How the People of Christ ought to behave themselves in War-like Discipline.” 330 328. The Christian Commonwealth, 3. 329. Edward Johnson, The Wonder-Working Providence of Sion’s Saviour in New England, ed. William F. Poole (Andover, MA, 1867), 1. 330. Ibid., 9. 168 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 The war by means of which these soldiers of Christ in New England were to put down prelacy was, of course, part of the great battle with Antichrist. In a chapter entitled “Of the Time of the Fall of Antichrist, and the Increase of the Gentile Churches, Even to the Provoking of the Twelve Tribes to Submit to the Kingdom of Christ,” Johnson, while admitting the exact time of the fall was obscure, nevertheless main- tained that it was not far away. “But to come to the time of Antichrists fall; and all that expect it may depend upon the certainty of it: yea it may be boldly said that the time is come, and all may see the dawning of the day: you that long so much for it, come forth and fight: who can expect a victory without a battel?” 331 {132} For those scoffers and doubters who would not believe that the day had really come until they could see Christ’s soldiers at the gates of Rome itself, Johnson had an easy answer. Had not the Lord said, “Come out of her my people”? To the New England historian, this obviously meant that Christ would come when His saints had been assembled in good order outside the church of Antichrist. As it was necessary that there should be a Moses and Aaron, before the Lord would deliver his people and destroy Pharaoh lest they should be wildred indeed in the Wilderness; so now it was needfull, that the Churches of Christ should first obtain their purity, and the civill gov- ernment its power to defend them, before Antichrist come to his finall ruine: behold the Lord Christ marshalling of his invincible Army to the battell: some suppose this onely to be mysticall, and not literall at all: assuredly the spirituall fight is chiefly to be attended, and the other not neglected, having a neer dependancy one upon the other, espe- cially at this time. 332 Purity and Eschatology Johnson’s insistence that the raison d’etre of New England was a spe- cial part in God’s plan for bringing down Antichrist suggests that, within two decades of its founding, apocalyptic thinking had become, for a great many of the colonists, an essential part of the rationale for their new departure in Puritanism. As we have seen, the departure, which made New Englanders “sui generis even among Puritans,” 333 was 331. Ibid., 231 332. Ibid., 232. Purity and Progress: New England’s First Generation 169 A Chalcedon Publication [] 3/30/07 their conception of the congregational church—a church whose mem- bership was limited to the conspicuously regenerate and yet which functioned as the state church for an entire political body. In the New England mind, the establishment of this particular kind of holy com- monwealth had somehow become indissolubly associated with the realization of Christ’s kingdom in history. Indeed, the very creation of a New England Way was grounded on the assumption that not only was the kingdom capable of being realized within history, but that it was the inescapable obligation of the saints as God’s instruments to work actively towards its establishment. And even though New England’s ministers did not always agree on the best way to proceed toward this goal, they did agree that the extraordinary times in which they lived formed the prelude to a new age. As Richard Mather put it: The Amplitude, and large extent of the Kingdom of Jesus Christ upon Earth, when the Heathen shall be his Inheritance, and the uttermost parts of the Earth his possession: and when all Kings shall fall down unto him, and all Nations do him service, ... is a thing plainly and plentifully foretold and promised in the Holy Scriptures; ... And although as yet our Eyes have never seen it, so, nor our Fathers afore {133} us, .. . yet the time is coming, when things shall not thus continue but be greatly changed and altered, because the Lord hath spoken this Word, and it cannot be that his Word should not take effect. 334 Thus from the very beginning, the bent of the colonists in Massachusetts Bay—unlike their brethren at Plymouth—was not to withdraw temporal but spiritual. Somehow this world’s institutions had to be refashioned to conform to Christ’s spiritual kingdom. “The Latter Erecting of Christs Kingdom in whole Societies, ... was our Design, and 333. Perry Miller, The New England Mind: The Seventeenth Century (Cambridge, MA: Harvard University Press, 1954), 434. 334. “To the Christian Reader,” in Eliot and Mayhew, Tears of Repentance. 170 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 our Interest in this Country: tho’ with Respect to the Inward and Invisible Kingdom, as the Scope thereof.” 335 It is no wonder that most of their English contemporaries reacted to this intention with incredulity and charges of fanaticism, for the New England design was precisely to make visible that which they admitted was invisible. They set out to do nothing less than reveal the bound- aries of grace by making the church conform to the inward rule of Christ in the hearts of the elect. This ambition to erect Christ’s king- dom by making it synonymous with the visible church and the defini- tive element of a secular community was much closer to radical millennialism than most Puritans came in the seventeenth century, and in fact, as we have seen, ran counter to the Calvinist conception of the church and its role in the world. For Calvin himself, although the church stood in a peculiar relationship to the kingdom, the church was identified with the kingdom only in the sense that the church served as the matrix for the embryonic, spiritual kingdom of Christ. Only when this foetal kingdom had been delivered from time’s womb on the Last Day would its outlines be visible to the world. Then, in the separation of the saved and the damned, men would indeed perceive the predes- tined limits of grace. Until that time, it was the implicit rather than the explicit growth of Christ’s kingdom which both impelled and shaped the flux of history. In opposition to this conception of the kingdom, the New England Puritans contended “that the visible Church of God on earth, especially in the times of the Gospel, is the Kingdom of Heaven upon earth.” 336 The touchstone to the New England conception of the church lies in the qualifying phrase, “especially in the times of the Gospel.” Having agreed with Calvin {134} and their English brethren that the kingdom grew in history toward its eventual climactic triumph, the New England Puritans went on to maintain that by means of a last preach- ing of grace—the Reformation—the church would become more and more clearly identified with the kingdom as the hour of the latter’s con- summation approached. Moreover, if the Reformation did mark God’s last offer of salvation to a sinful world, it seemed logical to the New 335. Jonathan Mitchell, quoted in Miller, 433. 336. Shepard, Parable of the Ten Virgins, pt. 1, 4. Purity and Progress: New England’s First Generation 171 A Chalcedon Publication [] 3/30/07 England clergy that this offer would be an example of purity as close to perfection as possible this side of heaven. What the New Englanders were saying, in other words, was that a particular church, covenanted together in “primitive” purity, was the closest possible historical approximation of an absolute eschatological reality. As they themselves put it: We still beleeve though personall Christians may be eminent in their growth of Christianitie: yet Churches had still need to grow from apparent defects to puritie; and [sic] from Reformation to Reforma- tion, age after age, till the Lord have utterly abolished Antichrist with the breath of his mouth, and the brightnesse of his coming, to the full and clear revelation of all his holy Truth; especially touching the ordering of his house and publiek worship. 337 Thus the congregational churches of New England must be interpreted as looking forward to Judgment Day as well as backward to the apostolic churches and beyond them to God’s covenant with the Israelites. The churches of New England were not merely an extension of God’s transaction with Abraham, but a representation of things to come. To conceive of the visible church as the kingdom of heaven meant that each individual church covenant was an anticipation of Judgment Day—a miniature, albeit incomplete, sorting out of the saved and the damned. Its plausibility ultimately depended upon the assumption that in His last offer of grace the Lord would so pour out His Spirit upon the land that regenerate men would be able to discern the workings of divine grace in the hearts of their friends and neighbors. That regenerate men could be fallible, New Englanders would have been the first to admit. There would be no time before the end when the church upon earth would be so pure that not a hypocrite would be in it. Yet this inability to attain perfection was no warrant for including within the kingdom men patently unregenerate. As John Cotton put it, arguing against the contention that it was unreasonable to expect a vis- ible church to remain undefiled, “It is not every sinne, that defileth a Church, but sin openly knowne, and allowed, at least tollerated and not 337. John Davenport, An Answer to the Elders of the Several Churches in New-England unto Nine Positions Sent Over to Them (London, 1643), “An Epistle Written by the Elders of the Churches in New-England.” 172 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 proceeded against by due admonition, and censure according to the rule of the Gospell.... {135} Let no man decline the evidence of this truth, by the wonted evasion of the invisible Church.” 338 The coven- anted saints—those who could manifest their faith in the outcome of history by binding themselves to the fulfillment of divine purpose— could exclude large numbers of their compatriots from church mem- bership in the certainty that the Spirit of the Lord would guarantee a working percentage of truly regenerate members because these were the “daies of the coming of the Son of man, wherein the Churches (especially in these places) grow to be Virgin-Professors.” 339 The New England Puritans—with the possible exception of John Eliot—were by no means desirous of radically reconstructing the soci- ety which had produced them; but in terms of their eschatological con- ception of church history, they were outright revolutionaries insofar as they thought of themselves as the instruments providence had chosen to “advance” history by making a decisive and irrevocable break with Antichristian corruptions. To say exactly when the majority of the New England Puritans arrived at this conclusion would be difficult. But in the second generation’s nostalgia for the heroic purity of their fathers, the connection between a congregational church and the imminent coming of Christ became an inextricable part of the fabled errand into the wilderness. Indeed, the validity of the vision of New England as a new chosen nation in their minds came to depend upon its position as the penultimate development in the story of man’s salvation from Adam’s fall to the Day of Judgment. 338. John Cotton, Of the Holinesse of Church-Members (London, 1650), 95. 339. Shepard, Parable of the Ten Virgins, pt. 1, 10. A Chalcedon Publication [] 3/30/07 FROM MEDIEVAL ECONOMICS TO INDECISIVE PIETISM: SECOND-GENERATION PREACHING IN NEW ENGLAND, 1661–1690 Gary North A successful program of Christian reconstruction must have two essential features if it is to keep from being swamped by secularism or overturned by traditionalism or a counter-reconstruction movement. First, it must have a positive eschatology. Men must have confidence in the long-term earthly effects of their present sacrifices for God’s king- dom. Second, they must have a concept of law which is uniquely Chris- tian. Without this, their specific recommendations for social change and personal discipline cannot be identified as explicitly Christian. Their projects will eventually drift with the prevailing intellectual cur- rents of the day. Some version of natural law or common ground phi- losophy will replace the original biblical frame of reference. The uniquely Christian character of the movement will be dissipated. An optimistic outlook concerning one’s labors is basic to the dynamic impulse of historical change, and a uniquely biblical law framework provides the tool for personal success and social transformation. The New England Puritan leaders of the first generation, at least those outside of the Pilgrim colony at Plymouth, were generally com- mitted to a postmillennial eschatology. They believed that New England would become a “city on a hill,” a light to the Gentiles, and the firstfruits of the expanding kingdom of God on earth. They were opti- mists, and they began the conquest of the North American wilderness. They also believed that they were in possession of a uniquely Chris- tian law structure. They did not have to answer to the king or Parlia- ment. They could rely on Old Testament laws to build their holy commonwealth. However, they also brought with them the Protestant version of medieval social theory, especially in the realm of economics. It was this inherited medievalism which was to be tested by the frontier 174 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 conditions of New England. Could a permanent standard of a “just price” or “fair dealing” be discovered? If so, could it be written into pre- dictable statute law? If not, what kinds of circumstances would bring such unjust dealing out into the open, so that everyone, especially the magistrates, would recognize it for what it was? If none could be agreed upon, what then? {137} The second generation in New England was forced steadily to aban- don the medieval economic framework, especially after King Philip’s War, the great Indian uprising of 1675–76. After 1680, Puritan clerics no longer could influence the legislators to impose ad hoc interven- tions of the old medieval outlook. The clerics no longer had confidence that they could provide specific recommendations for concrete eco- nomic reforms in the name of Christ. They could preach only general sermons against general deviance. The idea of concrete guidelines for economics based on biblical law was abandoned when the medieval economic casuistry was abandoned. Simultaneously, the old optimism of the first generation began to dim. There were some postmillennial optimists left, like the Rev. Jonathan Mitchel and the layman, Samuel Sewell, the famous diarist, but increasingly amillennialism and premillennialism (in the case of Increase and Cotton Mather) began to dominate the vision of the sec- ond generation. Thus, the two features most essential to the successful directing of social change—optimism and a unique law code—disap- peared as dominant factors in Puritan theology after 1660. Odd as it may seem, a poet marked this historically crucial transition. Michael Wigglesworth, within the space of a few months, produced two of the most famous poems in the history of New England. Indeed, they are used today as key documents of Puritan thought: God’s Con- troversy With New England and The Day of Doom. The year was 1662. The poems established a new pattern of expression which was to be fol- lowed closely by the writers of sermons throughout the period gener- ally classified as the second generation. God’s Controversy began by cataloguing the blessings God had granted to the first generation of New England: international peace, domestic safety, the covenant, wise rulers, spiritual gifts, and light. 340 “Yea many thought the light would last, And be perpetual.” This was their inheritance. “Such, O New- England, was thy first, Such was thy best estate.” But the changes are From Medieval Economics to Indecisive Pietism: 175 A Chalcedon Publication [] 3/30/07 now becoming apparent: tempests, carnality, deadheartedness, excess of all kinds. Are these the same people who once prized religious lib- erty, who fled England into a wilderness, who were protected by the hand of God? 341 Wigglesworth was careful to enumerate the multitudi- nous economic sins of the people as part of the general indictment: {138} Whence cometh it, that Pride and Luxury Debate, Deceit, Contention and Strife, False-dealing, Covetousness, Hypocrisy (With such like Crimes) amongst us are so rife, That one of them doth over-reach another? And that an honest man can hardly trust his Brother. 342 The ancient guidelines against excess had been breached, thus opening the land to the possibilities of God’s retribution. Drought, then exceeding wetness, and finally barrenness have already appeared. This, O New-England, hast thou got By riot, and excess: This hast thon brought upon thyself By pride and wantonness. Thus must thy worldliness be whipt. They, that too much do crave, Provoke the Lord to take away Such blessings as they have. 343 Beware, O sinful land, beware; And do not think it strange That sorer judgments are at hand, Unless thou quickly change. 344 340. Wigglesworth, “God’s Controversy [cited hereinafter as “GC”], lines 77–132, in Harrison T. Meserole, ed., Seventeenth-Century American Poetry (1968), 45–46. 341. “GC,” lines 133–214, ibid., 46–48. 342. “GC,” lines 215–20, ibid., 48. 343. “GC,” lines 399–406, ibid., 53. 344. “GC,” lines 415–18, ibid., 53. 176 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 In The Day of Doom, Wigglesworth echoed the same sentiments. The sinners of the land must bear in mind the penalties attached to their defiance: the day of final accounting would come upon them all. Adulterers and Whoremongers were there, with all unchast, There Covetous, and Ravenous, that Riches got too fast. Who us’d vile ways themselves to raise t’ Estates and worldly wealth, Oppression by, or Knavery, by force, or fraud, or stealth. 345 Thus one and all, thus great and small, the Rich as well as Poor, And those of place as those most base, do stand the Judge before. 346 Only those who had been fair dealers in life might hope to escape God’s wrath: {139} strivers. Idolaters, Adulterers, Church-robbers we were none, Nor false-dealers, no couzeners, 347 but paid each man his own. Our way was fair, our dealing square, we were no wasteful spenders, 345. Wigglesworth, “Day of Doom,” stanza 32, ibid., 63. 346. “Day,” stanza 53a, ibid., 69. 347. Cheaters, defrauders: Meserole, 79n. From Medieval Economics to Indecisive Pietism: 177 A Chalcedon Publication [] 3/30/07 No lewd toss-pots, no drunken sots, no scandalous offenders. 348 Few documents of the day gained wider circulation than The Day of Doom. The sale of the first edition alone, Meserole informs us, pro- vided a copy for every thirty-five inhabitants, some 1,800 copies. “No single poem—indeed no other work of literature—so captured the popular imagination of Puritan America as did The Day of Doom.” 349 Wigglesworth established a new genre, the jeremiad of crisis. In the earlier jeremiads of abundance, the listeners were warned not to forget the Giver of all material blessings, or else His wrath would follow. Wig- glesworth’s emphasis was different: accepting New England’s achieve- ment of abundance, he then turned to the evidence of existing wrath, proclaiming that “sorer judgments are at hand,/ Unless thon quickly change.” He, too, was operating in terms of the paradox of Deuteron- omy 8—obedience, blessing, forgetfulness, curse—only he was con- vinced that New England had crossed the bridge between blessing and forgetfulness in his day, and the curses of God were now imminent. This became the frame of reference for the jeremiad of crisis, the stan- dard form of sermon in the second generation. Ownership and Stewardship The doctrine of Christian stewardship preached by the second generation’s clergy did not vary from that laid down by the founders. Indeed, it was hardly distinguishable from Aquinas’s perspective, inso- far as the concept of God’s ownership of the world is concerned. But the Puritan emphasis on the final day of accounting stands out in a special way. Increase Mather’s language was aimed at calling for the continual exertion that is involved in the constant supervision of the whole of one’s estate: Yea, men shall be called to an account in that day, not only for all that they have done, but for all that they have received.... Whatever talents God shall entrust to any man withall, first or last a day of reckoning will come. The Lord Jesus will say to some at the great Day, You had 348. “Day,” stanzas 92–93, ibid., 79. 349. Meserole, 37. 178 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 such estates in the world, but what did you do with your {140} riches? Did you improve them for God, or did you not abuse them for sin and to dishonor His name? 350 A man’s labor must be accomplished within his allotted portion of time—“O what a case are they in, that death cometh upon them and their work not done!” 351 Every moment of a man’s life must be accounted for. 352 But a man’s time is only one part of God’s claim upon a man. “Our estates should be improved for Him; God has a right in every man’s estate.…” 353 The primary right of ownership belongs exclusively to God, and because of this fact, the requirements of fruit- fulness, growth, and improvement are placed upon men as ethical imperatives. Although the jeremiads of crisis, due to their implied pes- simism, generally avoided any serious consideration of the possibility of aggregate economic expansion (unlike sermons of the first genera- tion), the hope for and even insistence upon personal and family eco- nomic development was still present. The abhorrence of the waste of any gift from God was an obvious corollary to the doctrine of stewardship. This was as true for the sec- ond generation as for the first. Samuel Willard’s Mercy Magnified on a Penitent Prodigal (1684) dwells on this theme repeatedly. Willard left no doubts in the mind of any reader as to his attitude on the relation- ship between sinners and waste. “Unregenerate men are the greatest spendthrifts; for they unprofitably waste all their substance upon their lusts.” 354 Instead of using their property for God’s glory, they spend it on sensuality and profaneness. 355 This, of course, does not mean that a man can judge himself righteous simply because he saves his money; the covetous man may save his wealth, but he too is a waster, deceiving himself. 356 Willard went so far as to use the language of trading to con- trast saving grace and common grace; in doing so, he penned a sen- 350. I. Mather, The Greatest Sinners (1686), 88. 351. I. Mather, The Doctrine of Divine Providence (1684), 143. 352. I. Mather, Testimony Against Prophane Customs ([1687] 1953), 35. 353. I. Mather, Providence, 146. 354. Willard, Mercy Magnified on a Penitent Prodigal (1684), 64. 355. Ibid., 65–66. 356. Ibid., 72. From Medieval Economics to Indecisive Pietism: 179 A Chalcedon Publication [] 3/30/07 tence that, if taken out of context, would have horrified even the stereotyped Papist indulgence salesmen found in sixteenth-century Protestant tracts. “Nothing is profitably laid out, but what is expended for salvation: this is the only saving purchase that any of the children of men can trade for....” 357 His point, however, was quite orthodox: the impotence of common grace in one’s salvation. The best improvements that nature can make of God’s common favors cannot bring them to find and enjoy blessedness. Let men use them never so frugally and providently, according to the measures which they take of prudence and frugality, yet they will fall short.... 358 {141} One’s concern must be for the obedient, righteous administration of the property entrusted to each person by God. The goal is therefore ethical and soteriological, but the task, being earthly and therefore fraught with moral danger, must be regarded as innately systematic. Waste is not to be tolerated. Urian Oakes called attention to the danger of confusing ends and means. The goal is the service of God; the means are gifts from God. In an almost prophetic passage, one which antedated Max Weber by two centuries, Oakes announced: This world and the things of it were made for the service and accom- modation of man in his way of serving God. Man had originally an empire and dominion over these creatures here below.... But sin hath inverted this order, brought confusion upon the earth. Man is dethroned, and become a servant and slave to those things that were made to serve him, and he puts those things in his heart that God hath put under his feet. Profits, pleasures, honors, these lusts of the world, are the masters, yea the idols of sinful men: the life of their spirits is in these things. 359 Weber misread the Puritan ethic when he wrote: “The idea of a man’s duty to his possessions, to which he subordinates himself as an obedient steward, or even as an acquisitive machine, bears with chilling weight on his life.” 360 Not the Puritan ethic, but rather the secularized derivation thereof, was to be characterized by the view of man as “an 357. Ibid., 79. 358. Ibid., 80. 359. Oakes, A Seasonable Discourse (1682), 27. 360. Weber, The Protestant Ethic and the Spirit of Capitalism, 170. 180 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 acquisitive machine.” Oakes stated clearly that such a mental construct as “economic man” involves the death of the Puritan view of man, for it necessarily subordinates man to the creation instead of to the Creator. Puritans believed in the sovereignty of God and the vicegerency of men over God’s creation. There was no concept more basic to the social outlook of the Puritan world. Man was seen as passive toward God and active over creation. Richard Steere’s poem, Earth’s Felicities, Heaven’s Allowances, sketched the archetype of the godly Puritan activist: But for a man to know the highest joys This World affords, and yet without offence; To Live therein, and as a Master use them, In all Respects, and yet without abuse.… This man subjects to one, Commands the other, Owns God his Master, makes the World his Slave. 361 Abandon this perspective, Oakes warned, and man becomes passive toward the world and an active rebel against God. To grant to the affairs and needs of the world such a degree of autonomy was regarded as an act of idolatry, a worshipping of the creature and not the Creator. {142} With this kind of activism as its foundation, how was it possible that the second generation lost the commitment to earthly triumph which had motivated their fathers? The jeremiads present some evidence in this regard. The breakup of religious unity, the fragmentation of local and colony politics, the failure of the children to own the church cove- nant, the impact of King Philip’s War, and all the other blasts of God’s disfavor that were catalogued in the jeremiads combined to destroy the clergy’s hope in reaching the population and making of them godly Puritan activists. Oakes himself retreated into a pietistic world of indi- vidual victory apart from collective dominion. His sermon, The Uncon- querable, preached before the local militia in 1672, had as its theme the individual triumph of each Christian soul, but it never mentioned the possibility of a victory of the army of Christian soldiers. In fact, it pointed to the victories of Satan’s armies as being typical of earthly affairs. “The great conquerors of the world have been slaves to their 361. Steere, “Earth’s Felicities,” lines 286–89, 298–99, in Meserole, 259. From Medieval Economics to Indecisive Pietism: 181 A Chalcedon Publication [] 3/30/07 own pride, ambition, vainglory, covetousness, and other base lusts, which a Christian subdues and conquers. Many of them have been Satan’s slaves, when they have been masters of the world.” 362 God promises total victory only on the final day. “In the meanwhile, our work is to wait and pray, and exercise faith and patience....” 363 William Stoughton produced a comprehensive theory of stewardship. A hierarchy of stewards operates under the sovereignty of Jesus Christ, the “one great Steward,” who in turn works under the Father in this present dispensation. Gifts of all kinds are talents provided to men that they might improve them. “To betray a man’s trust, or not to improve his talent, is to lie and deal falsely, for of a steward it is required that he be faithful, 1 Cor. 4:2.” 364 Faithfulness to God is demonstrated, there- fore, by a conscientious improvement of one’s estate. Stoughton relied on the metaphor of bankruptcy to drive home his theological point. “It will be a doleful thing to be of a broken credit with God, and for the Lord to pronounce us bankrupt.” 365 True to the outline of the jeremiad, he concluded by pointing out that God filled His wilderness house with jewels and gold, whereas the present generation fills it with lumber fit for burning. 366 The leaders of the first generation had made it plain for all to hear that a commonwealth’s poverty or success could not be viewed, in and of itself, as demonstrating its position covenantally. External covenant blessings were, at best, a sign of obedience of the collective society to God’s covenant {143} requirements; possibly a gift for the sake of a godly remnant; or at worst a means of condemning a godless society, making its punishment that much worse when its time has come. External blessings of the society were only indirectly connected with the condition of the hearts of individuals: a society without Christians in it could not be expected to meet the terms of the civil covenant for very long. The founders no doubt expected that a society of saints 362. Oakes, The Unconquerable, All-Conquering & more-then- [than-] Conquering Souldier (1674), 16. 363. Ibid., 24. 364. Stoughton, New-Englands True Interest (1670), 14. An election sermon of 1668. 365. Ibid., 25. 366. Ibid., 28. 182 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 would meet the terms of civil government as set forth in the Bible, but they would not have said, as their sons were to say, that mere conver- sion and an owning of the church covenant would necessarily bring God’s blessing to the commonwealth apart from the collective obedi- ence of society to its covenantal standards. Each covenant has its own responsibilities. On the question of personal poverty or wealth, the two generations were in agreement. Wealth as a sign of personal salvation was no less repugnant a doctrine to the sons than to the founders. Eleazer Mather, Increase’s brother, set forth the general principle: the time was when there was less of the world, “but was there not more of heaven? less trading, buying, selling, but more praying, more watching over our own hearts, more close walking; less plenty and less iniquity....” Men were advised to take up “the New England prayer, Lord keep me poor and keep me humble.” 367 Thomas Shepard, son of the more famous minister, dismissed the idea that personal wealth indicates personal holiness with that Puritan term reserved for the most heinous theological deviations: the whole idea is Papist. 368 God’s gifts to individuals must be constantly improved if they are to be regarded as signs of election, wrote Willard. 369 Gener- ally, wealth strengthens sinful hearts. 370 The ungodly, wrote Oakes, merely store up wealth for the godly, who receive it “sooner or later.” 371 Echoing Cotton and Shepard, the preachers of the second generation 367. E. Mather, A Serious Exhortation to the Present and Succeeding Generation in New-England (1671), 9. He did, however, hold to the view that prosperity could be a sign of God’s collective blessing on a community of saints who “have learned to want as well as abound; ...” But if men make gods of their riches, they are in deep trouble. “Outward prosperity is a worm at the root of godliness, so that religion dies when the world thrives, Deut. 28.47. & 32.15.” Thus, he concluded, “prosperity in itself is of that nature that it is hard to judge of love or hatred, preference or absence of God with or from a people thereby ....” Ibid., 9. Cf. William Adams, The Necessity of the Pouring out of the Spirit from on High (Boston, 1679), 20, 30. 368. Shepard, Eye-Salve (1673), 36. This was an election sermon for 1672. 369. Willard, Useful Instructions for a Professing People in Times of Great Security and Degeneracy (1673), 6. 370. Willard, Mercy Magnified, 57, 60. 371. Oakes, New-England Pleaded with (1673), 33. Election sermon, 1673. From Medieval Economics to Indecisive Pietism: 183 A Chalcedon Publication [] 3/30/07 reminded men that the only testimony to rely on is the testimony of God’s Spirit to each man’s spirit. Men were called, in every jeremiad, to search their hearts and not look to their own prosperity for signs of their favor with God. {144} Stewardship, in the last analysis, demands full accountability from each human being. The requirement for every man’s life is inescapable: man must not live aimlessly, unsystematically, in any of life’s realms. The anonymous sermon, The Crown and Glory of a Christian, which went through at least three editions, emphasized work and downplayed the emotional introspection recommended by many second-genera- tion sermons. Be not poring and puzzling too long about laying your foundation; but having once laid Christ (alone) your foundation, go then to build upon it.... Live not at random, but square your life by the rule of right- eousness, to wit, the Word of God, in thought, word and deed; at night call your faithless heart to an account how oft and how much you have come short of that rule the day past.... 372 Not continual, morbid self-examination concerning one’s salvation, but continual reexamination of one’s work: does it conform, and how shall I make it better? It was this attitude of rationalization of the various tasks of life that later characterized Benjamin Franklin’s thirteen steps to personal virtue. 373 “Depend upon God for a blessing upon your daily labors,” wrote the anonymous author. 374 Do not expect your own labors, autonomously, to bring fruit; your job is only to do your duty. The author did not expect men to paralyze themselves with terror about their salvation; having laid Christ once as the foundation, a man is then to go and build upon it. Rational, systematic work is enjoined, and not mystical contemplation and examination of self. Work is the steward’s task. The blessings are God’s responsibility and so is one’s salvation. So long as a man is striving constantly to conform his whole life to the biblical requirements, he is doing his job in a fruitful manner. He will not be found short on the day of final accounting. 372. Crown and Glory, 3rd ed. (1684), 10–11, 29. 373. Franklin, Autobiography (1960 ed.), 93–95. 374. Crown and Glory, 42. 184 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Status and Social Mobility In 1676, William Hubbard preached a most unrepresentative elec- tion sermon in which he called for less diligence by magistrates in try- ing to weed out heretics. 375 Jonathan Mitchel’s Nehemiah on the Wall, a 1667 election sermon, was more familiar (except for its optimism): he called for the magistrates to exercise their traditional responsibilities in the field of economics. He wanted a stronger civil government. Unlike Willard, {145} Mitchel put the responsibilities of stewardship squarely on the shoulders of the civil magistrates of his day. Stewardship is one of the primary tasks of rulers. As personal stewards over the common- wealth’s economy, they, and not some autonomous market mechanism, are the primary actors in this universe of secondary causation and per- sonal responsibility. That which this respect, but especially in reference to necessary livelihood, when it is a time of distress and poverty, or special scarcity in this or that, of food or cloth- ing.... No man can wholly exclude himself from being his brother’s keeper, Gen. 4:9, but the keeping of the commonwealth of all their brethren is in a particular manner committed to the rulers; they are called in the Scripture shepherds. 376 By calling for action on the part of the rulers in specific economic matters of scarcity, Mitchel returned to the outlook of the 1640s. His colleagues might preach in vague terms about economic or social evils in general, but they were not inclined to be this specific in their elec- tion sermons. Mitchel, like all Puritans, saw God as the sovereign owner of creation, but he argued that God had entrusted this responsi- bility to the civil authorities, “to keep and maintain His possession of it. 375. Hubbard, The Happiness of a People (1676). For a partial analysis of this sermon, see Anne Kusener Nelson, “King Philip’s War and the Hubbard-Mather Controversy,” William and Mary Quarterly, 3rd Ser., 27 (1970): 615–29. Hubbard did not blame the outbreak of the war on the usual sins enumerated in a standard jeremiad. The cause, he said, might well be some special, hidden sin which we do not now know about (54). God does not bother to engage in our petty quarrels (50–51). 376. Mitchel, Nehemiah on the Wall (1671), 4, 7. Election sermon, 1667. From Medieval Economics to Indecisive Pietism: 185 A Chalcedon Publication [] 3/30/07 The eyes of the Christian world are upon you....” So, for that matter, are the eyes of God and His angels. Rulers must therefore seek “the welfare of the people.” 377 Citizens obviously have a major responsibility in obeying the magis- trates. “Keep order; keep in your places, acknowledging and attending the order that God hath established in the place where you live.” In short, “leave the guidance of the ship to those that are fit at helm, and are by God and His people set there....” 378 Here Mitchel’s colleagues were in absolute agreement. The jeremiads universally pointed to the failure of the citizenry to respect their superiors, whether in the family, the church, or in civil government. The key word was “pride.” It was invariably followed by an outraged cry against deviations in personal fashion. The preachers focused on the supposed wilderness condition of the land as justification for their outrage. “People in this land have not carried it,” wrote Increase Mather, “as becometh those that are in a wil- derness, especially when it is such an humbling time as the late years have been.” 379 Both rich and poor are involved, said Mather, “especially here in Boston.” The daughters of Zion adopt any “proud fashion” that appears. Men are to be seen {146} continually in their “monstrous and horrid perriwigs ... whereby the anger of the Lord is kindled against this sinful land.” 380 It was one thing for John Winthrop to challenge Thomas Dudley in 1632 for the latter’s ostentation in adorning his home with wainscot- ting (a wooden paneling on the walls of a house). He had more justifi- cation in his complaint, since it was, as he said, “the beginning of a plantation.” 381 Even so, it is not hard to understand Dudley’s anger when Winthrop had the frame of his house removed. Winthrop him- self, when challenged, “acknowledged himself faulty” in taking the responsibility on himself without consulting anyone. 382 But when half 377. Ibid., 19. 378. Ibid., 26. 379. I. Mather, Earnest Exhortation, 7. 380. Ibid. Cf. Samuel Danforth, A Brief Recognition of New-Englands Errand Into the Wilderness (1671), 3; James Fitch, An Explanation of the Solemn Advice (1683), 42. 381. Winthrop’s Journal, vol. 1, 77. 382. Ibid., 84–85. 186 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 a century had elapsed, we find the same argument of New England’s “wilderness condition” being used to justify the meddling of the civil authorities in community fashions. The sermons which, a few pages earlier, had praised God for His bounty in making a former wilderness fruitful, could hardly be expected to convince the newly rich (or the hopefully optimistic social climber) that his, or his wife’s, style of dress in some way constituted deviation from some hypothetical “wilderness standard.” Puritan preachers of the second generation, like those of the first, accepted the medieval heritage of the idea of a hierarchy of fixed—or nearly fixed—orders in society, each with its own powers, responsibili- ties, temptations, privileges. This was a universal Puritan perspective, as common in English Puritanism as in colonial America. 383 But the phenomenon of economic growth, in part aided by the Puritan con- cepts of stewardship, rational planning, the calling, and (in the early period) optimistic eschatology, brought with it additional “side effects,” such as social mobility which was more fluid than anything imagined by medieval theologians. Of course, as the biologist Garrett Hardin has argued, the phrase “side effects” is really a bit of word magic: effects are effects. 384 Upward social mobility was a concomitant to the idea of per- sonal responsibility and the right of the individual believer to exercise his responsibility in a calling. He was commanded to improve his tal- ents, and if he was successful, his station would obviously be improved. Only if all other men improved their stations to the same extent— mechanically—would the problem of social mobility be avoided, and no one believed that such would ever be {147} the case in a society in which sinners, saints, and even Presbyterians might find themselves thrown together. Some men would succeeed and other would fail. What baffled Puritan commentators was the incomprehensible rapidity of social change in the New England colonies, especially in Boston. 383. Thomas F. Merin, ed., William Perkins, 1558–1602 (1966), 189, 209 (from bk. 3 of The Whole Treatise of the Cases of Conscience); cf. M. M. Knappen, Tudor Puritanism ([1939] 1965), 412. Richard Baxter, Chapters from A Christian Directory, ed. Jeannette Tawney (1925), 158ff. 384. Garrett Hardin, “To Trouble a Star: The Cost of Intervention in Nature,” Bulletin of the Atomic Scientists (January 1970): 19. From Medieval Economics to Indecisive Pietism: 187 A Chalcedon Publication [] 3/30/07 It was a society in which a servant could elevate himself to wealth within a few decades, especially if he was a skilled craftsman. John Hull, one of the most respected men in Boston and surely one of the richest, had raised himself from very modest circumstances. 385 At any given point in time it was virtually impossible to be certain of an indi- vidual’s “proper” stratum in society, except in cases of extreme poverty or wealth. Social status was to the second generation what the just price had been to the first: an elusive quality which refused to be quantified or even defined. Yet the very elusiveness of the idea hypnotized Puritan preachers. They were certain that a definition could be found, but the perverse changes within the society kept it concealed. In their eyes, the evil lay with the society and not with the lack of definition. Changes in fashions, imitation by members of lower classes of their social superi- ors, the increase in affluence of the lower class as a class, this perverse unwillingness of men to keep in their original social positions into which they were born, all combined to convince Puritan commentators that New England society was in the process of dissolution, a sign of God’s departure from the land. By 1674, Increase Mather (whose very name seemed to cry out against his theory of fixed status) had con- cluded that the violation of the fifth commandment, whereby inferiors rise up against superiors in the commonwealth—in schools, families, churches—was the chief sin of his generation: “If there be any prevail- ing iniquity in New England, this is it.... And mark what I say, if ever New England be destroyed, this very sin of disobedience to the fifth commandment will be the ruin of the land.” 386 Willard saw the same crisis in the same institutions. 387 Daniel Denison’s last sermon, appended by William Hubbard to his funeral sermon for Denison, and published two years after the funeral, cites ambition as the curse of the land, along with envy: “... Ambition is restless, must raise commotions, that thereby it might have an opportu- 385. T. B. Strandness estimates that only two or three men could have been richer than Hull in 1680 New England: Samuel Sewall: A Puritan Portrait (1967), 33. A standard account of Hull’s life is found in Samuel Eliot Morison, Builders of the Bay Colony (1930), chap. 5. On the upward social mobility possible in this period, see Perry Miller, “Declension in a Bible Commonwealth” (1941), in Miller, Nature’s Nation, 40–47. 386. I. Mather, The Wicked Mans Portion (1675), 17. Preached in 1674. 387. Willard, Useful Instructions, 75. 188 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 nity of advancement, and employs envy to depress others, that they fancy may stand in their way....” 388 Such ambitious men are unwilling “to abide in {148} the calling, wherein they are set; they cannot stay for the blessing, nor believe when God hath need of their service, he will find them an employment, whatever stands in the way of their design, must give place....” 389 The clergy’s problem, of course, was to establish guidelines to decide in any given case whether a man’s ambition was of the restless sort, or whether the individual was simply exercising his calling. But to argue, as Denison did, that a fixed calling is basic to God’s plan for each man, involved him in a form of medievalism which was not likely to survive the acids of the competitive market mecha- nism, with its concept of voluntary free labor, the right of private con- tract, and profit in terms of an impersonal price mechanism. The Boston Synod of 1679 listed pride in apparel and the illegitimate imitation by servants of the dress of their superiors, as early entries in its catalogue of over a dozen social evils that had brought miseries to New England. 390 Five years earlier, Increase Mather had announced his difficulty in distinguishing the dress of the regenerate from that of the unregenerate. It is a dark day when “professors of religion fashion themselves according to the world.” 391 But given the existence of this sin, what could be done to correct it? What are the standards of legiti- mate fashion for a godly society? Like the standards of economic oppression, the just price, and usurious interest, the standards of proper fashion were elusive. Theologians were sure only of their theo- retical existence, but not of their actual definitions. Urian Oakes strug- gled costly garments are all right (2 Sam. 1:24). 388. Denison, Irenicon, attached to Hubbard, The Benefit of a well-ordered Conversation (1684), 195. 389. Ibid., 196. 390. Boston Synod, The Necessity of Reformation (1679), 2–3. 391. I. Mather, The Day of Trouble is Near (1674), 22. From Medieval Economics to Indecisive Pietism: 189 A Chalcedon Publication [] 3/30/07 Nor am I so severe, or morose, as to exclaim against this or that fash- ion,i- tated {149} ruinous condition, and the Lord calls to deep humiliation. This is very displeasing to God, and both Scripture and Reason condemn it. 392 Oakes put most of the Puritan theologians’ opposition to the mod- ern world into one lengthy exposition: excessive social change breaks down familiar communal standards—standards that function to keep members of differing classes in traditional occupations and in dress reflecting those occupations. The hierarchy of medieval life—a hierar- chy reflecting a great chain of being from God down to Satan—was being shattered by the winds of change. Men and their wives were increasingly unwilling to accept such limitations on the exercise of their property rights. The appeal of the theologians to “civil custom” was precisely the issue in question: in a society experiencing rapid social change—from a tiny frontier community to a productive com- ponent of Atlantic trade and culture—civil customs were no longer fixed, universal, or a function of clerical opinion. 393 The very fluidity of fashion, where new styles swept through the community, reflected the lack of fixed standards and in turn dismayed the preachers. Status distinctions were supposed to be respected by members of a Holy Commonwealth; this meant that each status required its appro- priate set of fashions. James Fitch, like Mather and Oakes, blamed the 392. Oakes, Pleaded, 34. 393. On fashions in New England, and on the resistance of the ladies to exhortations from the pulpit concerning deviant fashions, see Alice Morse Earle, Customs and Fashions in Old New England (1894), chap. 13. 190 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 poorer sort for their imitation of social superiors on precisely this ground: they made it difficult to determine their proper station in life. 394 But one basic question never seemed to occur to them: in a soci- ety in which men are not only free to increase their estates, but in fact have a moral obligation to do so, should they not be expected to improve their own personal statuses? If frugality, rational use of time and resources, systematic accounting, and a future-oriented view of the world are allowed to combine into an ethos favoring both individual and aggregate economic growth, then social mobility, upward and downward, should be characteristic of the particular society. Yet the Puritan theologians of the second generation did not reach such a con- clusion. Therefore, the crucial question for their purposes should have revolved around the nature of formal legislation necessary to redirect the citizen’s expressions of personal taste in fashion. This was the great stumbling stone for the Puritan oligarchs. They were never able to devise recommendations for formal legislation of this kind. But this inability did not keep them from railing continually about the deviant behavior of their contemporaries. Fashions continued to degenerate, economic oppression continued unabated, and factions seemed end- less. Worthington C. Ford’s description holds true: “Massachusetts Bay was {150} becoming degenerate, the older generation said. It is always becoming degenerate.” 395 The Reshaping of Community Property, Puritans were constantly reminded, has to be used princi- pally for the service of God and secondarily (yet concomitantly) for the service of the community. The use of property for private purposes is legitimate only after the needs of the community (including one’s fam- ily) have been met. Thus, it was natural for jeremiads to pay an increas- ing amount of attention to the signs within the commonwealth of concern for exclusively private interests and the sacrifice of public ben- efits. The operation of an impersonal market was not viewed as a device for the integration of private and public interests, at least not in 394. Fitch, Explanation, 43. 395. Worthington C. Ford, “Sewall and Noyes on Wigs,” Publications of the Colonial Society of Massachusetts 20 (1917–19): 112. From Medieval Economics to Indecisive Pietism: 191 A Chalcedon Publication [] 3/30/07 its progressively autonomous form, and therefore the spread of private production for a market was viewed with suspicion and incomprehen- sion. “The reason why men bring no fruit to the glory of God,” Increase Mather declared, “is because they have so much of a private selfish spirit prevailing in them. All seek their own, not the things which are Christ’s.” 396 One obvious example of this self-seeking—obvious to the ministers—was the parsimonious attitude of the towns and congrega- tions with respect to ministerial salaries. He was so incensed about this that he momentarily (perhaps by accident) gave up the cherished doc- trine of the golden age of the first generation and its corollary, the degeneration of the sons. He cited a letter he had received from John Davenport, the last of the first generation’s ministers to die, in which Davenport quoted John Cotton—two decades in the grave—as saying that “the ministry of the Gospel is the cheapest commodity in this land....” So it is today, said Mather, forgetting briefly that the function of the jeremiad was to catalogue degeneration and not continuity. 397 Oakes used threats as well as cajoling: men who pursue their own self- ish ends will have their labors cursed by God and be brought to naught. 398 Men are simply not fit to be left to their own autonomous devices. “If God leave men,” wrote Willard, “they waste all. That every unregener- ate man is not as vile and profligate as any ever was, is of God’s restraining grace; but if he withdraw and that man be left to himself, all goes to rack.... It is therefore a dreadful judgment of God for any man to be left to himself.” 399 Men desperately need restraining institutions and responsibilities; {151} laissez faire is ludicrous from this perspec- tive, assuming the existence of a social hierarchy of the responsibility imposed by God. So Willard bewailed “a selfish spirit growing among the most, together with a neglect of one another’s good,” for these are signs of God’s departure from New England. Civil authority would 396. I. Mather, Greatest Sinners, 117. 397. I. Mather, Earnest Exhortation, 7–8. 398. Oakes, Pleaded, 12. 399. Willard, Mercy Magnified, 69. 192 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 inevitably fragment. Puritan theology had an innate hostility to human autonomy. Throughout this thirty-year period the common agricultural fields were in the process of dissolution. As the battle over control within each town was waged among the competing groups that claimed the authority to supervise the land divisions, social friction was a visible effect. The town of Sudbury, by 1660, had already gone the way of con- tentious communities, splitting into two separate communities. 400 Other towns seemed to be heading for a similar fate. Pastors saw the threat clearly: new towns would eventually demand their own leaders, churches, schools, and other associations, thus removing the present sheep from the local flock. Increase Mather cried out against such alterations in the structure of land tenure, never quite grasping the nature of the changes that were making such alterations economically rational: Idolatry brings the sword, and covetousness is idolatry. Land! Land! hath been the idol of many in New England. Whereas the first planters here, that they might keep themselves together, were satisfied with one acre for each person, as his propriety, and after that with twenty acres for a family, how have men since coveted after the earth, that many hundreds, nay thousands of acres have been engrossed by one man, and they that profess themselves Christians have forsaken churches and ordinances, and all for land and elbow room enough in the world. 401 A policy of communal ownership of a common field involved con- stant supervision by the authorities against timber thieves, wandering animals, broken fences, and other forms of private profiteering on “unowned” property. The greater the possibilities for private profit, the more difficult the task of administering the commons became. With the expansion of the market into interior towns, it became possible for farmers to reserve at least a small portion of their crops or goods for sale, and this increased the economic pressures favoring the private administration of small parcels of land. Production for an impersonal market was slowly making inroads into the highly personal adminis- tration of local common lands, thus forcing a replacement in land ten- 400. Sumner Chilton Powell, Puritan Village, chaps. 8–9. 401. I. Mather, Earnest Exhortation, 9. From Medieval Economics to Indecisive Pietism: 193 A Chalcedon Publication [] 3/30/07 ure. Men producing for a market did not want counterclaims against their capital—land—from neighbors, especially given the tremendous investment of human labor that was necessary for making marginal land productive. They were taking very seriously the Lord’s command to improve their estates, and private ownership, consolidation, and geographic {152} dispersal away from a central village were basic in such improvement. If they were to bear individual responsibility before God on the day of judgment, men wanted to have individual authority over their property. A family could exist on two dozen acres if it had access to the commons and a subsistence economy was the only goal. A single family removed from the commons needed closer to eighty acres to survive. 402 But many pastors saw these new requirements as sinister changes in the society. The lust for wealth had now spread from arti- sans and merchants, groups always suspected of covetousness, to yeo- men on the land: “Do not your own consciences tell you that the market and price of ordinances is very low this day? Houses and lands, lots and farms, and outward accommodations are of more value with many people than the Gospel and Gospel-ordinances.” 403 Economic oppression was viewed as endemic in this new state of affairs: the poor exploit the rich (excessive wages) and the rich exploit the poor (excessive prices of goods). Self-seeking men abound, said Shepard, men who hold to a “lax, merry, loose religion....” Men today are not like those of that “first good old generation.” 404 Day laborers are demanding impossible wages; usury is common—complaints like these occur in sermon after sermon. 405 Like Luther a century and a half ear- lier, Increase Mather challenged the ethical propriety of any economic arrangement in which the poor man could be charged as much for a good or service as he was actually willing to pay in every circumstance. There could be no appeal to anything like the impersonal forces of sup- 402. Kenneth Lockridge, in his study of the town of Dedham, has estimated that the need for acreage was in the 60–90 acre range. The high average was necessary so that part of the land could lie fallow each year. Lockridge, A New England Town, 149n. 403. Oakes, Pleaded, 30. 404. Shepard, Eye-Salve, 34. 405. I. Mather, Earnest Exhortation, 11. 194 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 ply and demand; oppression is always oppression and always personal. Individuals must bear full responsibility for their actions: And is there no oppression amongst us? Are there no biting usurers in New England? Are there not those that grind the faces of the poor? A poor man cometh amongst you, and he must have a commodity, whatever it costs him, and you will make him give you whatever you please, and put what price you please upon what he hath to give, too, without respecting the just value of the thing. Verily I am afraid that the oppressing sword will come upon us because of the oppressions and extortions which the eyes of the Lord’s glory have seen amongst us. 406 The seller was not seen as being under the restraints of competition from other sellers, nor was he seen as being restrained by the limits of the potential {153} buyer’s willingness to forego the purchase. Sellers can make men pay whatever they please. This outlook betrays Mather’s implicit medievalism, in which each producer is the local specialist, able to restrict entry by competitors, dealing with everyone on a purely personal basis, as if he were in the position of the medieval miller, i.e., the only supplier of the particular service. All relations are purely personal, and therefore economic transactions are invariably ethical affairs; terms imposed by the stronger upon the weaker are not simply Frank Norris’s vision of “all the traffic will bear,” but a system in which the traffic will bear anything, in principle, and can be brought to manageable, just proportions only by the voluntary restraint of the stronger party in a bargain. New England has become, echoed Oakes, the place where there is continual “griping and squeezing and grinding the faces of the poor and greediness,” a place where the private spirit crushes charity “to the damage of the public and disgrace of religion.” Unregulated economic competition spells the end of men’s personal development spiritually: “Hence no progress in a cause of piety, no getting onward in the jour- ney of heaven. You have men now where they were twenty years ago, for they are sunk and stuck fast in the mire and clay of this present world and cannot stir....” 407 It was a triumph, said Benjamin Keatch, of the impersonal ledger book over the demands of faith: 406. I. Mather, Day of Trouble, 22–23. 407. Oakes, Pleaded, 33. Cf. Crown and Glory, 59ff.; Fitch, Explanation, 45–46. From Medieval Economics to Indecisive Pietism: 195 A Chalcedon Publication [] 3/30/07 Merchants and Traders have a nimble Art, To sum their Shop books, but neglect the Heart; For that they think there’s time enough, and look: But seldom to the Reck’nings of that Book.... Many like drones, on other’s Toil do live, Though ‘tis less honor to receive than give. What Lying, Cheating, Couz’ning and Deceit Do Traders use? O! how they overrate What they would sell? But if they be to buy, They undervalue each Commodity. 408 Men buy cheap and sell dear. Divisions, contentions, factions, law- suits: everywhere the clergy observed a splintering of the society. The ideal of the peaceable kingdom is being challenged at every point. 409 These are the signs of God’s departure. 410 Here are the signs of the weakness of Christ’s community of formerly godly men. 411 The end is clear, given the paradox of Deuteronomy 8: “I say,” wrote Shepard, “if after all this we will now turn our backs and revolt from God, we may then expect the Lord {154} [will] turn this fruitful land back into a wil- derness again, Psal. 107.34.” 412 From wilderness to fruitfulness and back again: the road is certain. 413 The commonwealth needs unity, for “Unity of counsel is one of the chief foundations of civil polity; but if the foundations be dissolved, what can the righteous do?” 414 But instead of unity of counsel, New England is plagued by a plurality of lawyers, whose commitment to the formal legal principle that every man is due his day in court thwarts the operation of substantive justice: ... the suppressing of such as will for their own ends espouse any case, right or wrong, and by their wits put fair cloak upon a foul case, and 408. Keatch, Sion in Distress, 3rd ed. (1683), 29. The poem appeared in the midst of a sermon. 409. Stoughton, True Interest, 21; E. Mather, Serious Exhortation, 10. 410. I. Mather, Day of Trouble, 10. 411. Hubbard, Happiness, 18. 412. Shepard, Eye-Salve, 33. 413. Hubbard, Happiness, 61. 414. Ibid., 17. 196 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 create needless suits, and be incendiaries in places, and maintain con- tention that contention might maintain them, such as care not who loses, so that they may gain: I say to suppress such will be of great use to the maintenance of justice and peace. 415 Every man is not entitled to the best defense possible. The innocent man is; the guilty man is guilty. The modern legal system’s faith in tri- umph of substantive justice, through the interaction of contenders in a court of formal, lawyer-directed law, was as repugnant to the Massa- chusetts theocracy as was the idea of the triumph of substantive eco- nomic justice through the formal operation of an unhampered market system. Lawyers were like uncontrolled prices in the view of the New England clerics: useful for some purposes in quiet, normal times, but not to be trusted as universally reliable guides to human action. To allow lawyers or the price system free autonomous operation in the midst of a Christian society would be to promote the destruction of that society. Continual contention and oppression, respectively, would be the inevitable results. The Function of the Jeremiad “The problem, as the second generation saw it,” writes Robert Mid- dlekauff, “was to explain the decline of New England and to prevent the decline {155} from becoming a fall.” 416 Members of the third gener- ation were not showing the necessary signs of conversion along the 415. Samuel Arnold, David Serving His Generation (1674), 17. This was a Plymouth election sermon. For a similar criticism of lawyers, see the Synod’s conclusion in Necessity of Reformation, 6. Connecticut passed a law in 1663 prohibiting the use of lawyers in misdemeanor cases: The Public Records of the Colony of Connecticut, vol. 1, 395. [Cited hereinafter as CCR.] Unfortunately for the over-optimistic hopes in this regard by Winthrop and Cotton, citizens went to court against each other constantly in New England. Rutman cites the hostile comments of Winthrop and Cotton as examples of Puritan utopianism, and then marks the decline of that vision: “The prejudice against lawyers did not last. It gave way before need, for a people grasping for the rich opportunities of the New World unavoidably trespassed each other.” Rutman, Winthrop’s Boston, 234. Ultimately Rutman’s judgment is sound, although Thomas Lechford complained in the 1640s of the lack of possible income for a man of his profession. The jeremiads testify to the increase of lawyers in the final quarter of the century. This hostility was not confined to New England; Virginia expelled all lawyers from the colony in 1658: David Hawke, The Colonial Experience (1966), 292. From Medieval Economics to Indecisive Pietism: 197 A Chalcedon Publication [] 3/30/07 lines set down by their grandfathers: profession of faith, outward good behavior, and a relation of the circumstances of conversion. This last provision, added in the mid–1630s, was the stumbling block. The grandchildren apparently did not share the same kind of emotional conviction that the early settlers, fleeing England to establish a new society in the wilderness, had experienced. 417 The society seemed to be in the process of dissolution, as factions, quarrels, and controversy became commonplace. The second generation succumbed to the temptation of placing their fathers on a pedestal, regarding their own achievements as pale by comparison. Increasingly, change was regarded as decay. 418 The fathers had lived in an era of just dealing, external covenantal blessings, and purity of vision. Men shared with each other voluntarily, wrote the poet Benjamin Thompson. They were not concerned about fashions, their wives did not gossip, they were content with simplicity. “These golden times (too fortunate to hold) / Were quickly sin’d away for love of gold.” 419 This reconstruction of a mythical golden (i.e., goldless) age only served to remind the sons of the extent of the decay. That “good old spirit,” as Urian Oakes called it, was no longer in the hearts of New Englanders. 420 416. Robert Middlekauff, The Mathers: Three Generations of Puritan Intellectuals (1971), 98. 417. Edmund S. Morgan, Visible Saints: The History of a Puritan Idea (1963); Morgan, The Puritan Family, rev. ed (1966), chap. 7. Raymond P. Stearns and David Holmes Brawner do not agree with Morgan’s estimate of the radical break with the past represented by the mid-1630s requirement that candidates for membership relate their experiences associated with conversion. They see this additional requirement as stemming from a desire simply to make the traditional confession of agreement with church standards a bit more rigorous. It was only “a technical improvement” in the process of church purification. Stearns and Brawner, “New England Church ‘Relations’ and Continuity in Early Congregational History,” Proceedings of the American Antiquarian Society (April 1965): 13–45. On “technical improvement,” see 22. The fact remains, however, that the relation of conversion experience did add one more test for membership, the one most likely to deter a new generation of listeners who had not gone through the turmoil of founding a new Christian commonwealth. 418. Middlekauff, 103-4. 419. Thompson, “New-England Crisis” (1675), lines 13–14, in Meserole, 226. 420. Oakes, Pleaded, 27. 198 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Thomas Shepard had warned that in the last days carnal security should be a mark of declining churches. John Cotton’s sermons, God’s Promise to His Plantation, preached in 1630 before he had left England, had stated specifically, “if you rebel against God, the same God that planted you will also root you out again, for all the evil which you shall do against yourselves....” {156} The sermon was reprinted in 1686, reminding New England of the wages of sin. Everywhere they looked, clergymen saw “the decay of godliness.” Even as Shepard had cried out against a Christ-glutted age, so Oakes complained about a sermon- proof people whose lethargy could be shattered only by “some sharp affliction, some smarting rod, or sore trial” brought by God upon New England. 421 Clerics lived, officially at least, in the expectation of doom. The jeremiad became, as Perry Miller has argued, an utterly formal ritual. 422 First, it struck out against religious formality, which in turn was seen as a product of the hardness of human hearts. Then came a catalogue of general sins, including (typically) lying, fraud, oppression in business, disobedience to superiors, ostentatious fashions, worldli- ness, pride, covetousness, and tight-fistedness with respect to clerical salaries. Next, a list of contemporary calamities (or promised calami- ties) would appear, followed by an appeal to men to search their hearts, reform their lives, and acknowledge their covenantal responsibilities. Finally, the promise of God’s blessings was offered, His response to honest repentance. However, this was added almost as an afterthought; the pessimism of the jeremiad of crisis was, by the end of the period, quite pronounced. Superficially, these jeremiads seem to follow the earlier pattern of the Deuteronomy 8 paradox. The founders came, sermon after sermon informed the listeners and readers, in order to establish a plantation of religion rather than a plantation of trade. 423 Into wilderness, a true desert, God brought His people, and He made the land fruitful for 421. Ibid., 25. 422. Perry Miller, The New England Mind: From Colony to Province, 31ff. [Cited hereinafter as Colony.] 423. Increase Mather, Day of Trouble, 23; Oakes, Pleaded, 21; John Higgenson, The Cause of God (1663), 10; Boston Synod, Necessity of Reformation, [i]; “Severals Related to the Fund” (1682), in Andrew McFarland Davis, ed., Colonial Currency Reprints, 4 vols. ([1910] 1964), vol. 1, 109. From Medieval Economics to Indecisive Pietism: 199 A Chalcedon Publication [] 3/30/07 them. But prosperity has blinded their descendants to the nature of their calling on earth, namely, to act as God’s stewards. Thus, God is about to turn His back on the colony. His judgments are manifested everywhere. Apostasy produces calamity; therefore, His judgments are doctrinal teaching devices. 424 But the similarity to older forms of exhortation is only superficial. The structure of the jeremiad of this period indicates the futility of the exercise. The preachers were dubious about the possibility of establish- ing specific standards for the measurement of communal success in meeting {157} God’s requirements. A classic instance of this reluctance to establish external guidelines for success is found in Increase Mather’s introduction to his wartime jeremiad, An Earnest Exhortation To the Inhabitants of New-England (1676). The sermon had been writ- ten several months before publication, he informed the reader, and the military affairs of the colony had subsequently grown optimistic. King Philip’s Indian forces had been routed on several occasions. Mather realized that this turnabout tended to compromise the impact of his prophecy of doom. Men must not slacken their zeal in reforming the society’s provoking evils just because favorable military reports are coming in. God’s controversy with the land is not yet finished, he wrote. 425 “The Lord can easily punish us by the same instruments again, if we go on to provoke him. Yea, if the power and good provi- dence of God prevent it not, it will be so.” 426 In other words, outward success is no guarantee of God’s favors, while outward disasters should be understood as categorical proof of His displeasure. These times are not like the days of the early church, Mather warned, when outward disaster came upon Christians only because God was judging the pagan lands in which they lived. 427 This is a Christian society, and it stands or falls in terms of the obedience of its citizens. The jeremiad of crisis was therefore molded on the principle of “heads I win, tails you 424. “All judgments whatsoever, and in what way soever they come, are doctrinal; they bring instruction and teaching along with them, to those that either see or hear them, ...” Samuel Willard, Useful Instructions, 25. On apostasy’s role in bringing social calamity, see 16. God is calling men to a “universal awakening” through His judgments: 22. 425. I. Mather, Earnest Exhortation, [i]. 426. Ibid., [ii]. 200 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 lose.” Disaster is a prelude to even worse things to come, while external victories are, at best, temporary. Thompson might proclaim, “New England’s hour of passion is at hand, / No power except Divine can it withstand,” but when the hour of passion was actually withstood, preachers needed to shift the terms of the jeremiad rapidly in order to explain why divine power had withstood it. As Perry Miller writes, the jeremiad could make sense out of existence as long as adversity was to be overcome, but in the moment of victory it was confused. It flourished in dread of success; were reality ever to come up to its expectations, a new convention would be required, and this would presuppose a revolution in mind and society. 428 The language of chapters 8 and 32 of Deuteronomy indicates the concern of God with the external obedience of the entire covenanted community to His law-order. But the jeremiads focused in a pietistic fashion on the hearts of individuals, giving far less concern to the possi- bility of the external reform of society through specific acts of legisla- tion by a {158} Christian political order. The catalogue of external calamities and general sins was used, not to formulate formal legal codes, but to stir individual souls to repentance. Samuel Willard went so far as to deny that “general visitations” of God’s wrath necessarily imply “a general provocation” of God by the entire community. 429 The private deviation of a single individual, as in the case of Achan’s forbid- den theft (Josh. 7), can bring the wrath of God upon an entire popula- tion. Willard had reversed Cotton’s argument that a saving remnant can preserve an externally apostate society from ruin: a single apostate man can apparently bring down the pillars of an externally obedient society. The general rule is made up of particulars, so each man must search his heart, pray, and seek God’s will for his life. Besides, until your heart is pure, you need not seek for external causes of God’s anger. If taken seri- ously, this injunction would permanently bar the possibility of success- 427. Ibid., 4. Obviously, Mather saw limits on the possibilities for the peace- preserving effects of the presence of a remnant of saints within a society of pagans or apostates, a line of argument which had been pursued by his father-in-law, John Cotton, in The Way of Life. Neither man was willing to admit the possibility of perpetual toleration on the part of God out of respect for such a remnant. 428. Miller, Colony, 33. 429. Willard, Useful Instructions, 72. From Medieval Economics to Indecisive Pietism: 201 A Chalcedon Publication [] 3/30/07 ful external political action, since orthodox Puritan thought never abandoned the doctrine of total depravity, resisting until the end the inroads of perfectionism and antinomianism. The principle set forth by Willard could not have escaped his audience: “Particular repentance goes before general mercies....” 430 Why this concern with the personal soul to the exclusion of external reform? Because anything more than an examination of men’s hearts and a consideration of their activities in private associations (family, home, town) would lead to cries for political reform. Samuel Willard, in 1676, was not about to make an opening for that kind of activity. Some may object, he wrote, that external cursings come because of some sin by the rulers. “This objection is strange and impertinent....” 431 It is sim- ply a “hypothetical excuse” made by sinful men, “to put off the edge of the conviction of present sins....” What is needed is personal reform; on this point, the New England jeremiad was adamant. 432 Preachers used each calamity to demonstrate the displeasure of God at the failure of men to own the church covenant. But if social disasters could only prove the continuing failure of persons to fulfill their duties toward God, and if successes or blessings externally and collectively could not be used to demonstrate God’s favor toward such individual- istic responses, then collective, covenantal blessings as such were noth- ing more {159} than a theoretical backdrop—a kind of limiting concept—which could never be relied on as an earthly reality. External blessings might be promised in all good faith; all individuals had to do was “to choose life, to choose spiritual, temporal, and eternal life.... If you do thus choose life, all will be well with New England....” 433 But when blessings seemed to arrive, other explanations were invariably 430. Ibid., 73. 431. Ibid., 76. 432. Cf. I. Mather, Earnest Exhortation, 13; Oakes, Seasonable Discourse, 32. Perry Miller traces the internalization of the jeremiad from 1652 on, but primarily after 1660: Colony, 28. He probably overemphasizes the shift away from “calamity as a judgment” to “sinfulness as a curse” as the message of later ministers. They did not, as he argues, reduce social distresses “to mere footnotes.” Calamities were used continually throughout the second generation period to demonstrate God’s anger. Cf. Miller, “Declension in a Bible Commonwealth,” Nature’s Nation, 21ff. 433. Samuel Torrey, A Plea for the Life of Dying Religion (1683), 41. 202 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 found to justify them, since it was obvious to New England’s clergy that nothing like revival was happening in their churches. Church atten- dance was falling off throughout New England, and church member- ship was falling off within the narrowing circle of regular attenders. 434 Women had always outnumbered men in the pews, but now the pro- portion was growing steadily worse. 435 The responsibilities of member- ship no longer seemed worth the sacrifice to most people. They remained silent, and the messages of impending doom continued. The very structure of the jeremiad led to cultural pessimism. To admit collective success was to abandon the formula. Men like the Mathers, Willard, Oakes, William Adams, and the members of the Synod of 1679 were unwilling to abandon the inherited formula. The founders had held to the validity of a national covenant involving national responsibilities, curses, and blessings. 436 The leaders of the second generation had substituted for the national covenant and its externals a concern almost exclusively for the covenant between indi- viduals and their God within the institutional church. They chose to regard external, collective affairs as examples to be used exclusively for the purpose of calling individuals into the church covenant. The preceding analyses of the jeremiad as a factor in the seculariza- tion of New England is almost the reverse of Perry Miller’s evaluation. Miller argues, in the concluding paragraphs of his essay on “prepara- tion for salvation,” that the New England divines of the second genera- tion appealed to their unresponding listeners to begin the work of salvation by hearkening unto the message, singing hymns instead of useless songs, dressing modestly, and in other ways demonstrating their concern for God’s requirements. The preachers advised this kind 434. Carl Bridenbaugh writes: “A consideration of the number and seating capacities of village meeting houses and churches demonstrates the sheer physical impossibility of crowding the entire village populations into their houses of worship. At no time after 1650 does it seem possible for the churches of Boston to have contained anywhere near a majority of the inhabitants; in 1690 little more than a quarter of them could have attended church simultaneously had they been so disposed.” Bridenbaugh, Cities in the Wilderness, 106. 435. Morgan, “New England Puritanism: Another Approach,” William and Mary Quarterly, 3rd Ser., 18 (1961): 238. 436. Miller, The New England Mind: The Seventeenth Century, 475–76. From Medieval Economics to Indecisive Pietism: 203 A Chalcedon Publication [] 3/30/07 of autonomous activity on the part of the {160} unregenerate, says Miller, not as their fathers had done, in order to see souls saved, but in order to keep the commonwealth from declining into oblivion. Thus, Miller asserts, by opening up a zone of autonomous human action in the program of community restoration, the preachers of the second generation led the way for Franklin’s moralism. 437 Is this the case? The jeremiads were only peripherally concerned with “preparation” and extremely concerned with salvation itself. They called the saints to refrain from dressing like pagans before they called the pagans to respect inherited status distinctions in fashions. They called men to examine their hearts, to pray, to repent as individuals. Conversion of individuals would ultimately bring a transformation of society. The jeremiads were intended to transform a declining society, but not through external conformity to God’s civil law-order—a law- order whose specific economic applications had almost completely baf- fled the ministers—but rather through a pietistic, individualistic search- ing of souls. Miller would have us believe that secularism came to New England in part because the divines proposed a scheme of positive external reformation through men’s acceptance of the tasks of prepara- tion for salvation, a preparation which implied human autonomy pre- ceding God’s special grace. It would seem true that the ministers did further the secularization of the external political, social, and economic orders, but they did so through a program of pietistic default, rather than by any appeal to a positive human autonomy. The theological leaders of the second generation hoped for external covenantal bless- ings as a result of a pietistic regeneration of individual souls. Social 437. Miller, “‘Preparation for Salvation’ in Seventeenth-Century New England” (1943), in Nature’s Nation, 50–77, esp. 75–77. Mr. Jon Zens, in a detailed survey of the history of the doctrine of preparation for salvation, explores the ambivalent phrases of both English and New England Puritan divines of the first generation. He concludes: “They did not teach, as they are accused of doing, ‘meritorious preparation.’ ” As to the idea of human autonomy in the work of preparation, Zens is emphatic: “The Puritans stressed that in salvation God decrees the end, but in so doing also disposes the means ... to accomplish his purposes.” Zens, “Preparationism” (mimeographed), 9, 14. Zens makes it very clear that this concept of God’s means was held by Thomas Hooker, whose teachings on preparation are relied on heavily by Miller. 204 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 benefits would follow the conversion of discrete souls, not the autono- mous activities of morally discreet men. Miller’s argument rests on his forced de-emphasis of those constant warnings by the clergy that even the work of preparation is a gift of God. Miller was fair in his citations of such passages, but in his estima- tion, these qualifications did not really counterbalance the language of autonomy in the doctrine of preparation. The evidence points else- where. Secularization did not come through any suggestion by the clergy of the possibility of positive, autonomous, personal activities of men who are the recipients {161} of common grace; it came far more as a result of the clergy’s insistence that without individual, special grace in the hearts of men there could be no real possibility of reforming the external law-orders. It was the language of pietistic retreat rather than any language of positive external reform which gave the field to Frank- lin. Pietism and Social Pessimism The jeremiads constantly appealed to the civil magistrates to enforce both tables of the Mosaic law in order to preserve and/or restore Chris- tian society. Only after 1690 did leading Puritan divines officially acknowledge that religious toleration might be preferable to the imposi- tion of force by the state in order to preserve the Holy Commonwealth’s official commitment to the tenets of orthodox Protestantism, i.e., the first five commandments. The Mathers adopted this position in 1690, after decades of holding the doctrine of external compulsion. 438 In this sense, William Hubbard’s election sermon of 1676 stood out as an anomaly. 439 He counseled against excessive zeal in weeding out here- tics and apostates. Within four years of the delivery and publication of this sermon, the Massachusetts General Court followed Hubbard’s advice and repealed the laws against the Quakers. Nevertheless, the majority of the clergy continued to recommend spiritual conformity 438. Miller, Colony, 138ff. This liberalization of religion was a Massachusetts phenomenon. Connecticut lagged behind for at least another generation. Only in 1708 did pressure from England force the Connecticut Assembly to formally permit meetings of sober dissenters, and this privilege, according to Richard Bushman, was rarely granted. Bushman, From Puritan to Yankee (1967), 16. From Medieval Economics to Indecisive Pietism: 205 A Chalcedon Publication [] 3/30/07 through external compulsion. One of the marks of the fall from politi- cal influence of the clergy in Massachusetts after 1680 was their inabil- ity to convince the magistrates of the absolute necessity of suppressing theological deviation. In the realm of economics, the clergy were even less precise. What, exactly, was the civil magistrate supposed to legislate? Even if magis- trates had been willing to follow the lead of the theologians, they would have received very little assistance in resolving the complex problems of economics. The clergy, when it came to specifics, drew back rapidly. Even Increase Mather, whose constant meddling in the ecclesiastical affairs of {162} his fellow clerics earned him their hostility, 440 was will- ing to admit that in theory the ministers had sinned in their interfer- ence “in affairs not proper for us to engage in.” 441 They preached in general terms familiar to members of an organic commonwealth, but they laid down no legislative specifics for the cure of its economic devi- ations from that organic ideal. After 1680, as their influence waned in secular matters, the ministers showed no signs of abating in their intensity; having little responsibility for external affairs in the commu- nity, they apparently did not feel the need for tempering the language of critical outrage. 442 What would cure New England’s ills? William Hubbard’s answer was simple: charity. Charity would restore the world they had lost. It had conquered the wilderness before their day, fulfilling Isaiah 66; without 439. On Hubbard’s sermon, see Nelson, “King Philip’s War,” 615ff.; T. H. Breen, Character of the Good Ruler, 111ff.; Miller, Colony, 135–36. Increase Mather’s 1677 election sermon, A Discourse Concerning the Danger of Apostasy, had criticized the magistrates for having shown too much religious toleration. By 1690, Miller argues, both the Mathers had become advocates of toleration: Colony, 165. Breen, however, thinks that Cotton Mather’s sermon, The Serviceable Man (1690), was aimed at the proponents of toleration, and that it was only after Increase Mather returned to Massachusetts with a new charter requiring religious toleration that the younger Mather became a full advocate of toleration: Good Ruler, 200. In any case, by 1692, the Mathers were both religious tolerationists. 440. Clifford K. Shipton, “The New England Clergy of the ‘Glacial Age,’ ” Publications of the Colonial Society of Massachusetts 32 (1937): 30. 441. I. Mather, Earnest Exhortation, 13. 442. On the question of 1679–80 as the years marking the beginning of the decline of the clergy’s influence, see Shipton, “‘Glacial Age,’” 30, and Miller, Colony, 142. 206 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 charity there would be a return to the wilderness. Charity would serve as “a sovereign remedy against all our troubles.” 443 Heresies would be cured, debts paid, public charges defrayed. Charity never failed the early church; hell could not stamp out the little organization. While other ministers did not see charity as a total panacea, they did argue that voluntary giving would help to transform New England. Oakes blamed the people for showing so little charity. 444 Shepard warned that New England’s clergy were in need of charity, so that ministers would not be reduced to the status of begging friars. Relief should come “out of some public bank or stock for an honorable relief....” 445 But as to the actual percentage of income that should be given out, the ministers, as always, were vague. They were also vague as to who should be in charge of charities, whether some basic amount is mandatory, or whether the state or church should be the enforcing agency. Cotton Mather, in 1710, decided that the full 10 percent figure is required of men, but the jeremiads generally avoided such specific percentages. 446 In short, no concrete institutional proposals for the implementation of a new sys- tem of charity came in this period. The kingdom of God, which had served as a touchstone of optimism among members of the first generation, lost its optimistic definition in the second. The jeremiads pointed backward toward a golden age and forward to an almost inescapable declension of the commonwealth. The cultural pessimism of the majority of the jeremiads is striking. The exception is Jonathan Mitchel’s Nehemiah on the Wall. Mitchel pointed to Constantine’s {163} age as an archetype of Christianity’s triumph over the forces of evil in the social and religious realms. 447 God is hon- ored—will be honored— “when Zion is built up and restored from her captivity into a condition of welfare....” Such external victory is the ful- fillment of God’s prophecies and promises. It is therefore no carnal thing, but an holy duty to desire, and in our places to seek and endeavor the peace and tranquility of Israel, not for 443. Hubbard, Happiness, 60. 444. Oakes, Pleaded, 32. 445. Shepard, Eye-Salve, 47. 446. C. Mather, Bonifacius: An Essay Upon the Good ([1710] 1966), 108-9. 447. Mitchell, Nehemiah, 9. From Medieval Economics to Indecisive Pietism: 207 A Chalcedon Publication [] 3/30/07 low and sensual ends, but that God might have glory by his mercy to us, and by more abundant and fruitful service from us.... [In the case of physical sickness, God can be glorified, but we are to seek health: 8th commandment.] The same may be said of political health and welfare. God is to be submitted to, and glorified in affliction and trib- ulation,ified for it. 448 This is anything but a representative passage of the era. Samuel Sewall took seriously optimism such as Mitchel expressed, but clerics, in their published sermons, gave their audience little hope for an external, social triumph on earth and in time. 449 The great personal eschatological event of death began to replace the visible kingdom of God as the focus of Puritan sermons. 450 Another sign of change in perspective was the acceptance by the two Mathers of a premillennial eschatology. On numerous occasions, Increase outlined his expectations for New England. God is not yet fin- ished with New England; there is always great darkness before the dawn; a radical discontinuous event—the bodily return of Christ in power and glory to begin His earthly reign on earth—may be expected immediately after the {164} conversion of the Jews, which could take 448. Ibid., 9–10. 449. Sewall, poem for Wednesday, Jan. 1, 1701, in Meserole, 305-6. Cf. Letter Book of Samuel Sewall, reprinted in the Massachusetts Historical Society Collections, 6th ser., vol. 1 (1886), 177, 288, 325; ibid., vol. 2 (1888), 42. 450. Cf. John Norton, Three Choice and Profitable Sermons (1664), sermon 2, preached in 1663, 17: Christ promises to come for us at the point of death.... See also Gordon E. Geddes, “Welcome Joy: Death in Puritan New England, 16301730” (Ph.D. dissertation in history, University of California, Riverside, 1976). Writes Geddes: “These early visions of New England were built on an eschatology that focused on the final and communal triumph of Christ over death and on the consummation of the fullness of life in the completion of the church in Christ. But by the end of the century the goal of the city on the hill was abandoned. The world increasingly fell outside the realm of religious control, becoming either a weary place of pilgrimage or a beneficent system run by natural laws for the good of man. An individualized and spiritualized eschatology again predominated, and death became again the most important eschatological boundary.” From the intro., 14. 208 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 place at any time. 451 When he appealed to the younger generation to own the church covenant and assume their responsibilities, he was not encouraging them to begin any reconstruction of the Holy Common- wealth; he had abandoned any such hope. What external hopes could men legitimately have concerning the prospects of the expansion of God’s kingdom? Hubbard, in the midst of King Philip’s War, could offer only this to men: “... a quiet possession of what they already have, with the enlargement of their property, if attainable.” 452 Gone was the prospect of a final and successful confrontation with the Antichrist, the vision which had delighted Edward Johnson; the peaceable cultivation of one’s own garden was its psychological substitute. The jeremiad served as an instrument of per- sonal pietism and self-examination. Its appeal to examples of social or economic events was simply a means of stimulating personal repen- tance. Decline seemed inevitable to the authors of the jeremiads; for three decades the prophecies of doom persisted. But the prospects for the survival of New England kept getting better after 1690, if not on the terms of the Holy Commonwealth, then at least in terms of the expand- ing British Empire. A modification of the jeremiad was made increas- ingly necessary; the uncompromising severity of the written critiques of society could not be taken seriously by most citizens in the face of the continued success of the colonies. An other-worldliness became characteristic of Puritan sermons in the second generation. The clergy abandoned the idea of social reconstruc- tion through the application of concrete biblical laws to specific politi- cal and economic situations. Simultaneously, they abandoned eschatological hope for the community as an organism. The biblical image of the soldier dimmed; that other biblical image, the pilgrim, replaced it. A man should strive to attain inward peace, wrote Willard, by “living above the world, and keeping his heart disentangled, and his mind in heaven, in the midst of all outward occasions and urgency of business....” God calls a man “not to be of this world, but a pilgrim on 451. I. Mather, Greatest Sinners, 78–79, 83ff.; Earnest Exhortation, 26; Providence, 54ff.; Day of Trouble, 12, 20. His most comprehensive eschatological work was his first published book, The Mystery of Israel’s Salvation (1669). 452. Hubbard, Happiness, 28. From Medieval Economics to Indecisive Pietism: 209 A Chalcedon Publication [] 3/30/07 the earth, a citizen of heaven....” 453 Edward Johnson’s vision of an unconquerable army of Christian soldiers became, as was mentioned earlier, merely the promise of ultimate spiritual conquest for individual Christian soldiers, with no mention whatsoever of any army of saints. 454 Triumph is assured only on the final day of judgment; {165} presumably, one’s death serves as the gateway to triumph—victory beyond time and earth. The ministers warned against the overemphasis men place in their particular callings. “Farms and merchandizing have been preferred before the things of God,” warned the Boston Synod of 1679. 455 John Whiting followed this outline: “Be there never so much farming and merchandise, buying and selling, and gain got by it, it is not such wealth [that] can make us rich indeed, while the fear of God is want- ing.” 456 Both callings, the general (spiritual) and the particular (occu- pation), have to be respected. 457 Piety and faith have to be restored in the people; only then can externals be divinely blessed. The heart first, and then the civic body. 1675: The Turning Point The three-decade period between 1661 and 1690 is generally regarded by historians as the era in which the Massachusetts Bay the- ocracy declined from its position of political strength into a religiously fragmented, increasingly secular culture. These years brought on a series of crises that shook the foundations of the clerical influence in New England: the growth of the merchants as a political force; the res- toration of Charles II to the throne (and later, the accession of James II), which challenged colonial autonomy; a devastating Indian war; political divisions both in towns and at the level of the central govern- ments; the division of the common fields; the advent of the Andros regime and the revolution which followed; the establishment of a per- 453. Willard, The High Esteem Which God hath of the Death of his Saints (1683), 17. 454. Oakes, Unconquerable. See above, n. 384. 455. Synod, Necessity of Reformation, 7. 456. Whiting, The Way of Israel’s Welfare (1686), 8. This was a Hartford election sermon. 457. Crown and Glory, 12. 210 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 manent English bureaucracy to supervise the enforcement of the Navi- gation Acts; and, finally, the revocation of the charter in Massachusetts (and the granting of a desirable one to Connecticut). It was, certainly, a time of distress for those holding a social philosophy which empha- sized the desirability of gradual change, semipermanent status rank- ings, and an organic community of saints. From the Restoration through the mid-seventies, the king chose to allow his colonial servants a considerable degree of operational auton- omy, so long as formal allegiance was maintained. He did not see to it that his demands for a liberalization of laws restricting religious free- dom and limiting suffrage were actually obeyed; it took two decades for the Massachusetts legislature officially to impose this demand on their Puritan commonwealth, when the Quakers finally were acknowl- edged as citizens. The royal commission which arrived in the colonies in 1664 was snubbed. It was unable to impose the king’s desires respecting the conduct of all judicial proceedings in his name, the per- mitting of the Book of Common Prayer for religious {166} worship, and freemanship separated entirely from church membership. Two political factions formed in response to the king’s pressures. One faction, led by the clergy, did not favor cooperation; the other, which included the bulk of the merchants, favored greater cooperation. From 1665–1675, the clerical faction triumphed. This, at least, is the picture drawn by Professor Bailyn. 458 The franchise was too wide for the merchants to gain power; farmers whose small property holdings would not have qualified them for the franchise anywhere in Europe could vote in New England if they were church members. The mer- chants’ group remained partially disfranchised after the suffrage act of 1664, which imposed a religious qualification, but even had they all been able to vote, their overall voting weight in the community would not have altered the outcome. 459 But Bailyn’s distinctions may be too finely drawn, given the extent of intermarriage between merchant and 458. Michael Garibaldi Hall, Edward Randolph and the American Colonies, 1676– 1703 (1960), 17–18. 459. Bernard Bailyn, The New England Merchants in the Seventeenth Century, 159– 60. From Medieval Economics to Indecisive Pietism: 211 A Chalcedon Publication [] 3/30/07 clerical families. Colonial class distinctions were more amorphous than the following would indicate: Economically all-powerful, politically influential but circumscribed, the merchants—willingly or not—were prime movers in a gradual, subtle, but fundamental transformation of New England society. Their involvement in the world of Atlantic commerce committed them to interests and attitudes incompatible with life in the Bible Common- wealths. Most of them did not seek the destruction of the Puritan soci- ety; but they could not evade the fact that in many ways commercial success grew in inverse proportion to the social strength of Puritan- ism. 460 Thus the social distinctions derived from the early institutions of church and state were no longer effective among the majority of the merchants. This fact in itself constituted a threat to the guardians of the old order, for merchants were now in a position to challenge their authority. Though the merchants’ influence did not yet extend over the political system, it reached into those subtle, fundamental atti- tudes and assumptions which ultimately determine institutions. 461 Bailyn quite properly centers his attention on the merchants as agents of social change. Cosmopolitan, geared to the problems and opportuni- ties associated with change, impatient with restrictions on trade imposed by {167} king or theocracy, they sought to establish a zone of legitimacy for market operations, profits, and the trappings of prestige and authority that accompany success in socially beneficial spheres of a community. But they were not alone in their commitment to the bene- fits of market operations, nor were they always consistent supporters of the market. The expansion of market transactions permitted the greater specialization of professions, a point noted by Adam Smith a century later. 462 Men began to produce for the market, and as the num- ber of competitive buyers and sellers increased, the authorities found it 460. Ibid., 105. 461. Ibid., 139. The distinctions between the Puritan clergy and the Boston merchants should not be overemphasized, however. Stephen Foster, in his study of Puritan New England, remarks that “so far from being at odds, merchants, magistrates and ministers through family connections and intermarriages formed one thoroughly interlocked community.” Foster, Their Solitary Way, 120; cf. 182ff. Foster provides a summary of four of these family genealogies: 187–89. By 1700 in Boston this process of intermarriage was well advanced. 212 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 less necessary to supervise the activities of the economy. The last great outburst of intervention into the market by the political authorities came in 1675–76, during King Philip’s War, the great Indian uprising. The legal compilation of 1672 included the old 1651 statute enforc- ing differences of apparel on the two classes of men, i.e., those living above or below the “affluence line” or £200 of total assets. It also included a 1662 reaffirmation of the code: even tailors who made “upper-class” garments for children or servants dwelling with families that denied them such extravagance were to be admonished, then fined, along with the children or servants. Such a piece of legislation was necessary, the General Court explained (using the language of the jeremiads) because “excess in apparel amongst us [is] unbecoming a wilderness condition....” 463 Oppression by wage laborers resulted, the Court declared, in their winning the right of daily wine allowances; henceforth, such allow- ances were deemed illegal (except in cases of physical necessity). A 20- shilling fine was imposed on the offending laborers. 464 It is important to record that this legislation carefully avoided any detailed scheme of wages, hours, and conditions, unlike the legislation of the 1630s. It would seem to indicate an unwillingness on the part of the central gov- ernment to become embroiled in numerous, semipermanent wage dis- putes. Controls on production and export of goods were still in vogue in 1672. A temporary prohibition on the export of bread had been passed 462. Adam Smith, The Wealth of Nations, chap. 3. For a rather technical analysis of this concept of economic specialization and the limits of the market, as it relates to the formation of monopolies, see George J. Stigler, “The Division of Labor is Limited by the Extent of the Market,” Journal of Political Economy 59 (1951): 185–93. 463. The Colonial Laws of Massachusetts ([1672] 1887), 5–6; also included in Records of the Governor and Company of the Massachusetts Bay in New England, vol. 4, pt. 2, 41– 42. [Cited hereinafter as MCR.] Connecticut passed a law which was almost identical with the wording of the Massachusetts legislation, included as a section of Connecticut’s list of “Provoking Evils” that had supposedly brought on the Indian war. Operating in terms of a somewhat lower standard of living (presumably), Connecticut enforced a £150 “affluence line” rather than Massachusetts’ £200 limit: CCR, vol. 2, 283. The entire list of “Provoking Evils” appears on 280–83. 464. Colonial Laws, Supplements, [20]2. From Medieval Economics to Indecisive Pietism: 213 A Chalcedon Publication [] 3/30/07 in 1662, {168} due to a temporary scarcity. 465 Hide exports were once again forbidden in 1672, reaffirming an old 1646 law. Only licensed monopolists were permitted to ship out leather hides. 466 Unlicensed persons were prohibited from boiling, pickling, or packing sturgeon in 1673. 467 Connecticut had a law against idleness in 1672. 468 Tanning standards were set in Connecticut by statute. 469 Monopolies were declared illegal, except those patented by the magistrates. 470 Massachu- setts passed a detailed list of twenty-seven regulations to be met by ship captains regarding shipping and the employment of seamen. 471 A ten- year monopoly for the production of pitch, rosin, and turpentine (including an import monopoly) was granted to one group in 1671. 472 A 6 percent limit on interest was set in Connecticut; no one could be forced by a court of law to pay more than this, although if the debtor were willing to pay more it was legal. 473 Massachusetts, a bit more lib- eral, imposed a similar restriction at eight percent. 474 The usual laws against gaming, drunkenness, and the inspection of the taverns by tithingmen remained in force in all the Puritan colonies throughout the period. So did laws against the ubiquitous roaming pigs and cattle. (The amount of total space devoted to animals in both town and colony records sometimes gives the impression that they were more of a problem than deviant humans.) King Philip’s War saw the final outpouring of economic controls in the early colonial period. The jeremiads had warned the people against 465. MCR, vol. 4, pt. 2, 43. 466. Colonial Laws, Supplements, [20]5; MCR, vol. 4, pt. 2, 512. 467. Colonial Laws, Supplements, [20]9. 468. The Book of the General Laws of the People Within the Jurisdiction of Connecticut (1675), 30. A similar law was passed in Massachusetts: MCR, vol. 4, pt. 2 (1667), 394– 95. Men who fail to provide for their families or who “misspend what they earn” are to be accounted idle and are subject to assignment to the house of correction. 469. General Laws, 38. 470. Ibid., 52. 471. MCR, vol. 4, pt. 2 (1667), 389–91. 472. MCR, vol. 4, pt. 2, 499. 473. General Laws, 68. 474. Colonial Laws, 153; cf. 41, 43. 214 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 the terrors that the Lord had in store for the apostate, and finally the war came to justify the concern of the theologians. Increase Mather pressed the General Court to pass a list of “Provoking Evils” that had brought on the curse of war. The deputies accepted the advice almost immediately; the magistrates balked for a week until news of another major Indian victory arrived. Then they, too, affirmed the statement. 475 The prologue of the “Provoking Evils” acknowledged that the war was a punishment—fully deserved—of the sinful commonwealth. Continued warnings from God in the form of “many general (though lesser) judgments” {169} had been ignored. The magistrates and depu- ties then proposed a list of social reforms necessary to stay God’s wrath. Children were to be catechized more faithfully by the elders of the churches; they were to be encouraged to own the church covenant. Per- riwigs, long hair, and excess apparel must be eliminated from the com- monwealth. Quakers were once again singled out, after a decade of relative peace, as culprits. A £5 fine was imposed (or the house of cor- rection) on any person attending a Quaker meeting. (Naked breasts drew a 10s fine, 10 percent of the Quaker penalty, indicating Puritan priorities of 1675.) Disorderly youths in church, shameful tippling, vio- lations against the fifth commandment for showing “contempt for authority: civil, ecclesiastical, and domestical,” idleness, and economic oppression were to be dealt with by the proper authorities. Oppression in pricing drew the wrath of the General Court; double restitution of the amount of the overcharge, plus a fine to be imposed at the discre- tion of the court, were imposed. Complaints against artisans could be lodged as well as complaints against merchants. No mention was made, however, of inflated agricultural prices. 476 The key concern of the magistrates was shown the following year. Inhabitants of different counties were charging various prices for the same goods or services to the militia. 477 The answer to this problem, the General Court believed, was the passage of this enactment on May 3, 1676, the last time full-scale price controls were to be passed in New England until the advent of the Revolutionary War: 475. Nelson, “King Philip’s War,” 617. 476. Colonial Laws, Supplements, [2]32ff.; MCR, vol. 5, 59ff. Cf. CCR, vol. 2, 280–83. From Medieval Economics to Indecisive Pietism: 215 A Chalcedon Publication [] 3/30/07 It is ordered by this Court, that a committee shall be chosen in each county to examine the rates put up on all manner of things used or expended for the public, and to view the particular bills allowed by the militia of each town for expences, together, and so to regulate the whole, as to them shall seem most just and equal, whose act being by them given under their hands to the {170} treasurer, shall be a sufficient warrant for their allowance in payment of the county rate. 478 Richard Morris comments, “The act of 1675 for the reformation of ‘Provoking Evils’ marked the culmination of wage regulation in the pre-Revolutionary period.” 479 It also marked the demise of price con- trol in general. It was the end of sumptuary laws that tried to regulate dress or other status-oriented displays of wealth. 480 One last great attempt at controlling animal imports from other colonies was made when a tariff was passed in 1680, but even this was repealed within a few months. 481 Clearly, it was the end of an era. 477. The General Court stated that the goods and services are identical, wherever found. It operated in terms of the concept of intrinsic value, i.e., a rifle is a rifle, and therefore it is worth the same in all Massachusetts counties. Modern economic analysis can be dated from the 1870s, when the concept of intrinsic value was abandoned. The value of any good is dependent upon its supply and demand, which in turn are determined by location and timing. A rifle in Boston would not be worth as much as a rifle on some frontier community threatened by imminent attack. Cf. Gary North, “The Fallacy of ‘Intrinsic Value,’ ” Freeman (June 1969), reprinted in North, An Introduction to Christian Economics (1973), chap. 7. 478. Colonial Laws, Supplements, [2]48a; MCR, vol. 5, 79. A similar law was enacted in Connecticut in the same month: CCR, vol. 5, iv-v; a 33 percent profit maximum was established. 479. Morris, Government and Labor in Early America, 77. 480. Miller, Colony, 50. If liquor controls are subsumed under the classification of sumptuary laws, then sumptuary laws did continue beyond 1675. Not, however, the fashion category of these laws. 481. MCR, vol. 5, 292. 216 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Other manifestations of altered attitudes appeared at this time. Con- trols restricting the purchase of land by strangers in the isolated com- munity of Dedham were effectively removed. 482 Communal recitations replaced the personal relations of prospective church members after 1675, reducing some of the psychological (and social) disadvantages involved. 483 The Connecticut probate records indicate that the hereto- fore almost universal entry of the makers of last testaments, the bequeathing of the soul to God, virtually disappeared after 1675. 484 It had been a practice recommended by pastors, yet it disappeared. 485 Aletha Gilsdorf ’s study of seventeenth-century Puritan eschatology in America concludes that after 1676 a realization came upon ministers that the errand into the wilderness had in some way failed. An eschato- logical pessimism had set in at least by this time. 486 The clergy had made the call to reformation its communal rallying cry during the war. 487 The war was won by the colonial forces. Victory was a difficult prospect for writers of the jeremiads to deal with successfully; the appeal of the rallying cry wore off rapidly. The Indian war had brought serious dislocations to New England society. Families were displaced, whole towns destroyed, and New England {171} experienced the worst death toll, proportional to total population, that has ever been sustained in a war fought by Ameri- cans. 488 Bands of soldiers had traveled through communities distant from their own, and they brought new ideas with them when they came and took new ones with them when they left. Leach has written that “King Philip’s War put an abrupt end to this youthful period of colonial history, for the severe losses suffered by the colonies shook 482. Lockridge, Town, 84. 483. Miller, Colony, 116. 484. Charles William Manwaring, ed., A Digest of Early Connecticut Probate Records, 3 vols. (1904), vol. 1, 150ff. 485. Cf. Norton, Profitable Sermons, 17. 486. Aletha Joy Gilsdorf, “The Puritan Apocalypse: New England Eschatology in the Seventeenth Century” (Ph.D. dissertation, Yale, 1965), 157ff. I would say that pessimism set in at least a decade and a half earlier. 487. Douglas Edward Leach, Flintlock and Tomahawk (1958), 193. 488. Ibid., 243. From Medieval Economics to Indecisive Pietism: 217 A Chalcedon Publication [] 3/30/07 their confidence, weakened their twin structures of church and state, and developed internal strains which were the unmistakable signs of a newer and more diversified order yet to come.... The old Puritan hopes of a true wilderness Zion were dead even in the very moment of vic- tory.” 489 The next fifteen years saw the imposition of English customs agents, the end of the religious requirement for the suffrage, the revocation of the Massachusetts charter—the great national covenant with God—in 1684, a papist sovereign on the throne the next year, the coming of Andros and the implied threat against landed property (it was more a threat than a reality 490 ) a political revolution, and the final humiliation (for Massachusetts) in 1690: the inability of the various factions to cre- ate political stability, necessitating a call to the new king to command respect and to force the recalcitrant population to pay its taxes. 491 Fac- tionalism, without the unifying presence of a personal sovereign, threatened to paralyze the Bay Colony. The new charter of 1691 removed the right of electing a governor from the people of the state and transferred it to the king. The locus of political activity immedi- ately shifted to the legislature, and this in turn meant that the struggle for power would take place in the towns, since a town residence requirement for House members was established (at the time a revolu- tionary proposal: it abolished “virtual” representation). 492 489. Ibid., 250. 490. Hall, 102ff. 491. Ibid., 125ff. 492. Michael Zuckerman, Peaceable Kingdoms (1970), 18ff., 32–33, 120ff. The law prohibiting virtual representation in the Massachusetts legislature was the outcome of a political impasse between Governor Phips and the “old charter” faction led by Elisha Cooke. Cooke’s anti-Mather, anti-Phips group continued to send their own members, all of whom were residents of Boston’s South End, as delegates of other Massachusetts towns. Phips refused to administer the oath of allegiance to these delegates. The Cooke faction would then disrupt the House, whereupon Phips would dissolve it. This happened twice in 1693. Phips, understandably, attempted to pressure the House into accepting a residence requirement resolution. In retaliation, Cooke’s forces were able to cut off Increase Mather’s salary as president of Harvard College unless he were willing to move to Cambridge. Finally, in the third House of 1693, the residence requirement was voted into law by the narrow margin of 26 to 24. On these early factional disputes, see G. B. Warden, Boston, 1689–1776 (1970), 45–46. 218 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Added to the political instability were monetary instability and price {172} inflation. Several bank schemes were put forward, a few were tried, and all failed. Legislative fiat was imposed to stabilize exchange rates between local currency and foreign; each time Gresham’s Law went into effect, as the artificially overvalued currency was used by everyone for most purchases, while the artificially undervalued cur- rency went into hoards or across the ocean to settle debts. Finally, the colony began in 1690 an emission of paper bills, which were depreciated in exchange by Massachusetts citizens almost the moment they went into circulation. 493 No reasonable long-run solution seemed imminent. The clerics were as baffled as the merchants as to what ought to be done. Conclusion Nothing seemed to go right for clerics in these years. The jeremiads failed to stimulate the sons and daughters of church members to join the churches, even after the churches had practically torn themselves apart with strife over the halfway covenant in order to make it easier for the covenant line in each family to continue. 494 Church attendance was falling throughout the period. Political life gave every sign of that terrible evil, faction. Pessimism was the order of the day, if the jeremi- ads are to be regarded as accurate reflections of public opinion. After 1680, the only sign of brightness belonged to the merchants: the decade of 1680–90 was one of the most remarkable periods in American his- tory in terms of commercial expansion, despite political turmoil and monetary instability. 495 That gave little comfort to conservative clerics, especially those outside of Boston whose incomes would not have reflected the new prosperity so rapidly. The familiar economic guidelines of a medieval commonwealth— the just price, fair dealing, recognizable status-oriented fashions, export controls—were familiar in name only by 1680. The first genera- 493. Bailyn, 102ff.; E. A. J. Johnson, American Economic Thought in the Seventeenth Century, chap. 9; William B. Weeden, Economic and Social History of New England, vol. 1, 325ff. 494. Morgan, Puritan Family, chap. 7. 495. Weeden, vol. 1, 353. From Medieval Economics to Indecisive Pietism: 219 A Chalcedon Publication [] 3/30/07 tion had found such controls on the voluntary exercise of property rights to be irregularly applied and almost impossible to enforce. By 1660, the specific applications of such medieval controls were conspicu- ously absent from Puritan sermons. The existence of such guidelines was insisted upon as a theological and moral necessity; Christian soci- ety was still inconceivable apart from them. But the search for practical applications was no longer seriously being attempted, by either the clergy or the colonial legislatures. Those who found it profitable to par- ticipate freely in a generally open market were thus at liberty to do so. The fact that increasing numbers of citizens and {173} church mem- bers were actually doing so appalled the clergy, but they were defini- tionally and institutionally impotent to do very much about it, except in a period of great emergency. As Tawney comments with regard to sixteenth-century prohibitions on usury, “No church has ever experi- enced any difficulty in preaching righteousness in general: no church has found a specific to disguise the unpalatableness of righteousness in particular.” 496 The jeremiads could only condemn the excesses associ- ated with the uncontrolled use of private property; unrighteousness in general was opposed, but the clergy forfeited the right of defining the specifics to others. 497 But no others appeared on the scene to take the responsibility of defining the operational limits of a medieval com- monwealth. It is unlikely that any group could have imposed such a vision on the New England colonies in the final quarter of the seven- teenth century. For half a century, from 1630 to 1680, the New England clergy had built up a paradigm of economic justice, but they were unable to trans- late the language of conscience into the language of formal law. Without such an operational framework for economic restraint or reform, it became impossible for the clergy to maintain effective political control over the external realm of economics, or even in their own congrega- 496. R. H. Tawney, “Introduction,” Thomas Wilson, Discourse on Usury (1935), 114. 497. Abraham Kaplan’s comment is relevant on this failure of Puritan leaders to provide concrete economic recommendations for the preservation of the received doctrine of the Holy Commonwealth: “What is objectionable in a verbalistic morality is that its symbols function not as ideals but as utopias. They do not guide moral action, but substitute for it.” Cited by David Hawke, A Transaction of Free Men: The Birth and Course of the Declaration of Independence (1966), 244. 220 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 tions. It was not long before new theories were offered as substitutes for the dead language of a medieval universe. There had been enormous economic progress during the era of the second generation in New England. A new culture had been con- structed, and Boston became a part of the whole transatlantic trade system of Europe. But the progress in economic growth was less and less the product of a uniquely Puritan theology. More and more, eco- nomic affairs were seen as autonomous, and few business leaders or legislators in 1690 would have taken seriously the inherited medieval economic casuistry that the first generation had brought with them from England. The ethical framework for each individual’s moral actions was unquestionably Christian, but outside the church and fam- ily, Puritanism had lost its position of leadership. 498 The secularization of the economic realm had begun. The economic capital that had been created by the hard work and sharp trading of the first generation became the foundation of a distinctly less Puritan New England. The old vision of the holy commonwealth could not {174} endure intact. An intellectual transformation preceded the economic transformation. Puritanism constructed a social framework which encouraged progress, and progress created rapid social change that the old medi- eval categories simply could not deal with successfully. The jeremiads of crisis demonstrated an unforeseen reality: nothing fails like success. The new wine of economic growth could not be contained by the old wineskins of medieval guild socialism. 498. Shipton, “ ‘Glacial Age,’ ” 46. A Chalcedon Publication [] 3/30/07 A NEO-PURITAN CRITIC REPLIES [The following is the only letter this Journal has received to date which is critical of vol. 5, no. 2, “Symposium on Puritanism and Law.” The author is apparently not writing with respect to the Journal itself, but with respect to the flyer which Chalcedon sent out promoting this issue. We print it verbatim and without comment, except to express the hope that some of the author’s misgivings will be alleviated by R. J. Rushdoony’s essay in this present issue. The Journal welcomes interaction with its essays.] March 22, 1979 To: Symposium on Puritanism and Law The Journal of Christian Reconstruction My name is ____ . I read the Puritans, published by Banner of Truth Trust. I have just read your short paper on why one must read all of Puritan literature and thus gain an accurate assessment on a world and life view. I write this short letter to you, to rebuke you for your err: but a rebuke which, I hope would be in the proper spirit and which has as its end, repentance and restoration unto full communion with Jesus Christ. May Jesus the Lord grant me wisdom to expose your error, the wisdom that leads and freely gives men salvation and not mere intellec- tual wisdom which I believe you are wrapped up in without proper sanctification. From reading your paper (vol. 5, no. 2) what I perceive is that you are against making the whole Christian life and the whole writings of the Puritans center on the issues of sin and grace. You want to invade all areas of life and redeem these areas for Christ Jesus. You want to extent Gospel wisdom and sanctification to every area of life, and that, so as to bring all areas, spheres, everything unto a new and holy thing. You do not want to be merely confined in your Christian experience to be always caught up in wrestling and striving against sin. (I want to be very careful not to judge you. I am stating what I, as a Christian, think of your attitudes.) You do not want to always have your horizons fixed on just {176} “salvation” consisting always in witnessing, the local 222 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 church, and the concept of believers always being separated from the world, and only speaking out in the world when some sin is brought down: like homosexuality. You want to pervade the society with posi- tive notes, and especially with the concept of redeeming this or that area for Christ and not just always talking about sin and grace, hell and heaven and salvation. Well enough with this description. I believe this is your sinful hangup; although I am not judging your mind. I want to be free from that sin. To rebuttal you in the Biblical sense I would first off call to your attention the express purpose for which Christ came to earth: to save sinners. To save “people” not areas, spheres, non-personal entitites such as: economics, science, merchants, politics. Jesus has not as His aim to sanctify areas, spheres, etc. To save people from their sins—Matt. 1:21. Not to reconstruct areas of peoples lives; but to transform sinners into non-sinners. This is the aim of Christ, and you do not seem to be one with Him in it!!! That means you are anti-Christ. Now, if you would think immediately of Genesis 1–3 and the cultural mandate, that Christ wants to redeem man and put him back into the world which God created and thus see man fulfilling all his world and life functions as God originally created him for—this still is erro- nanous. Certainly, sinless Adam would have reached out into all spheres and areas of life: economics, politics, science: and done this holy and righteously unto God, but: this would not have been the aim, goal, pursuit, of Adam but rather the secondary consequences of abso- lute holiness. You see it is not Christs goal to redeem areas of econom- ics, politics, this is rather a result of an efficient cause. This world is going to burn up, 2 Peter 3, redeeming areas is not the goal of Chris- tianity—its redeeming people! Jude vs. 23 “and some save, snatching them out of the fire.” People not things is the goal of redemption. I would urge you to leave off this Satanic pursuit of yours. You stand against Christ if you oppose dealing with the great issues of sin and grace. Paul determined to know nothing save Jesus Christ and him cruci- fied. This is God’s concern, if it is not yours; then you better do some self-examination as to your salvation. A Chalcedon Publication [] 3/30/07 2. DEFENDERS OF THE FAITH A Chalcedon Publication [] 3/30/07 OLIVER CROMWELL (1599–1658) Judy Ishkanian There are some events in history that are so pivotal for the future that we tend to take them for granted. The English Revolution was such an event. The true significance of the English Civil Wars, 1641–49, and the years of the Commonwealth, 1649–60, escaped partisans on both sides. The restoration of the monarchy was viewed by most as a total defeat of the goals of Puritanism and republicanism. Yet it is difficult to imagine today’s English-speaking world without the central impor- tance of constitutional government, its industrialized economy, or its dominant middle class. We owe this basic framework to the flowering of the Reformation in England and Scotland, and to the unique outlet that Calvinism stamped on the English mind. The English Civil Wars, the execution of a king of England, and the years of the Common- wealth and the Protectorate, occurred in a very short period of time, but were the result of one hundred years of historical development. None of these events would have come to pass in quite the same way without Oliver Cromwell. That this unpretentious country gentleman should rise to rule England is a source of amazement, for his entire military and civil career spanned only fourteen years. This military leader, who is rou- tinely compared to Caesar or Napoleon for strategical brilliance on the battlefield, had never seen a battle nor led a troop until he was forty- three years old. While serving his initial terms in Parliament, he was eclipsed by his illustrious cousins and more experienced politicians. Nevertheless, Oliver Cromwell rose to be the greatest Puritan states- man the seventeenth century produced in England. A man perhaps too partisan to his God, His cause, His people to be beloved by all English- men, either then or now, he is acknowledged by all to have brought order out of chaos and to have set a decaying island kingdom on a path of greatness and international respect that was to the benefit of the Oliver Cromwell (1599–1658) 225 A Chalcedon Publication [] 3/30/07 entire nation. Who, in retrospect, can deny the effects of the doctrine of special election which Oliver Cromwell believed called him into God’s service, or to his indomitable belief in the divine Providence which would guide him to the victory of His cause? Perhaps that is why this militaristic, partisan, passionate, devout Puritan has earned the title historian Christopher Hill has given him: “God’s Englishman.” General Background The fortunes of the Cromwell family were tied to those of the Tudor monarchs. The Cromwell patronage was based on the dispersal of Catholic {178} landholdings after Henry VIII broke with the Vatican to create a national church. They were, thus, members of a rising Protes- tant aristocracy. While the politically motivated Protestantism of Henry VIII produced an independent, national church, the printed English translation of the Bible eventually gave England Puritanism, since conformity to the Word of God was increasingly demanded. In the north, the intrepid theological child of Calvin, John Knox, was forging the structure of Scottish Presbyterianism in the midst of a traditionally violent and unruly government. Due, in large part, to his forceful leadership, Presbyterianism became the national church of Scotland, and the dominant voice in Scottish politics. It was a voice the volatile Stuart rulers came to fear and detest. In milder climes to the south, Queen Elizabeth had never relinquished control of the official Anglican Church, and had kept a watchful eye on religious enthusi- asms of all persuasions. Unofficial Calvinism grew and flourished in Elizabethan England despite general repression and spasmodic periods of persecution, and whole sections of the country became known as “Puritan.” Restive though Parliaments were at the close of the sixteenth century, Elizabeth and her Privy Council had retained her father’s absolute monarchy. With Elizabeth’s death in 1603, James VI of Scotland succeeded the Spinster Queen to become James I of England. The country rejoiced to have what appeared to be a vigorous family man on the throne. He had been taught by the famous Puritan Buchanan, and the religious people in the land held high hopes that at last they had a kindred spirit at the helm. They were soon relieved of their illusions, for James I proved himself to be, in the words of historian Esme Wingfield-Stratford, “a 226 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 buffoon in purple.” 499 Avenging his lean years as captive king of the Presbyterian Kirk, James I and his Catholic wife plundered the fat English treasury. The modicum of statesmanship provided by the Eliz- abethan Privy Council was replaced with diplomacy by James’s bisex- ual courtesans. He set himself on a nonconciliatory course with his Parliaments that was to seal the doom of his son and successor, Charles I. The Stuart kings’ claim of “divine right of kings” to be above the law could not have been more ill-timed, considering the budding constitu- tionalism of increasingly Puritan influenced Parliaments. Charles I, with a Catholic wife of his own, ascended the throne. With Charles, England continued to be ruled by the petty intrigue of courtiers in both domestic and foreign affairs. At the same time, his assembled Parlia- ments were demanding that their authority be extended to all taxation, lawmaking, foreign affairs, and the control of the king’s advisors. An impasse was reached in 1628, when Parliament refused {179} to finance and implement Charles’s foreign policy. When it became apparent that none of the successively assembled Parliaments would accommodate his schemes, he purposed to govern England without calling any more into session. This he managed to do for eleven sullen, seething years, with his rationale of “divine right of kings” to place him above the law of the land. Early Life A return to the turn of the century finds Oliver Cromwell entering the scene in 1599 at the twilight of Elizabeth’s long reign. His father, Robert Cromwell, was the second son of the heir to the Cromwell for- tune, and as the second son of “The Golden Knight of Hinchinbrooke,” he was settled in the less spectacular, yet substantial, landholding at Huntingdon in East Anglia. Here, among seven sisters, Oliver Crom- well grew to fit the position of country gentleman, which he was des- tined by birth to fill. His parents were dedicated Puritans, and it is said that his mother, Elizabeth Steward, exerted a profound influence on him all her long life. Years later, in the public eye of the Protectorate, she was known and respected for her quiet wisdom. Beyond his home, 499. Esme Wingfield-Stratford, The History of British Civilization (New York: Harcourt, Brace & Co., 1948), 469. Oliver Cromwell (1599–1658) 227 A Chalcedon Publication [] 3/30/07 the single greatest influence in his youth was Dr. Thomas Beard, under whom he sat for the entire tenure of grammar school. This fiery and zealous Puritan schoolmaster was also his pastor and family friend. It is impossible to imagine that Oliver had not read and absorbed his teacher’s widely circulated book, The Theatre of God’s Judgements, the thesis of which was that God actively intervenes in the affairs of men in this life, and no person is too great or too small to escape God’s judg- ment, or violate God’s law with impunity. In direct contradiction to the theory of “divine right of kings,” Beard stated that princes are subject to God’s law. At age seventeen Cromwell left home to attend Cambridge Univer- sity at the Puritan college of Sussex, although the death of his father necessitated his return home a year later. It is speculated that the fol- lowing three years were spent in London at an Inn of Court (Lincoln Inn), where youthful gentry commonly attended to a mastery of legal matters important to landowners. A firm record exists of his marriage in London to Elizabeth Bourchier, daughter of a successful merchant, in 1620. Theirs was a stable and enduring marriage which produced eight children, and she shared with him all the blessings of smiling Providence, as well as the vicissitudes of war and the invective of Oliver’s enemies. When raised to prominence along with Oliver, her frugality and preference for hearth and home won her ridicule in fop- pish royalist circles, whose appreciation for Puritan virtues was notably lacking. Unfortunately for the reputation of “Protectress Joan,” as they sneeringly called her, their trivial, chiding remarks have survived the centuries. {180} With the exception of a few political encounters, the life of Oliver Cromwell was, until 1640, occupied with family pleasures and personal pursuits. The year 1628, however, occupies a particular interest because it marks the first time he was elected to Parliament. He was witness, then, to all of the dramatic events that led to the dissolution of Parlia- ment for eleven years. 1628 is also the date historians attach to the dra- matic spiritual conversion, where the Puritan doctrine of his upbringing welded with a quickening of his own heart and soul. From that time forward, his correspondence indicates a concern for doctrine and for matters of the faith that was to be the guiding force in his life for the rest of his days. His fascination with the New England Colonies 228 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 prompted him to consider emigrating there during the frustrating thir- ties, and he came so close that he sold all his property. Many have been tempted to speculate on the course of events had Oliver Cromwell joined his brethren in New England. The Civil Wars The Calvinist cause proved itself to be far from dead when, in 1638, Charles’s Archbishop Laud attempted to force the Episcopal Book of Common Prayer on the stern Scottish Kirk. The move by Charles dem- onstrates three generations of Stuart misunderstanding of Scottish Presbyterianism, with its jealously guarded religious integrity. Instead of handling the tinderbox situation with tact, Charles provided the spark which was destined to consume him by taking arms against the Scots. Despite the initial bravado, the end of the “Bishop’s Wars” found the king with 25,000 Scottish soldiers occupying the northern part of England with a demand for £12,000 a month subsidy pending a final settlement. Charles, his options gone, was forced to call another Parlia- ment to meet the financial demands. Oliver Cromwell had been elected to serve in the Short Parliament from the borough of Cambridge, and was elected again to the “Long Parliament” which convened on November 3, 1640. The spirit of deter- mined unanimity that prevailed at the first session of the Long Parlia- ment was not to be seen again for many years. That spirit produced dramatic reforms which many felt satisfied demands for the restoration of the ancient balance of government. Under the leadership of John Pym, the Triennial Act was passed, which insured that Parliament would meet on a regular basis, and Parliament passed another bill that it could not be dissolved against its own will. All prerogative courts were abolished, such as the Star Chamber and the High Commission, which had been a source of religious and political persecution since Elizabethan times. All existing taxes initiated outside the authority of Parliament were swept away. The precipitous event of a violent Catholic insurrection in Ireland prompted Parliament narrowly to pass “The Grand Remonstrance,” which {181} not only elaborated its position against raising arms against Ireland, but underscored its grievances with the Stuart rule and put forward even bolder attacks on royal sovereignty than had yet been Oliver Cromwell (1599–1658) 229 A Chalcedon Publication [] 3/30/07 seen. Cromwell, still not prominent in Parliament, but active in gaining valuable experience in serving on committees behind the scenes, stood foursquare in support of “The Grand Remonstrance,” but its uncom- promising tone divided the loyalties of members of Parliament. Given Parliament’s increased defiance, the king demanded the arrest of five parliamentary members (known thereafter as the Five Members, and included Pym and Cromwell’s cousin, John Hampden). King Charles himself arrived at Parliament with 100 soldiers to make the arrest, only to find that the Five Members had lost themselves in the safety of Par- liament’s stronghold city of London. This display of force caused the House of Lords to turn against the king, and to avoid retaliation he sought refuge at Hampton Court. The following months witnessed propaganda efforts of both sides, accompanied by the kind of preparations which foretell war. Finally, on August 22, 1642, King Charles raised his standard at Nottingham, and the English Civil War began. Undoubtedly, many at the time viewed the outbreak of war as a struggle for power between divergent political forces, and they aligned themselves according to their interests and sympathies. The Presbyteri- ans were seasoned veterans of political battles with royalty—particu- larly Stuart royalty—and there were among them sophisticated politicians and lawyers who were prominent in Parliament. Their hard- headed demand for the replacement of Episcopalianism with Presbyte- rianism as the national religion could point to Scotland as a successful example and could not have failed to appeal to many English Calvin- ists. Oliver Cromwell numbered among the thousands of Puritans who had never known an official “Calvinist” church affiliation. Puritans, variously identified as the Independents, the “Gathered Churches,” the Sectarians, or the Separatists, had learned their doctrine from the Geneva Bible in their homes from parents, under teachers, with after- noon lecturers, and home Bible study groups. They were advocates of religious tolerance for all orthodox sects and no national church. Theirs was a view of spiritual unity among believers rather than the organic, physical unity other religious groups sought. Their initial political naiveté came not from pietism (which infected Puritanism decades later), but from a lack of opportunity for practical expression of their Calvinistic ideas (unlike their brethren in the Colonies). As the 230 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Civil War progressed, the Independents were to be found as well repre- sented on the battlefield as the Presbyterians were in Parliament. How- ever others might view the challenge of war, the Puritans did, with one heart, regard it as a signal from God that at last He was going to advance His kingdom on earth. The Lord was calling His own servants into battle to subdue and overcome the {182} Antichrist, whom Puri- tans on both sides of the Atlantic believed was either Charles I or Arch- bishop Laud. At last, the great war of faith raging on the continent (the Thirty Years War), which they had viewed from afar for so many years, was coming to English soil. Whatever the commitment of others, there was no hesitation on the part of Puritans, with Cromwell resolutely in their number, to answer the momentous opportunity that God was providing His own elect to bring righteous government to England. At the outset of the Civil War, it became clear that this was no “busi- ness as usual” affair in Cromwell’s estimation. His daring innovations demonstrated his reliance on God’s special direction and leadership for victory. From the recruitment of his first troop of horse at Huntingdon, Captain Cromwell selected his cavalrymen on the basis of their spiri- tual qualifications: “honest men,” “godly men,” “men of spirit,” he called them. Tossing aside the timid euphemisms of other parliamentary leaders, he stood squarely before his men and, as one soldier recalled, “promised to stand with us for the liberty of the gospel and the laws of the land.” 500 After the first battle of Edgehill in October 1642, Crom- well became certain that his method of recruitment was superior to that of the major portion of parliamentary forces and attempted to convince John Hampden, who thought his ideas were unrealistic: Your troopers [wrote Cromwell] are most of them old decayed serving men and tapsters and such kind of fellows ... and their troopers are gentlemen’s sons, younger sons, persons of quality.... you must get men of a spirit ... that is likely to go as far as a gentleman will go or else I am sure you will be beaten still. 501 Unrealistic or not, Cromwell’s “honest men” were proving them- selves worthy in battle, and by 1643 Cromwell was promoted to Lieu- tenant-General of the Eastern Association, which he had helped to 500. Roger Howell, Cromwell (Boston: Little, Brown & Co., 1977), 42. 501. Ibid., 45. Oliver Cromwell (1599–1658) 231 A Chalcedon Publication [] 3/30/07 organize, under the earl of Manchester. Discipline was loose in both the royalist and parliamentary armies, and so the discipline and drill to which Cromwell’s “men of spirit” subjected themselves was all the more remarkable. Cromwell had insisted upon and received from Par- liament the promise of regular pay for all the soldiers under his com- mand, and ample provisions. While a measure of this sort seems an elementary aspect of a soldier’s morale, in the seventeenth century no armies received pay on a regular monthly basis. Their reward for vic- tory in battle was to plunder the enemies’ baggage and supplies, the nearby town, or resort to the comforts of the camp followers. Crom- well’s men were permitted none of these incentives and were disci- plined for lapses in personal behavior or desertion. Therefore, regular pay and good provisions were an essential component {183} of Crom- well’s strategy for high morale as well as for the obvious benefits in public relations. By 1644, Cromwell commanded a regiment of fourteen troops. His officers were chosen for their proven ability, their commitment to the cause, and their spiritual integrity. It was becoming apparent to other Parliament and military leaders that Cromwell was developing a huge Independent Church-in-Arms—a fighting church in a Holy War— which they saw, perhaps far more clearly than Cromwell at that point, did portend to become genuinely subversive to the existing social order. So ingrained in the modern American mentality is the old Puri- tan idea of advancement by merit, that it is difficult to comprehend that the world, both then and now, has largely been ruled by a rigid class system in which neither individual merit nor personal integrity have been factors for consideration. Actually, within Cromwell’s “con- gregation-in-arms” an aristocracy of its own was developing which was to confound the social expectations of the day. It was an aristocracy of the spirit which transcended all distinctions of class or rank and saw men of humble origins allowed to rise as far as their ability and com- mitment would permit. The “saints” clamored to be in Cromwell’s ser- vice, and men of “quality” preferred to serve elsewhere. The devotion between Cromwell and his men developed far beyond expected limits and reflected the relationship of a pastor to his parish. Although he retained his membership in Parliament throughout the war, and served, after 1644, on the Committee of Both Kingdoms, his sym- 232 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 pathies were repeatedly with the army. The fellowship with his own troops undoubtedly influenced his view that the army was more representative of the concerns of God’s people than was Parliament. The discipline and morale of his troops made possible Cromwell’s greatest innovative field tactic of recharging after the initial cavalry charge. Prince Rupert, Cromwell’s prime adversary in the field, received his experience in the continental war and repeated the tradi- tional use of cavalry. The dashing nephew of Charles I would stage his advance at full gallop and cut a swath through enemy lines. Win or lose, the control would be lost after the initial pass, and his cavalry would gallop off in anticipation of plunder or escape. Cromwell was able to make greater use of his troops in every battle because of his abil- ity to hold his horse in tight control. Instead of charging at a gallop, he charged at full trot. Whatever the outcome of the initial charge, his men turned, regrouped, and awaited orders, so that whether they recharged to gain victory or retreated, they were in formation and in communication with their commander. With the enemy’s horse off the field after the initial pass, they could, thereafter, turn to the heart of the enemy’s defenses. Victory after victory rewarded their devotion to drill and discipline, and reinforced their spirit of invincibility, which came to be shared by the enemy. The great Prince Rupert himself, {184} after the decisive victory of Marston Moor, nicknamed Oliver, “Ironsides.” Later the apt nickname was extended to include his soldiers as their reputation became a terror to all. The first two years of the war saw Cromwell gain valuable military experience and rise to importance as a political voice in Parliament. Despite its scattered victories, the outlook for Parliament’s forces gen- erally, however, was not good. Time had been considered to be on the side of Parliament, with the richest counties under its control. The fleet had declared for Parliament, thus rendering the seas more secure from the threat of foreign aid to the king. Nevertheless, royalist forces made impressive gains in 1643. Parliament’s great Sir Thomas Fairfax and his father were isolated in the north, blocking the Great North Road and preventing the earl of Newcastle and his private regiment of “White- coats” from aiding royalist allies in the south. Sir Ralph Hopton had, after many smaller victories, annihilated the army of the Western Asso- ciation under General Waller at Roundway Down. It was this crisis Oliver Cromwell (1599–1658) 233 A Chalcedon Publication [] 3/30/07 which prompted the dying Pym to negotiate the Scots into the field. The deaths of the two leaders, John Pym and John Hampden, in 1643, were a blow to the morale of the Puritans. The dedicated fighting spirit exemplified by Cromwell in the Eastern Association was being undone by the dilatory posture of his immediate superior, the earl of Manches- ter, as well as the commander-in-chief, the earl of Essex. This “no-win” policy of the parliamentary generals echoed the equivocal sentiment of factions in both houses of Parliament. Cromwell became the chief spokesman for a speedy and victorious conclusion to the war. As such, he was at odds with generals with such a vested interest in the existing system that they were as alarmed at the implications of the emerging Independency as a sociopolitical force as they were of the enemy in the field. Historian R. S. Paul notes that Oliver Cromwell had become “the acknowledged hero of the sects,” 502 and his partisan militancy was shrewdly watched by politicians who, nonetheless, regarded his ser- vices as indispensable, because it was observed by such as Sir Henry Vane that “God was with him.” 503 The Battle of Marston Moor, July 2, 1644, was turned from impend- ing defeat to victory by Cromwell, Fairfax, and the Scots. It was the reluctance of parliamentary and military leaders to follow through and capitalize on the gains that convinced Cromwell that the Cause must rid itself of the “no-win” fainthearted in its midst. The crisis surfaced with Commons receiving accusations of sabotage of the war effort against the earl of Manchester, and counteraccusations against Crom- well as an incendiary. The resolution of this divisive exercise came from an unexpected {185} direction when a bill was introduced remov- ing all M.P.s from the field. This, the Self-Denying Ordinance of Febru- ary 15, 1645, eliminated all the half-hearted generals such as Essex and Manchester, who were in the House of Lords. It also eliminated Oliver Cromwell. There is no reason to doubt that Cromwell had every inten- tion of laying down his command with the others. He diligently worked on the Committee of Both Kingdoms to reorganize the army along the lines of his own regiment and was instrumental in securing Sir Thomas Fairfax as commander-in-chief of the New Model Army. 502. R. S. Paul, The Lord Protector (London: Lutterworth Press, 1955), 89. 503. Ibid., 97. 234 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Cromwell faded into the curious state of inaction which characterized his attendance on God’s call and special direction. Before the Self-Denying Ordinance went into effect, a military offen- sive launched at Leicester caused the new Commander-in-Chief Fair- fax to dispatch Cromwell and his troop post haste. Fairfax insisted that, despite the ordinance, Cromwell was indispensable to the war effort. To Cromwell, waiting on God’s sign, the seal was given when Parlia- ment permitted him to be the exception to the rule. With Fairfax in command and Cromwell lieutenant-general of the cavalry, the New Model Army became, by the end of the Civil Wars, a national fighting force considered the best in Europe. 504 The first major test of the New Model Army was at the Battle of Naseby, June 14, 1645, which proved again the superiority of Cromwell’s cavalry. The victory was the turn- ing point of the first Civil War. The capture of King Charles’s personal baggage revealed through the examination of his correspondence such duplicity and schemes for the wholesale betrayal of England that the “War Party” was vindicated in its assessment of the conflict and vacil- lating voices were silenced. The following year was a mopping-up action which ended with the escape of Charles from his headquarters at Oxford in order to surrender into what he hoped to be the friendly hands of the Scottish army at Newark. Shortly after his departure, Oxford fell, on June 24, 1646, ending the first Civil War. Despite his continuing attempts at intrigue, the king was reduced to a pawn in a power struggle emerging between Parliament and the Army, which had a newly discovered political voice of its own. The Scots were the first to use King Charles to increase their bar- gaining power. They held the king for settlement of the arrears in pay for their army, still encamped in Newark. Receiving payment, they released the king to Parliament and withdrew from England. The Parliament exulted at their possession of the king, for now they could risk disbanding the New Model Army. Their attempt hastily to dismantle the army without honoring the arrears in pay or the agreed- upon compensation for widows and orphans caused an uproar in the army. It {186} immediately organized itself into political units to pro- 504. Brig. Gen. William A. Mitchell, World’s Military History (Military Service Publishing Co., 1931), 301. Oliver Cromwell (1599–1658) 235 A Chalcedon Publication [] 3/30/07 test its grievances. Each regiment elected an officer and a rank and file member to represent it in a Central Council of the Army. On the coun- cil, Fairfax, Cromwell, and Henry Ireton, Cromwell’s son-in-law and closest advisor until his death in 1652, were central figures. A highly political group which had already been fomenting concepts of social democracy in the army, called the Levellers, seized upon the newly formed political apparatus to advance its own views. Thus, the system of democracy among those indwelt by the Holy Spirit created by Cromwell within his “fighting Church,” became politicized in peace- time. With the king in the hands of Parliament, the army quickly realized that it was powerless to justify its continued existence. The council made a historic move which established the army as a de facto power equal to Parliament. Presumably under orders of the Council of the Army, Coronet Joyce and a troop of horse seized the king from the Par- liament’s Holdenby House and placed him under the custody of the army. This revolutionary move put Cromwell, still an M.P., in an awk- ward position. He and Ireton attempted to negotiate privately with the king on behalf of the army, and put forward a plan of government called “The Heads of Proposals,” based on the concept of a limited con- stitutional monarchy. They were, in fact, ready to conciliate with any party to achieve a settlement with Parliament and yet preserve the unity of the army. To that end Cromwell made every effort to come to terms with the leader of the Levellers, John Lilburne, who in turn viewed Cromwell’s peacemaking overtures to the king with extreme suspicion. The Parliament was not slow to retaliate for the loss of the king, and the Presbyterians excluded the army sympathizers, the Inde- pendents, from the House of Commons. Amidst London rioting, Gen- eral Fairfax marched into London and forcibly reinstated the Independents and removed the Presbyterians! With all this stress it was imperative to establish army unity, and so the famous Putney Hall Debates were held in October and November of 1647 between the gen- erals and their soldiers. To the Independent “Church Meeting” atmo- sphere the Levellers brought their own version of a constitution called the “Agreement of the People,” demonstrating that they had moved far beyond discussing army grievances and were presuming to legislate on behalf of the nation. Among their innovative ideas were universal man- 236 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 hood suffrage, elimination of the House of Lords, freedom of the press, and annual Parliament. These ideas were presented in a Calvinistic frame of reference and represented divergent social interpretations of theologically oriented issues. Yet, as R. S. Paul notes, the extreme Level- lers substituted “their Divine Rights of the People” for the “Divine Right of Kings.” 505 During the debates Cromwell developed {187} his position regarding social doctrines. His motives continued to be to establish God’s kingdom on earth. He seemed to favor any system which would advance that end. It is generally thought the intellectual Ireton gave direction to Cromwell’s ideas, and together they came to represent the conservative, so-called “Grandee” position in the army, supporting the preservation of private property and limited suffrage. There is a great deal of speculation, though impossible to prove, that the king’s surprising escape from the custody of the army to Caris- brooke Castle on the Isle of Wight, was somehow engineered by Crom- well, whose cousin, Robert Hammond, happened to be governor of the Isle of Wight. As it was, Hammond did not suffer King Charles to leave, nor did he hand him over to contending parties, thus neutralizing the bargaining power of them all. The loss of the king caused a mutiny among radicals in the army who felt their interests had been betrayed, and Cromwell suppressed it with a heavy hand at Corkbush Field. Charles, in a characteristic miscalculation, decided that, because all parties were locked in a struggle for power, the time was ripe to make his own move to regain the throne. Busily in touch with any and all who would support him, Charles finally accepted an offer by the Scots to return him forcibly to the throne, in exchange for the establishment of Scottish Presbyterianism as the national religion. As 1647 closed, the Scots were raising an army and Charles was calling royalist supporters to arms. He had failed to recognize that he had been witnessing a “fam- ily quarrel.” His move provided the outside threat guaranteed to end the quarrel. In the face of uprisings in South Wales, Kent, Sussex, and elsewhere, a mutiny of the formerly loyal fleet, and an invasion by the Scottish duke of Hamilton, the army immediately returned to legend- ary New Model discipline. The Parliament voted a No Address and cut off all communication with the king. The Second Civil War of 1648 505. Paul, The Lord Protector, 219. Oliver Cromwell (1599–1658) 237 A Chalcedon Publication [] 3/30/07 suppressed the uprisings and defeated the duke of Hamilton, who, it fatally turned out, did not enjoy the support of the Presbyterian Kirk. Cromwell crossed the Tweed and reached an agreement with the Kirk. Returning to England, he tarried in Yorkshire with a protracted siege of Pontefract. In London, Henry Ireton sized the reins of action. In a dark mood after the Second Civil War, the army deemed Charles a traitor, incapable of anything but duplicity and treachery. The army demanded that he be brought to trial. When Commons hesitated, the council moved to reoccupy London and General Fairfax gave the order to arrest Charles at Carisbrooke. He also sent for Cromwell, who had been obviously “waiting on the Lord” at Pontefract for history to take a turn. By order of Ireton, Col. Thomas Pride and his soldiers marched into Commons to purge it of all members who held a soft position toward the king. The remaining 150 members who survived the mili- tary oustings became the “Rump” Parliament which hastily tried the king and ten days {188} later executed him at Whitehall on January 30, 1649. Cromwell took full part in the proceedings and he never voiced a regret about the regicide, which legend says he termed, one dark night as Charles’s body lay in state, “Cruel necessity.” 506 The indictment of the king, once uttered, pointed to the modern age, waiting in the wings. It was, in the words of R. S. Paul, unique and of a higher nature even than High Treason and since there was no regular machinery by which such case might be tried, Crom- well and his colleagues set up a clumsy machinery of their own. It was illegal machinery because the charges were in fact higher than those of which the Law took cognizance and it broke down because they tried to translate into terms of the English Common Law crimes which called into question the very foundation of the Law itself.... arbitrary power was being used to destroy arbitrary power. 507 King Charles I repeated the example of his grandmother, Mary Stuart, Queen of Scots, by bearing himself in death with a dignity he never demonstrated in life. Yet, even in his noblest moment his words illustrate a basic alienation from the future being shaped around him: 506. Antonia Fraser, Cromwell, The Lord Protector (New York: Alfred A. Knopf, 1973), 293. 507. Paul, The Lord Protector, 194. 238 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 As for the people, truly I desire their liberty and freedom as much as anybody whatsoever, but I must tell you that their liberty and freedom consists in having government, laws by which their lives and their goods may be mostly their own. It is not having a share in the govern- ment; that is nothing appertaining to them. A subject and a sovereign are clean different things. 508 The Commonwealth The establishment of the Commonwealth on March 17, 1649, was a victory for Puritans. Only Independents were members of the Rump Parliament, with not a Presbyterian within shouting distance. They were in control of the army, which had become the power in the land. Oliver Cromwell was the most powerful man in the Rump, as chairman of the newly formed Council of State, in which members of the Rump were culled out of the greater body to serve in executive capacity. He was a member of the new judicial court, and second in command of the army, where he was still the dominant member of its council. The Independents knew, and Oliver Cromwell knew, that from this time forward the Commonwealth dare not fail. Challenge from its enemies came from all quarters. News of the king’s death had sent tremors throughout Europe, and Scotland immediately crowned Charles’s son, “King Charles II,” in absentia. A serious threat of a royalist invasion from Ireland deemed an {189} offensive against Ireland necessary, but was impossible until the mutinous agitation by the Levellers within the army was quelled. Leveller John Lilburne continued his antigovern- ment protesting, seemingly unmindful that the army was now the gov- ernment. Cromwell, the same officer who had made possible a hearing for his ideas, now swiftly silenced him. All Leveller leaders were arrested. Mutinies were subdued with some bloodshed, but Cromwell’s tactic involved severe measures for the leaders and leniency for the fol- lowers. With military discipline restored, Cromwell turned his attention to the forthcoming campaign against Ireland. He made painstaking prep- arations, anticipating the use of siege tactics he was likely to encounter, and also contacted Irish allies. The actual campaign was expeditious 508. John Kenyon, “The English Civil Wars, part 3,” British History Illustrated (October/November 1978): 51. Oliver Cromwell (1599–1658) 239 A Chalcedon Publication [] 3/30/07 and vicious by necessity—the memory of Drogheda lingers yet—for he knew that England was in no mood for a protracted war. Cromwell was well aware, too, that his political enemies would be more than happy should he bog down in Ireland. Within the year, Ireland was brought under his command and was declared a member of the Common- wealth. In Scotland, royalist forces were rallying around King Charles II, and the people were reacting to the regicide of their Stuart kinsman. Crom- well became commander-in-chief of the army because Thomas Fairfax resigned in protest to the proposed invasion of Scotland and retired from public life. Cromwell made temporary peace with the radical wing of the army to preserve the precious solidarity, and then launched the war with Scotland. Trapped from the start on the coast at Dunbar, he faced formidable odds at Dunbar, yet won, on September 3, 1650, what even his incredulous friends saw as a miraculous victory. Oliver was convinced that God had delivered the Scots to him and was there- after certain that, despite political disappointments, he was still faith- fully pursuing God’s cause. He came to terms with the Kirk through diplomacy, and with royalists through further decisive battles in Fife. Then Cromwell maneuvered the remnant of the Scottish army, which was still backing the royalists, and the followers of Charles II into England, thus severing them from their support in Scotland. On the providential date of September 3, 1651, Cromwell defeated Charles II in a brilliantly executed battle at Worcester. Only a miracle could have saved the Stuart cause at this point, and, as R. S. Paul points out, “mira- cles did not seem to be attracted to the Stuart cause.” 509 Scotland, as Ireland, was annexed into the Commonwealth. Cromwell returned from Worcester a military hero to face the intractable political problems posed by the Rump. The Rump could hardly be called representative of the electorate when whole segments of the country were no longer represented, yet its members felt that it was all that was {190} left of the Long Parliament and showed no incli- nation to dissolve itself. Instead of meeting triennially, it had been in one continuous session since 1641. The army wanted it dissolved, but they shared with the Rump the fear that free elections would doom the 509. Paul, The Lord Protector, 243. 240 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Independents. For this reason, Cromwell and his officers suffered along until 1653 with the Rump’s dalliance on matters of law reform, religious reform, and the war with the Dutch. When the Rump attempted to pass a bill prohibiting their dissolution for another three years, the pretense of cooperation was dropped, and Cromwell moved with decisive speed and force to prove what everyone already knew: the army was the law of the land. On April 20, 1653, he entered Commons with a few officers and, after listening quietly to the proceedings, he leaped forward in a rage of righteous indignation and castigated the startled M.P.s with an emotional speech. “Come, come, I will put an end to your prating.... Call them in, call them in,” 510 and the sergeant- at-arms opened the door to two files of musketeers, who escorted the speaker from his chair. Thus ended the Rump and the Republic! According to Cromwell, not so much as the “barking of a dog” greeted its demise. 511 The Protectorate Oliver Cromwell, in the spring of 1653, embarked on the final years of his life at the pinnacle of power in England, displaying what the his- torians describe as the “paradox” of Cromwell the “Independent,” and Cromwell the “Lord Protector.” The perceptive R. S. Paul aptly resolves the seeming paradox by placing the years of the Protectorate as the ful- fillment of Cromwell’s prophetic mission: It was resolved in the “prophetic” function of Cromwell’s political mis- sion. On the fundamental questions of “healing and settling” he did not believe it was he himself who was speaking to the nation, but it was God speaking through him. His attitude to his Parliaments and his public utterances breathe the spirit of the prophetic “Thus saith the Lord”: it was not a denial of the Independents’ principles of democ- racy, but a development of their contention that all government should be theocratic and therefore prophetic—it was to be a public ministry exercised on behalf of the whole nation. 512 510. Howell, Cromwell, 175. 511. Fraser, Cromwell, The Lord Protector, 424. 512. Paul, The Lord Protector, 274. Oliver Cromwell (1599–1658) 241 A Chalcedon Publication [] 3/30/07 Initially, Cromwell hoped to share his prophetic mission with the Nominated Assembly (nicknamed “Barebones Parliament”) selected from the congregations of the “gathered churches.” His commission to it on July 4, 1653, was not a political speech, but had the ring of a charge at the collective Ordination of the Assembly members. The great general had {191} pastored a “fighting church,” and now the Pro- tector was calling his “political church” into service. As with the Rump, the 150 members could not claim to be representative of the nation at large, and in terms of political policy they reflected the very same split seen developing between rival factions on the Council of Officers. Nonetheless, the Nominated Assembly proceeded, in a businesslike way, working through committees, but its program designed to usher in the millennium sent spasms of horror throughout England. Some of its “shocking” legislation was to legalize civil marriages, regulate the registration of births and deaths, probate of wills, provide relief to the poor, humane care for the insane; the repeal of laws calling for the exe- cution of pickpockets, horse thieves, and the like after the first offense, and to end the relatively less humane methods of execution, such as burning at the stake and pressing to death. The “Barebones” brought calamity about its ears when it answered the mandate for law reform by voting to eliminate the Chancery, and the need for an equitable reli- gious settlement by voting to abolish tithes. To avert national chaos, Cromwell dissolved the Nominated Assembly a scant six months after it had begun. The influence of Major-General Thomas Harrison, and the Fifth Monarchists, who advocated civil reform based on biblical patterns, faded with the demise of the “rule of the saints”—a sad pass- ing for Cromwell and those who had hoped to see the kingdom of God established on earth in that culminating year. The complexion of the Protectorate years took a different turn with advisor John Lambert leading the way of the Council of Officers for a professional atmosphere. It was perhaps rendered necessary, since the repeated purges of Parliament and army had lost enthusiasts of many persuasions along the way. There was a pressing need to get on with the business of government, where Cromwell now likened himself to a constable of peace between warring factions. It is astonishing that in four years, 1654–1658, most of the farsighted and enduring foreign policy measures took place. The standing, professional New Model 242 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 Army, with an evangelist at the helm of state, made the upstart nation impossible to ignore. Spain had been among the first to recognize the Commonwealth. Taken as a whole, the concentrated thrust of Crom- well’s foreign policy was to expand English trade and export Protestant evangelism. This overview was translated into an action plan called the Western Design. Despite the on-going naval war with the Dutch over trade supremacy, Cromwell envisioned a multinational Protestant union under the leadership of England. To the relief of Holland, it never materialized, yet because of the Protectorate’s aggressive trade policies, it was commercially subordinated to England, anyway. The Protectorate’s unwillingness to strike bargains or resort to courtly intrigue won uncompromising respect from diplomats and the nations they represented. The Western Design was linked with {192} the objec- tives of the East India Company, and plans for global domination were initiated. As contemporaries said, “Cromwell gave the Lion tooth and claw.” The attacks on the Spanish monopoly of the Americas eventually resulted, for example, in the acquisition of Jamaica, whose colonization played a central role in England’s trade with its developing colonies. Origins of the British Empire are solidly rooted in the Protectorate years. Christopher Hill reflects: But for good or ill, England’s world position was transformed out of all recognition ... was changed from an agricultural island to a world power that was chiefly industrial and commercial.... Ignored before by most countries, during the time between 1654–58 all countries and interests were courting Cromwell. 513 The first Protectorate Parliament convened on Cromwell’s favorite date; “September 3,” 1654. Under the “Instrument of Government,” Oliver was installed as the Lord Protector. New faces were ascending, as the revolutionaries receded from view. Cromwell’s most valuable advisor at the time was John Thurloe, who developed an effective intel- ligence system designed to monitor not only foreign governments, but the local population as well. Plots were uncovered involving disgrun- tled republicans, army men, and royalists. A drastically unpopular pro- gram was installed under the major-generals, which had the effect of placing the entire nation under guard by regional military directors. 513. Christopher Hill, God’s Englishman (New York: Dial Press, 1970), 165. Oliver Cromwell (1599–1658) 243 A Chalcedon Publication [] 3/30/07 Until this measure, the basic military nature of the regime had not been so widely evident. At the same time, Puritan manners and habits were forced on all Englishmen by ordinance. It was the seemingly inconse- quential interference with the “simple pleasures” of unbelievers that brought home the implications of the Puritan revolution to these peo- ple far more than the loss of their king. With Cromwell’s dissolution of the First Protectorate Parliament, the second and last Protectorate Parliament was called in 1657. It pre- sented a replacement for the Instrument of Government in the “Hum- ble Petition and Advise,” which reinstated many of the old forms of government, such as the House of Lords, and the hereditary principle of succession. Cromwell had been made a king in everything but name. He was offered the crown and refused it. Cromwell attained a stature from which he could not only stretch out his hands toward the crown, so long the supreme symbol of authority in England, but also, in final triumph, reject it and still retain his power. 514 Prematurely old and sick with kidney stones, malaria from the cam- paign in Ireland, and respiratory ailments from the campaign in Scot- land, {193} Oliver Cromwell was taken in death on September 3, 1658, during the worst gale ever recorded in England. Mourners noted the date and pondered the providence of God. Conclusion Only a strong man with the prestige of Oliver Cromwell could have maintained order after his death, and his son, Richard, was hopelessly unsuited to the task. In 1660, King Charles II returned to England, serenaded by the fatuous cheers of his subjects. Yet, in only a few years, people were hearkening back sentimentally to “those Oliveran days of liberty.” Even London’s plague and fire of 1665–66 were muttered to be God’s judgment on Charles II’s England. English diplomats complained that they were treated differently by foreign countries while represent- ing Charles II than they were when representing Cromwell, and the ambassador of the Netherlands “told Charles II to his face that, of course his country treated him differently from the Protector, for 514. Fraser, Cromwell, the Lord Protector, 705. 244 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 ‘Cromwell was a great man who made himself feared by land and sea.’ ” 515 In retrospect, it is easy to see that the return of the monarchy was of little consequence in history. Parliaments were destined to rule England, representing the middle class, with its commercial and indus- trial interests. Its emulation of Cromwell’s emphasis on aggressive world trade coupled with a worldwide outreach of Protestant evange- lism caused England to enjoy her greatest moments. Cromwell, the Englishman, would appreciate that. But Cromwell was, first and fore- most, a Puritan, and the full assessment of the cause he served cannot be contained within the boundaries of English history. The revolution- aries knew that in order to establish God’s kingdom in England through Independency, they must tear out the “Root and Branch” of institutions contrary to that end. This, they found, was impossible to do. If Cromwell resembles a displaced American it is because Independency—Puritanism—IS the Root and Branch of America. Efforts to eliminate America’s Root and Branch were to prove equally difficult to others. It was no accident that the tiny American colonies watched with prayerful interest the Cromwellian era in England. Many Puritans and republicans emigrated to the colonies during the 1660s and strengthened the atmosphere of intellectual and practical curiosity and freedom that remains a Puritan legacy. It matters little, really, that the cause of Puritanism was short-circuited by pietism and a 250-year love affair with secular humanism. The fact remains that Puritanism is not a historical curiosity or a fallen blossom of the English Reforma- tion. For, in its essence, the Puritan movement was, and is, a living expression of faith in the sovereignty of God over all areas of human endeavor. Oliver Cromwell was one man, {194} called of God, and con- fessing Jesus Christ as Saviour, who dared to strive for his Savior’s king- dom on earth, whether on the battlefield or as chief-of-state. While historians mark the Cromwellian period as the dawn of the modern era, the full implications of the Puritan dream of a Holy Common- wealth built on biblical laws of justice and love have not been realized. Yet if a Christian movement were to arise in our time with the courage and vision to advance Christ’s kingdom on earth, no doubt God would send a Cromwell to lead it—and the world again would tremble. Per- 515. Hill, God’s Englishman, 254. Oliver Cromwell (1599–1658) 245 A Chalcedon Publication [] 3/30/07 haps that is why Major-General Thomas Harrison, the Fifth Monar- chist ridiculed by contemporaries and historians, may have had the last word on all of us when, from the scaffold, he answered the jeering crowd: Wait upon the Lord, for you know not what the Lord is leading to, and what the end of the Lord will be.... Though we may suffer hard things, yet He hath a gracious end, and will make for His own glory and the good end of His people. 516 516. Ibid., 248. A Chalcedon Publication [] 3/30/07 3. CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 INTRODUCTION TO WILLIAM SYMINGTON’S MESSIAH THE PRINCE James B. Jordan William Symington was born in Paisley, Scotland, in 1795, and died in 1879. A descendent of the persecuted Covenanters, he was born into and reared in the Reformed Presbyterian Church, which he served all his life. The book from which this selection is taken, Messiah the Prince, was written during his ministry at the church in Stranraer, and was first published in 1839. In that year Symington moved to a pastor- ate in Glasgow, where he served until called to the Chair of Systematic Theology at the Theological Seminary of the Reformed Presbyterian Church, also in Glasgow. Messiah the Prince, or The Mediatoral Dominion of Jesus Christ stands squarely in the Scottish theological tradition of affirming that the church is a kingdom of grace, and the state a kingdom of nature. Traditional theology had always maintained that Christ is King of both institutions by virtue of creation and of His essential Godhood, but that He is King of the church also by virtue of His redemptive work, having been enthroned as “mediatorial” King upon His ascension, when He sat down at the right hand of the Father (Heb. 1:13). Symington went further and asserted that Christ is mediatorial King also of the nations, thus bringing the state and all of society under the specifically redemp- tive sceptre of Christ. This concept is defended at length in Messiah the Prince. Christ being King of the state as well as of church—no new idea for any Scottish Covenanter, though newly strengthened by Symington’s work—clearly the nations are not free to invent their own laws, but must submit to those of Christ. We take up Symington’s discussion at this point. {195} 248 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 MESSIAH THE PRINCE, OR THE MEDIATORIAL DOMINION OF JESUS CHRIST William Symington, D.D. The Nations It is the duty of nations, as the subjects of Christ, to take his law as their rule. They are apt to think it enough that they take, as their stan- dard of legislation and administration, human reason, natural con- science, public opinion, or political expediency. None of these, however, nor indeed all of them together, can supply a sufficient guide in affairs of state. Of course, heathen nations, who are not in possession of the revealed will of God, must be regulated by the law of nature: but this is no good reason why those who have a revelation of the divine will should be restricted to the use of a more imperfect rule. It is absurd to contend that, because civil society is founded in nature, men are to be guided, in directing its affairs and consulting its interests, solely by the light of nature. Might not the same be said with as much propriety, of many other relations of human life, such as parents and children, husbands and wives, masters and servants—the duties of which we never think of exempting from the control of a preternatural revela- tion? Nay, might it not, with equal propriety, be maintained, as was for- merly of nature; and to restrict ourselves to the latter, and renounce the former, in any case in which it is competent to guide us, is at once to condemn God’s gift and to defeat the end for which it was given. We contend, then, that the Bible is to be our rule, not only in matters of a purely religious nature, in matters connected with conscience and the worship of God, but in matters of a civil or political nature. To say that in such matters we have nothing to do with the Bible, is to maintain what is manifestly untenable. To require nations, who possess the sacred volume, to confine themselves, in their political affairs, to the dim light of nature, is not less absurd than it would be to require men, Introduction to William Symington’s Messiah the Prince 249 A Chalcedon Publication [] 3/30/07 when the sun is in the heavens, to shut out its full blaze and go about their ordinary duties by the feeble rays of a taper. Indeed, if nations are moral {197} subjects, they are bound to regulate their conduct by what- ever laws. We have only to look into the volume of revelation itself, to have these reasonings confirmed. The people of Israel were instructed to regulate their national concerns by a revealed standard, and were taught to regard the possession of God’s revealed statutes and judg- ments as a national distinction for which they were bound to be grate- ful. Nor is there anything said which would warrant us to conclude that this was to be regarded as peculiar to that people. “Behold,” says Moses, “I have taught you statutes and judgments, even as the Lord my God commanded me, that ye should do so in the land whither ye go to pos- sess it: keep therefore and do them; for this is your wisdom and your understanding in the sight of the nations. And what nation is so great that hath statutes and judgments so righteous as all this law which I set before you this day?” (Deut. 4:5–6, 8). In strict conformity with this, the chief magistrate was to have a copy of the law, according to which he should act in the discharge of his official duties. com- mandment, to the right hand or to the left: to the end that he may pro- long his days in his kingdom, he and his children in the midst of Israel” (Deut. 17:18–20). The same principle is illustrated in the instructions given to the rulers, judges and kings of Israel. To Joshua it was said, “This book of the law shall not depart out of thy mouth; but thou shalt 250 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07 meditate therein day and night, that thou mayest observe to do accord- ing to all that is written therein: for then thou shalt make thy way pros- perous, and then thou shalt have good success” (Josh. 1:8). When the days of David drew nigh that he should die, he charged Solomon, his successor on the throne: “Be thou strong and shew thyself a man; and keep the charge of the Lord thy God, to walk in his ways, to keep his statutes, and his commandments, and his judgments, and his testimo- nies, as it is written in the law of Moses, that thou mayest prosper in all that thou doest, and whithersoever thou turnest thyself ” (1 Kings 2:1– 3). {198} We wait not to quote those passages, in which nations and their rul- ers ille- gitimate,- istrates con- duct con- trary to it, but may, at pleasure, revel with impunity in the violation of every branch of revealed truth—a degree of licentious indulgence which, however agreeable to the taste of the infidel, cannot fail to shock the mind of every Christian. Introduction to William Symington’s Messiah the Prince 251 A Chalcedon Publication [] 3/30/07, kings obli- gation {199} partic- ular relation and circumstances is not under obligation to obey those parts of revelation which have respect to persons placed in other rela- tions 252 JOURNAL OF CHRISTIAN RECONSTRUCTION A Chalcedon Publication [] 3/30/07, sev- enth, eighth, and ninth commandments, but just by passing laws obli- gating constitu- tion {200}. A Chalcedon Publication [] 3/30/07 PUBLICATION SCHEDULE Volume 7 (1980) of the Journal of Christian Reconstruction will feature sympo- siums on “Inflation” and “Evangelism.” Manuscripts dealing with either topic are now being reviewed for publication. Anyone wishing to submit a manuscript for consideration would be wise to clear the topic in advance with the editor. Manuscripts should be between 20 and 40 pages in length, typewritten and dou- ble-spaced. A Manuscript Style Sheet for the Journal is available from the editor or directly from Chalcedon. It is imperative that each writer consult this style sheet before submitting a final draft of any manuscript. If accepted, the Journal will pay the author $75 upon publication. Shorter manuscripts (under 15 pages) receive $35. Book reviews (5–10 pages) receive $10; books dealing with the sym- posium’s topic are preferred. Suggestions concerning the reprinting of important documents or published articles, if accepted, are worth $20, if accompanied by a clear photocopy of the recommended piece. Manuscripts suitable for publication in the sections on “Christian Reconstruc- tion” and “Defenders of the Faith” are always given careful consideration, as are suggestions for reprinting. Again, it is wise to clear the topic in advance with the editor. Summaries of dissertations are acceptable. Deadlines: INFLATION February 15, 1980 EVANGELISM August 15, 1980 GARY NORTH, Editor 713 W. Cornwallis Road Durham, NC 27707 (919) 489–9137 THE MINISTRY OF CHALCEDON Chalcedon [kalSEEdon] is a Christian educational organization devoted exclu- sively to research, publishing, and cogent communication of a distinctly Chris- tian scholarship to the world at large. It makes available a variety of services and programs, all geared to the needs of interested laymen who understand the propositions that Jesus Christ speaks to the mind as well as the heart, and that His claims extend beyond the narrow confines of the various institutional churches. We exist in order to support the efforts of all orthodox denominations and churches. Chalcedon derives its name from the great ecclesiastical Council of Chalcedon (AD 451), which produced the crucial Christological definition: “Therefore, fol- lowing the holy Fathers, we all with one accord teach men to acknowledge one and the same Son, our Lord Jesus Christ, at once complete in Godhead and com- plete in manhood, truly God and truly man....” This formula challenges directly every false claim of divinity by any human institution: state, church, cult, school, or human assembly. Christ alone is both God and man, the unique link between heaven and earth. All human power is therefore derivative; Christ alone can announce that “All power is given unto me in heaven and in earth” (Matthew 28:18). Historically, the Chalcedonian creed is therefore the foundation of West- ern liberty, for it sets limits on all authoritarian human institutions by acknowl- edging the validity of the claims of the one who is the source of true human freedom (Galatians 5:1). Christians have generally given up two crucial features of theology that in the past led to the creation of what we know as Western civilization. They no longer have any real optimism concerning the possibility of an earthly victory of Chris- tian principles and Christian institutions, and they have also abandoned the means of such a victory in external human affairs: a distinctly biblical concept of law. The testimony of the Bible and Western history should be clear: when God’s people have been confident about the ultimate earthly success of their religion and committed socially to God’s revealed system of external law, they have been victorious. When either aspect of their faith has declined, they have lost ground. Without optimism, they lose their zeal to exercise dominion over God’s creation The Ministry of Chalcedon 255 A Chalcedon Publication [] 3/30/07 (Genesis 1:28); without revealed law, they are left without guidance and drift along with the standards of their day. Once Christians invented the university; now they retreat into little Bible colleges or sports factories. Once they built hospitals throughout Europe and America; now the civil governments have taken them over. Once Christians were inspired by “Onward, Christian Soldiers”; now they see themselves as “poor wayfaring strangers” with “joy, joy, joy, joy down in their hearts” only on Sundays and per- haps Wednesday evenings. They are, in a word, pathetic. Unquestionably, they have become culturally impotent. Chalcedon is committed to the idea of Christian reconstruction. It is premised on the belief that ideas have consequences. It takes seriously the words of Profes- sor F. A. Hayek: “It may well be true that we as scholars tend to overestimate the influence which we can exercise on contemporary affairs. But I doubt whether it is possible to overestimate the influence which ideas have in the long run.” If Christians are to reconquer lost ground in preparation for ultimate victory (Isa- iah 2, 65, 66), they must rediscover their intellectual heritage. They must come to grips with the Bible’s warning and its promise: “Where there is no vision, the people perish: but he that keepeth the law, happy is he” (Proverbs 29:18). Chalce- don’s resources are being used to remind Christians of this basic truth: what men believe makes a difference. Therefore, men should not believe lies, for it is the truth that sets them free (John 8:32). Finis
https://www.scribd.com/document/30544367/JCR-Vol-06-No-01-Symposium-on-Puritanism-and-Progress
CC-MAIN-2018-47
refinedweb
97,496
56.29
Home > Project Euler, python > Problem Euler #19 Problem Euler #19 novembre 13, 2012 Lascia un commento Go to comments)? Python: import time import datetime as date ts = time.clock() def how_much_sundays(y, z): count = 0 for y in range(y, z + 1): for m in range(1, 13): for d in range(1, 32): try: dobj = date.date(y, m, d) day = dobj.weekday() if day == 6 and d == 1: count += 1 except ValueError: pass return count if __name__ == '__main__': print how_much_sundays(1901, 2000) print time.clock() - ts Annunci Categorie:Project Euler, python Commenti (0) Trackbacks (0) Lascia un commento Trackback Commenti recenti
https://bancaldo.wordpress.com/2012/11/13/problem-euler-19/
CC-MAIN-2017-26
refinedweb
103
64.41
Search Criteria Package Details: perl-devel-repl 1.003028-4 Dependencies (18) - perl-b-keywords - perl-data-dump-streamer - perl-data-dumper-concise - perl-file-homedir - perl-file-next - perl-lexical-persistence - perl-module-refresh - perl-module-runtime - perl-namespace-autoclean - perl-ppi - perl-ppi-xs - perl-sys-sigaction - perl-task-weaken - perl-moosex-object-pluggable>=0.0009 - perl-moosex-getopt>=0.72 - perl-moose>=0.93 - perl-test-cpan-meta (make) - perl-test-fatal (make) Latest Comments 1 2 3 Next › Last » mbunkus commented on 2020-11-03 22:14 I'm not sure why I missed those comments back in March until a kind soul flagged the package out-of-date half an hour ago. Sorry for that. I've just added all the packages required for the optional REPL modules to the PKGBUILD. It's true that those modules are optional, but as they're distributed with the package the REPL attempts to auto-load them, which obviously fails is the optional modules' requirements aren't installed. You'll have to install a couple more packages from the AUR now, but re.pl will start again. jthvai commented on 2020-03-17 05:00 After some testing: Before compiling, add perl-lexical-persistence, perl-data-dump-streamer, and perl-ppito the depends array in the PKGBUILD. lexical-persistence and data-dump-streamer are both AUR packages (with their own quirks that need some patching to the PKGBUILD. This ensures that you are at the very least brought to the REPL shell (i.e., it runs), but I make no guarantees as to whether it parses Perl correctly after these additions~ Nowaker commented on 2020-03-13 01:51 Compiles just fine, but won't start. mbunkus commented on 2018-08-24 15:33 The warnings while building perl-getopt-long-descriptive don't indicate that the package won't work. They only indicate that the package uses deprecated features that will be gone in Perl 5.32. You can simply build perl-getopt-long-descriptive without the tests, install it and continue with perl-moosex-getopt. Additionally you should probably file a bug report with Getopt::Long::Descriptive. hexadecagram commented on 2018-08-24 03:08 Thanks for the tips, @mbunkus, I did as you prescribed. When I reach step 4, it says that it wants perl-getopt-long-descriptive, which also fails testing. mbunkus commented on 2018-08-23 16:04 I am aware of the Perl update. The problem is, as you've noticed, that its dependency perl-moosex-getopt doesn't test cleanly. A new version has already been released upstream that does compile, and perl-moosex-getopt has appropriately flagged as outdated. So here's your solution: I've just pushed a new version of perl-devel-repl that not only bumps the pkgrel, but also depends on perl-moosex-getopt>=0.72 in order to make this explicit. hexadecagram commented on 2018-08-23 09:20 ArchLinux Perl got updated from 5.26 to 5.28 recently, and as a result this package is b0rken. pacman does not upgrade perl modules when a new base version is released, so to force a reinstall of all the modules, I run: LC_ALL=C find "/usr/lib/perl5/site_perl" -type f -exec pacman -Qqo {} + |& sed -n 's/^error: No package owns \(.*\)$/\1/p' as prescribed. Some packages lag behind, such as perl-task-weaken and perl-getopt-long-descriptive. The former continues to install in /usr/lib/perl5/5.26 where as the latter just flatly fails to pass the testing phase. Also, I made a comment for perl-data-dump-streamer which is one of the complaints re.plfires at me when it starts. It seems to want this package even though it doesn't seem strictly necessary (I've gotten it to run without it). The only solution right now is to pacman -Rccs perl-devel-repland hope that some kind user can help me get it reinstalled. ;-) jnbek commented on 2016-04-08 14:27 Also, regarding my Jenkins builder, I'll Open Source it when it's ready. It will scan your aur4/ root for new dirs, changes to PKGBUILDs etc using Inotify and trigger builds, create new builds if a new directory appears in the root, delete builds when a dir is removed ( say deleted pkgbuilds etc ). That way, it'll help those of us with a cpl hundred thousand PKGBUILDs to stay ahead of problems. I hope to have it done before Perl 5.24 releases, since core perl always makes for funtimes for perlaur :-P Email me, or add me on FB and we'll coordinate testing etc. jnbek commented on 2016-04-08 14:23 Err, no, I'm very active with Maintainership of the AUR. I do rely heavily on the users to inform me when things break, even with an autobuilder, new deps can easily get missed, since I probably have hte dependency installed, but if the utility fails to catch the dep and put it in the pkgbuild, I'm ignorant to it, I only become aware of problems when either a) my build breaks or b) y'all tell me :D In other news, I'm working on a Jenkins build environment that will email me failures and can help me to notice problems a bit better, but even still, it won't be perfect. Just ping me if any of my PKGBUILDs are broken/out of date. I almost always get to them the same day I see the email. mbunkus commented on 2016-04-08 07:07 Absolutely. If the package is orphaned I'll adopt it.
https://aur.archlinux.org/packages/perl-devel-repl/
CC-MAIN-2021-25
refinedweb
946
62.68
To define a single drag object, you will add a special attribute to the image component, then specify the new attribute as the drag source that will be passed to the target when the image is dragged to a target component. To define the first single drop target object, you will specify an attribute on the input text component as the target to receive a drag source when a component is dropped on it. Next you will create a custom drop event listener method in a JavaBean to programmatically handle a drop event. To define the second drop target object, you will register the custom listener on the listbox component. The final page will look like this: From the main menu, choose File > New. In the New Gallery, expand the General category and select Applications. Then in the Items list, select Custom Application and click OK. To follow along with the example, enter DndAppas the application name and_6<< In the Application Navigator you can collapse and expand any panel. You adjust the size of panels by dragging the splitter between two panels. To group and sort items in the Projects panel, use the _9<<. Enter MyPage.jsfas the file name. Make sure Facelets is the selected document type. The New Gallery The JSF navigation diagrammer The ADF task flow diagrammer (available only in the Studio edition of JDeveloper) On the Page Layout page, select Quick Start Layout, then click Browse. In the Component Gallery, select the Two Column category on the left. Then on the right, select the third type and the third layout. You should see Two Column Left, Partial Header (Two Splits, Stretched) in the Options box. Click OK. The Create JSF Page dialog should now display the quick start layout selection you made: Click Managed Bean and select Do Not Automatically Expose UI Components in a Managed Bean. Click OK. By default JDeveloper opens the new page in the visual editor, showing the first facet of the horizontal panel splitter as selected. Click Save All to save your work.. trinidad-config.xml file: Where you configure ADF Faces features such as skin family and level of page accessibility support. jsf) or JSP documents written in XML syntax (which have file extension .jspx). You can create both types of JSF pages with the Create JSF Page dialog, opening it from: In the Component Gallery of quick start layouts, you can choose from one, two, or three column layouts, and then determine how you want the columns to behave (for example, fixed widths or stretched). You can also choose to add color and styling to the quick start layout you select by checking the Apply Themes checkbox. By default components are not exposed to managed beans. If you wish to bind components to managed beans, select one of the automatic binding options on the Managed Bean page in the dialog. _14<< To view the page code, click the Source tab to switch from the visual editor to the XML editor. For example, the following code is generated for a Two Column Left, Partial Header (Two Splits, Stretched) layout: The structure of the starter JSF Facelets page (with file extensionThe structure of the starter JSF Facelets page (with file extension <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <f:view xmlns: <af:document <af:form <af:panelSplitter <f:facet <f:facet <!-- <f:facet <f:facet </af:panelSplitter> </f:facet> </af:panelSplitter> </af:form> </af:document> </f:view> .jsf) has one xmlnsattribute for the JSF Core tag library and one xmlnsattribute for the ADF Faces tag library. The other elements included in the starter file are elements for laying out a page, specifically everything else within <f:view>and </f:view>. Once your page file is created, you can add UI components and work with the page source. In the project, the folders and files that conform to the Java EE Web module directory structure are: You will insert an image to be used as the UI component to drag on the page. To define a single drag object, you will add a special attribute to the image and then specify the newly added attribute as the drag source. In the Component Palette, ADF Faces page, Layout panel, Interactive Containers and Headers section, drag and drop Panel Box into the first facet of the horizontal panel splitter on the left side of the page. When you drag the component to the facet, you should see a target rectangle with the name Facet first on the page; this means the component you are dragging will be inserted inside that target. In the Property Inspector, Common section, change the Text attribute value to Drag this. In the Component Palette, General Controls panel, drag and drop Image into the panel box you just added. In the Insert Image dialog, from the dropdown menu next to the Source field, choose Edit. Then use the dialog to locate and select an image file. Click OK. When prompted, click Yes to add the image under the resources directory, then click Save. You should see #{resource['images:jdeveloper.png']}in the Source field. Click OK to close the Insert Image dialog. In the Component Palette, expand the Operations panel. Drag and drop Client Attribute into the image component you just added. In the Property Inspector for Client Attribute, enter the following values: In the Component Palette, Operations panel, Drag and Drop section, drag and drop Attribute Drag Source into the image component. In the Insert Attribute Drag Source dialog, enter cupin the Attribute field or select it from the dropdown list. Then click OK. Click Save All to save your work. The page in the visual editor should look similar to this: <jdev_home>/jdeveloper/ide/lib/folder and double-click oicons.jarto open it. oracle/javatools/icons/headerand select the image file jdeveloper.png. af:clientAttributelets you specify the name and value of an attribute to add to a component. Note that in a real-world application, theNote that in a real-world application, the <af:image <af:clientAttribute </af:image> valueattribute would be an EL expression pointing to a bound attribute (for example, #{bindings.Departmentname.inputValue}). At runtime the EL expression will evaluate to a value. By embedding af:clientAttributeinto a component, at runtime, the added attribute is made available both on the client side as well as on the server side. af:attributeDragSourcetag lets you specify a component attribute to use as the drag source. In the example, by adding af:clientAttributeto the image component and also using af:attributeDragSourceto specify the added attribute as the drag source, at runtime when the user drags the image, the added attribute becomes the component attribute to use as the drag source. Note: If you wish to use an existing component attribute as the drag source, you don't need to addNote: If you wish to use an existing component attribute as the drag source, you don't need to add <af:image <af:clientAttribute <af:attributeDragSource </af:image> af:clientAttribute. For example, the following code uses the output text component's valueattribute as the drag source: You can drag a single object using a component and one of its attributes as the drag value, or you can drag a collection of objects such as a table or tree component.You can drag a single object using a component and one of its attributes as the drag value, or you can drag a collection of objects such as a table or tree component. <af:outputText <af:attributeDragSource </af:outputText> ADF Faces provides two other tags for declaratively enabling a component as a drag source, namely, af:componentDragSourceand af:dragSource. For details on how to use the tags, see the ADF Faces Tag Reference documentation. You will insert an input field to be used as the UI component to accept a dragged component. To define a single drop target object, you will specify an attribute on the input field that will be used as the target to receive a drag source. In the visual editor, drag the horizontal splitter bar down to about half the page. In the Component Palette, ADF Faces page, Layout panel, Interactive Containers and Headers section, drag and drop Panel Box into the first facet on the right side of the page. In the Property Inspector, Common section, change the Text value to Drop here. In the Component Palette, Layout panel, drag and drop Panel Group Layout into the panel box component you just added. In the Property Inspector, Common section, change the Layout value to scroll. In the Component Palette, Text and Selection panel, drag and drop Input Text into the panel group layout component you just added. In the Property Inspector, Common section, change the Label value to Cup. In the Component Palette, Operations panel, Drag and Drop section, drag and drop Attribute Drop Target into the input text component. In the Insert Attribute Drop Target dialog, select value from the Attribute dropdown list, and click OK. In the Application Navigator, right-click My> Drag the image and position it over the Cup input field. As you position the cursor over the input field, the background color of the field changes, indicating the mouse cursor is over an acceptable area on the page where the image can be dropped. If the mouse cursor is not over an acceptable drop target, the cursor changes to a circle with a slash across it. When you release the mouse button to drop the image on the input field, you should see the word Coffeein the Cup input field. af:attributeDropTargettag lets you specify a component attribute to be set (such as value) when a compatible value is dragged and dropped onto the target component. In the Structure window, you should see the component you have defined as the drop target. In the example, by embedding af:attributeDropTargetwithin af:inputTextand specifying valueas the drop target attribute, at runtime when a compatible drag source is dropped on the input text component, the input component will automatically refresh to show the value of the source.. <af:inputText </af:inputText> Note: You can drag a single object and drop it to another single object only. Similarly, you can drag a collection and drop it to another collection only. You cannot drag and drop a single object to a collection, and vice versa. ADF Faces provides three other tags for declaratively enabling a component as a drop target, namely, af:collectionDropTarget, af:calendarDropTarget, and af:dropTarget. For details on how to use the tags, see the ADF Faces Tag Reference documentation. _26<< Note: Terminating the application stops and undeploys the application from Integrated WebLogic Server but it does not terminate Integrated WebLogic Server. You will create a Java class and listener method for handling a drop event. The class will be registered as a managed bean using annotations. In the Application Navigator, double-click faces-config.xml to open the file in the editor window. Click the Overview tab at the bottom of the editor window. Then in the Managed Beans section of the overview editor, click to open the Create Managed Bean dialog. In the Create Managed Bean dialog, enter the following values or select the. If necessary, in the editor window click the MyPageInfo.java tab at the top to bring the document forward. Note the managed bean annotations JDeveloper added for you: @ManagedBean(name="dnd") @SessionScoped public class MyPageInfo implements Serializable { ... } Java Code Insight, the Java-specific implementation of completion insight Code Assist to fix common problems Import statement assistance and sorting Automatic doc comment templates Customizable sorting and expansion for the Structure window Distinctive highlighting for syntax and semantic errors Customizable code separators In the source editor, add custom code to handle a drop event. For example, you can add code that inserts a dropped value to a list of items in a listbox. To achieve this, first you add a property and getter method that creates a list of items for populating a select input component. Then you create a DndActionmethod that handles a drop event. Instead of writing your own code, you can use the sample code provided. In the source editor, delete all the generated code and replace with this: In the Application Navigator, right-click MyPageInfo.java and choose Make. You should see the message Successful compilation: 0 errors, 0 warningsin the Messages Log window. faces-config.xml. A managed bean is any application JavaBean that is either registered in the JSF configuration file faces-config.xmlor has special managed bean annotations in the bean class. Note: If you are creating an application that also uses ADF data bindings and task flows, you should add managed beans to either the adfc-config.xmlfile or the task flow definition file. In this step, you are merely using the faces-config.xmloverview editor to access the Create Managed Bean dialog and let JDeveloper create the Java class file for you. Scope: The scope of a managed bean determines the scope within which the bean is stored. The following are the valid scopes for a bean:, JDeveloper automatically updates the faces-config.xmlfile for you with the necessary configuration elements. For example: <managed-bean> <managed-bean-name>dnd</managed-bean-name> <managed-bean-class>MyPageInfo</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> As you can see, using managed bean annotations reduces the size and complexity of the faces-config.xmlfile, which can grow quite substantially. When the JSF application starts up, faces-config.xmlis parsed and registered managed beans (if any) are made available. Also, any JavaBeans marked by annotations become managed beans at runtime.. import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import java.util.ArrayList; import java.util.List; import javax.faces.model.SelectItem; import oracle.adf.view.rich.datatransfer.DataFlavor; import oracle.adf.view.rich.dnd.DnDAction; import oracle.adf.view.rich.event.DropEvent; @ManagedBean(name="dnd") @SessionScoped public class MyPageInfo implements Serializable { public MyPageInfo() { } /** * @return the beverage items */ private List<SelectItem> _choices; public List<SelectItem> getChoices() { if (_choices == null) { _choices = new ArrayList<SelectItem>(); _choices.add(new SelectItem("Cocoa", "Cocoa")); _choices.add(new SelectItem("Tea", "Tea")); _choices.add(new SelectItem("Wine", "Wine")); } return _choices; } /** * Drop event handler */ public DnDAction handleItemDrop(DropEvent dropEvent) { try { DataFlavor<String> df = DataFlavor.getDataFlavor(String.class); String droppedValue = dropEvent.getTransferable().getData(df); if (droppedValue == null) { return DnDAction.NONE; } else { _choices.add(new SelectItem(droppedValue, droppedValue)); } return DnDAction.COPY; } catch (Exception ex) { System.out.println("item drop failed with : " + ex.getMessage()); return DnDAction.NONE; } } } In the example, you create a drop event listener method that adds a dropped value to a list of items in a listbox. You also create a property and getter method to dynamically populate the listbox with an initial list of items. The first method is a getter method for returning a Listof javax.faces.model.SelectIteminstances. This is for populating a listbox component, which you will add later. To write the method, first declare a property of type List<SelectItem>, then use a set of add(new SelectItem("some value", "some label"))statements to create the list. The second method is a drop event listener method. A drop event listener method takes a DropEventevent as a parameter and returns oracle.adf.view.rich.dnd.DndAction. For example: The drop event listener method must determine whether the drop event is accepted or rejected, and return an appropriateThe drop event listener method must determine whether the drop event is accepted or rejected, and return an appropriate public DnDAction handleDrop(DropEvent dropEvent) { // handle drop event here } DndAction. If accepted, valid values must be one or more NMTOKENSfrom the set of COPY, MOVE, LINK(in any order). If rejected, DndAction.NONEshould be returned. In the drop method logic, retrieve the dropped value and use the dropped value as the value and label for a new select item to add to the SelectItemlist. At runtime, when an item is dropped on the listbox, the listbox refreshes to show the new list of items. For more details about retrieving data from a transferable object in a drop event, see the Javadoc for oracle.adf.view.rich.event.DropEventand oracle.adf.view.rich.datatransfer. You will add a listbox component to serve as a new drop target on the page, then register the listener method on the target. In the editor window, click the MyPage.jsf tab at the top to bring the page forward. In the Component Palette, ADF Faces page, Text and Selection panel, drag and drop Listbox into the second facet on the page. In the Insert Listbox dialog, Select page, make sure Bind to list (select items) is selected. Click Bind... next to the Value field. In the Expression Builder, expand JSF Managed Beans | dnd. Select choices to create the expression #{dnd.choices},. Then click Finish to complete inserting the listbox. In the Property Inspector for the select one listbox component, Common section, change the Label value to Beverage choicesand press Enter. The page in the visual editor should now look like this: In the Component Palette, Operations panel, Drag and Drop section, drag and drop Drop Target into the select one listbox component on the page. In the Insert Drop Target dialog, choose Edit from the dropdown menu next to the DropListener field. In the Edit Property dialog, select dnd from the Managed Bean dropdown list, then select handleItemDrop from the Method dropdown list. Click OK. You should see #{dnd.handleItemDrop}in the DropListener field. Click OK to close the Insert Drop Target dialog. In the Insert Data Flavor dialog, enter java.lang.Stringin the FlavorClass field, and click OK. In the Application Navigator, right-click MyPage.jsf and choose Run. The page in the browser now looks similar to this: Drag the image and drop it on the list of beverage choices. Upon a successful drop action, the drop target rerenders by partial page rendering, thus you should see the new item Coffee appended to the list of existing beverage choices in the listbox: af:selectOneListboxcomponent and use it as the drop target. The af:selectOneListboxcomponent (and other similar select input components) can contain one f:selectItemscomponent for representing the items in the list. For the af:selectOneListboxcomponent to be populated with an initial list of items at runtime, you value bind the f:selectItemscomponent (through its valueattribute) to a getter method on a managed bean that returns an array of javax.faces.model.SelectIteminstances. When you add the af:selectOneListboxcomponent, the Insert Listbox dialog displays for you to create individual, static items for the list, or to bind to a list that is populated dynamically through a managed bean. Since you have already created a property and a getter method in a managed bean that can populate the list dynamically, you will choose to bind to a dynamic list. : af:dropTargettag with a component to make that component eligible for accepting drops. The af:dropTargettag has a dropListenerattribute, which enables you to register your custom drop event listener method on the drop target. af:dataFlavortag with the af:dropTargettag, java.lang.Stringor java.util.Collection). In the example you specify a data flavor of java.lang.Stringbecause the client attribute value you are using as the drag source is a String. After binding, the complete code for the select one listbox component is this: <af:selectOneListbox <af:dataFlavor </af:dropTarget> </af:selectOneListbox> - Use JDeveloper wizards and dialogs to create applications and starter pages - Use the visual editor, Component Palette, Property Inspector, and Structure window to create UI pages - Add a client attribute to a component - Specify a single component attribute as a drag source or a drop target - Create a drop event listener method to invoke custom code for handling a drop action - Use Integrated WebLogic Server to run an ADF Faces application
http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_41/jdtut_11r2_41.html
CC-MAIN-2017-22
refinedweb
3,320
54.63
Ping O:-)Looking for feedback from at least Cleber and Eduardo before I barge ahead and send a PR to include this on master. Additional packaging and versioning feedback from Dan would be nice. (I know we have a very busy two weeks here; I will continue pinging, but I have every intention of merging this prior to 5.2.)(I know we have a very busy two weeks here; I will continue pinging, but I have every intention of merging this prior to 5.2.) --js On 10/20/20 3:35 PM, John Snow wrote: Based-on: This series factors the python/qemu directory as an installable package. It does not yet actually change the mechanics of how any other python source in the tree actually consumes it (yet), beyond the import path. > The point of this series is primarily to formalize our dependencies on mypy, flake8, isort, and pylint alongside versions that are known to work. It also adds explicitly pinned versions of these dependencies that should behave in a repeatable and known way for developers and CI environments both. With the python tooling as a proper package, you can install this package in editable or production mode to a virtual environment, your local user environment, or your system packages. The primary benefit of this is to gain access to QMP tooling regardless of CWD, without needing to battle sys.path. For example: when developing, you may go to qemu/python/ and invoke `pipenv shell` to activate a virtual environment that contains the qemu packages. This package will always reflect the current version of the source files in the tree. When you are finished, you can simply exit the shell to remove these packages from your python environment. When not developing, you could install a version of this package to your environment outright to gain access to the QMP and QEMUMachine classes for lightweight scripting and testing by using pip: "pip install [--user] ." Finally, this package is formatted in such a way that it COULD be uploaded to and installed independently of qemu.git with `pip install qemu`, but that button remains unpushed. TESTING THIS SERIES: CD to qemu/python first, and then: 1. Try "pipenv shell" to get a venv with the package installed to it in editable mode. Ctrl+d exits this venv shell. While in this shell, any python script that uses "from qemu.[qmp|machine] import ..." should work correctly regardless of your CWD. 2. Try "pipenv sync --dev" to create/update the venv with the development packages without actually entering the venv. This should install isort, mypy, flake8 and pylint to the venv. 3. After the above sync, try "pipenv shell" again, and from the python project root, try any of the following: - pylint qemu - flake8 qemu - isort -c qemu - mypy qemu 4. Leave any venv you are in, and from the project root, try the following commands: - pipenv run pylint qemu - pipenv run flake8 qemu - pipenv run isort -c qemu - pipenv run mypy qemu V3: - Changed "qemu.core" to "qemu.qmp" and "qemu.machine", Partly to accommodate forthcoming work which would benefit from a separate qemu.qmp namespace. - Changed the initial version from 5.2.0a1 to 0.5.2.0a1, to allow for more rapid development while we smooth out the initial kinks. - 001: Renamed patch title; differences implement the new names. - 002: Readme changes for above. - 003: Version change. - 004: New readme for the new qmp directory. - 006: A few more import exceptions for pylint, hopefully temporary. - 009: Updated flake8 config comment to match qapi's - 012: Added namespace_package configuration value 001/15:[down] 'python: create qemu packages' 002/15:[0009] [FC] 'python: add qemu package installer' 003/15:[0002] [FC] 'python: add VERSION file' 004/15:[0015] [FC] 'python: add directory structure README.rst files' 005/15:[----] [--] 'python: Add pipenv support' 006/15:[down] 'python: add pylint import exceptions' 007/15:[----] [--] 'python: move pylintrc into setup.cfg' 008/15:[----] [--] 'python: add pylint to pipenv' 009/15:[0002] [FC] 'python: move flake8 config to setup.cfg' 010/15:[----] [--] 'python: Add flake8 to pipenv' 011/15:[----] [-C] 'python: move mypy.ini into setup.cfg' 012/15:[0001] [FC] 'python: add mypy to pipenv' 013/15:[----] [--] 'python: move .isort.cfg into setup.cfg' 014/15:[----] [--] 'python/qemu: add isort to pipenv' 015/15:[----] [--] 'python/qemu: add qemu package itself to pipenv' John Snow (15): python: create qemu packages python: add qemu package installer python: add VERSION file python: add directory structure README.rst files python: Add pipenv support python: add pylint import exceptions python: move pylintrc into setup.cfg python: add pylint to pipenv python: move flake8 config to setup.cfg python: Add flake8 to pipenv python: move mypy.ini into setup.cfg python: add mypy to pipenv python: move .isort.cfg into setup.cfg python/qemu: add isort to pipenv python/qemu: add qemu package itself to pipenv python/PACKAGE.rst | 26 +++ python/README.rst | 27 +++ python/qemu/README.rst | 8 + python/qemu/machine/README.rst | 9 + python/qemu/qmp/README.rst | 9 + python/Pipfile | 16 ++ python/Pipfile.lock | 207 ++++++++++++++++++++ python/VERSION | 1 + python/mypy.ini | 4 - python/qemu/.flake8 | 2 - python/qemu/.isort.cfg | 7 - python/qemu/__init__.py | 11 -- python/qemu/machine/__init__.py | 44 +++++ python/qemu/{ => machine}/accel.py | 0 python/qemu/{ => machine}/console_socket.py | 0 python/qemu/{ => machine}/machine.py | 16 +- python/qemu/{ => machine}/qtest.py | 3 +- python/qemu/{qmp.py => qmp/__init__.py} | 12 +- python/{qemu/pylintrc => setup.cfg} | 67 ++++--- python/setup.py | 23 +++ tests/acceptance/boot_linux.py | 3 +- tests/qemu-iotests/297 | 2 +- tests/qemu-iotests/300 | 4 +- tests/qemu-iotests/iotests.py | 2 +- tests/vm/basevm.py | 3 +- 25 files changed, 437 insertions(+), 69 deletions(-) create mode 100644 python/PACKAGE.rst create mode 100644 python/README.rst create mode 100644 python/qemu/README.rst create mode 100644 python/qemu/machine/README.rst create mode 100644 python/qemu/qmp/README.rst create mode 100644 python/Pipfile create mode 100644 python/Pipfile.lock create mode 100644 python/VERSION delete mode 100644 python/mypy.ini delete mode 100644 python/qemu/.flake8 delete mode 100644 python/qemu/.isort.cfg delete mode 100644 python/qemu/__init__.py create mode 100644 python/qemu/machine/__init__.py rename python/qemu/{ => machine}/accel.py (100%) rename python/qemu/{ => machine}/console_socket.py (100%) rename python/qemu/{ => machine}/machine.py (98%) rename python/qemu/{ => machine}/qtest.py (98%) rename python/qemu/{qmp.py => qmp/__init__.py} (96%) rename python/{qemu/pylintrc => setup.cfg} (50%) mode change 100644 => 100755 create mode 100755 python/setup.py
https://lists.gnu.org/archive/html/qemu-devel/2020-10/msg08515.html
CC-MAIN-2022-33
refinedweb
1,090
61.22
Neeran Gul At Yammer, we run more than a dozen different PostgreSQL clusters supporting our Production applications. As with most databases, we run regular maintenance tasks such as rotating user credentials, adding new users and databases, dealing with index bloat reduction, and so on. To make life easier, we have created additional tools to streamline our maintenance tasks without human intervention. The purpose of this article is to show how we use our pg_tester gem with RSpec to provide a TDD-approach for writing maintainable scripts and automation involving PostgreSQL. The Ruby gem pg_tester provides users with the functionality to write tests for their scripts involving PostgreSQL. It creates a temporary database in a directory of the user’s choice and allows it to be accessible via the pg gem API. It was designed to facilitate automated tests against a PostgreSQL instance reliably and cleanly, and without needing to do any hardcore database configuration and setup! You only need to have installed PostgreSQL locally first via whichever method you prefer (dpkg, rpm, tar.gz, exe, source etc). The pg_tester gem is available from Microsoft’s repository on Github: As an example, we’ll create a new user by taking the TDD-approach and using pg_tester. We will also use ruby 2.1.2 (available at). Here’s what our final test will perform: 1. Create a new user with a username and password. 2. Verify the new user exists in the database. Let’s setup our dev environment. The directory setup and layout looks like this: pg_tester_example ├── Gemfile └── spec ├── postgresql_manager.rb └── postgresql_manager_spec.rb Our Gemfile is as follows: ### Gemfile source "" gem "pg_tester" gem "pg" gem "rspec" After the Gemfile is in place, running a bundle install will install the necessary dependencies. With those quick two steps, setup is complete! Now we can look at the code: Here, we are writing a spec for our PostgresqlManager class. We want to create DummyUsername user in our temporary database with the create_new_user method. Let’s put in an empty class with some basic parameters, so we don’t get errors. ### postgresql_manager.rb ### class PostgresqlManager def initialize(host, database, user, port) end end Here is our spec: ### postgresql_manager_spec.rb ### require "pg_tester" require "postgresql_manager" describe PostgresqlManager do ## create a local test DB psql = PgTester.new({ database: "testbuddy", user: "buddy", }) before(:each) do psql.setup end after(:each) do psql.teardown end subject { described_class.new(psql.host, psql.database, psql.user, psql.port) } describe "create_new_user" do context "testing create user method" do it "should create a new user" do subject.create_new_user("DummyUsername", "complexPassword") result = psql.exec "SELECT usename FROM pg_catalog.pg_user" expect(result.values).to include(["DummyUsername"]) end end end end In the above code sample, we create a PgTester instance, then create our subject PostgresqlManager class. In this example, we want to run psql.setup before each test in the context block. That will spin up our temporary database and tear it down afterwards by running psql.teardown. We run our create_new_user method then verify the user is created in PostgreSQL. We can run the above by doing bundle exec rspec. $ bundle exec rspec F Failures: 1) PostgresqlManager create_new_user testing create user method should create a new user Failure/Error: subject.create_new_user('DummyUsername', 'complexPassword') NoMethodError: undefined method 'create_new_user' for #<PostgresqlManager:0x007fcf3313eae8> # ./spec/postgresql_manager_spec.rb:20:in 'block (4 levels) in <top (required)>' Finished in 4.72 seconds (files took 0.50818 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/postgresql_manager_spec.rb:19 # PostgresqlManager create_new_user testing create user method should create a new user This will give us a failing test, citing that the create_new_user method does not exist. Let’s add a create_new_user method to our class. ### postgresql_manager.rb ### require "pg" class PostgresqlManager def initialize(host, database, user, port) @connection = PG::Connection.open(:host => host, :dbname => database, :user => user, :port => port) end def create_new_user(username, password) results = @connection.exec "CREATE ROLE #{username} WITH password '#{password}' LOGIN" @connection.close() end end We open a connection to our database via the pg gem in the initialize method whilst passing in arguments. This class is generic, so we can pass any database connection details. We are going to pass in our temporary database connection details for purposes of our test. The create_new_user method will issue a CREATE ROLE statement to create a new user with supplied credentials and LOGIN permissions.We then close our connection to the database. Let’s run our tests now: $ bundle exec rspec . Finished in 4.64 seconds (files took 0.49654 seconds to load) 1 example, 0 failures Hooray! Our tests pass! We’re really happy to release pg_tester to the Open Source community on the Microsoft Github. More examples and installation instructions can be found here: Neeran Gul is an engineer on the Production Engineering Team in the Yammer London Office and author of the pg_tester gem
http://engineeringjobs4u.co.uk/testing-postgresql-scripts-with-rspec-and-pg_tester
CC-MAIN-2019-22
refinedweb
808
50.02
Opened 4 years ago Closed 3 years ago Last modified 23 months ago #19774 closed Cleanup/optimization (fixed) contentypes generic module has core functionality plus admins-specific one Description (last modified by ) (Copied and adapted from) Consider a project with a foo and a bar apps listed on INSTALLED_APPS: foouses generic foreign keys, with the following models.py:() barhas a Sitemodel: from django.db import models class Site(models.Model): name = models.CharField(... # ... - Neither the admin nor sites Django apps are being used. This causes the user's Site model to be overridden and masked by Django sites framework's one. This is because the django/contrib/contenttypes/generic.py module contain both the definitions of the model-related generic stuff (GenericForeignKey, etc.) AND the admin app-related specialized inlines (GenericInlineModelAdmin, GenericStackedInline, GenericTabularInline.) Maybe it's time we move the latter ones from django.contrib.contenttypes.generic to, say, a new generic_admin (or admin_tools?) on django.contrib.contenttypes?. Of course this would need a deprecation process. Change History (15) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by comment:3 Changed 3 years ago by comment:4 Changed 3 years ago by comment:5 Changed 3 years ago by comment:6 Changed 3 years ago by @ramiro, I created a PR missing release notes and documentation adjustment. I'll try to work on it in the new few days but if you want to pick it up from here feel free to do it. comment:7 Changed 3 years ago by I adjusted the documentation and added a release note. The PR should be ready for review. comment:8 Changed 3 years ago by Looks good to me, I'm pretty happy with the forms.py, fields.py, admin.py split up. comment:9 Changed 3 years ago by Looks good to me; good idea to remove everything from that module and just deprecate the module, that's a lot simpler than the previous approach. I won't claim to have reviewed all the minor changes to docs and tests in detail, but I assume if you've run the tests and they are warning-free that that was all done correctly. Looks good to me! comment:10 Changed 3 years ago by (I did make a couple comments on wording of docs and error messages.) comment:11 Changed 3 years ago by Simon, I had some unfinished work in that direction and was a bit uncomfortable about still having the formset definition in the new fields module. Good call on creating forms.py Please go ahead, my review didn't find anything. As discussed on IRC with ramiro and loic splitting the genericmodule into fieldsand adminand deprecating the former should fix the issue. I couldn't reproduce the Sitecloaking with you described example against 1.6 and master. The only way I managed to reproduce is by having a sitesapp, just like it's described in #16368.
https://code.djangoproject.com/ticket/19774
CC-MAIN-2016-50
refinedweb
493
64.3
#include <rte_atomic.h> #include <rte_compat.h> #include 32 of file rte_stack.h. The stack uses lock-free push and pop functions. This flag is only supported on x86_64 or arm64 platforms, currently. Definition at line 94 of file rte_stack.h. Push several objects on the stack (MT-safe). Definition at line 112 of file rte_stack.h. Pop several objects from the stack (MT-safe). Definition at line 136 of file rte_stack.h. Return the number of used entries in a stack. Definition at line 156 of file rte_stack.h. Return the number of free entries in a stack. Definition at line 175.
https://doc.dpdk.org/api-20.11/rte__stack_8h.html
CC-MAIN-2021-39
refinedweb
102
72.73
Trie data structure Get FREE domain for 1st year and build your brand new site Reading time: 45 minutes | Coding time: 15 minutes A trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes), is a kind of search tree. Keys tend to be associated with leaves, though some inner nodes may correspond to keys of interest. Hence, keys are not necessarily associated with every node. For the space-optimized presentation of prefix tree, see compact prefix tree.. The figure depicts the basic structure of Trie. Algorithm Basic operations associated with Trie: Insertion of node in Trie: - Every character of input key is inserted as an individual Trie node. Note that the children is an array of pointers (or references) to next level trie nodes. - The key character acts as an index into the array children. - If the input key is new or an extension of existing key, we need to construct non-existing nodes of the key, and mark end of word for last node. - If the input key is prefix of existing key in Trie, we simply mark the last node of key as end of word. - The key length determines Trie depth. Searching a node in Trie - Searching for a key is similar to insert operation, however we only compare the characters and move down. - The search can terminate due to end of string or lack of key in trie. - In the former case, if the isEndofWord field of last node is true, then the key exists in trie. - In the second case, the search terminates without examining all the characters of key, since the key is not present in trie. Deletion of a node in Trie: When the current node that we are looking at is not the last node for key 'k', then 1. We first make a recursive call to delete the node which is child of the currentNode. 2. We check if child node was deleted in step #1. If child node was not deleted then child node must be shared with some other key which implies this currentNode is also part of some other key and hence we do not delete currentNode and return deletedSelf = false to the parent node. 3. After step #1, if child node was deleted then we check if this currentNode can be deleted. We check that using two conditions: (a) If this node is marked as a leaf node then this node must be the last node corresponding to some other key and hence we return deletedSelf = false without deleting currentNode. (b) If this node has any more children then that means this node is part of some other key as well and hence return deletedSelf = false without deleting currentNode. (c) If both conditions (a) and (b) evaluate to false then we know that this node can be safely deleted. We return deletedSelf = true by marking currentNode as null When we make currentNode = null for deleting the current node, current node won't be deleted since we are making only the local reference to the node as null. Note that this node still has got another reference in terms of parent node's child reference. To delete the node completely, what we do is once a child returns deletedSelf as true, we make child reference = null as well. Code for this is code snippet is - if (childDeleted) currentNode.children[getIndex(key.charAt(level))] = null; The figure depicts the searching of an element in a Trie. **The figure illustrates the insertion of an element in a Trie.** The figure illustrates the deletion of an element from a Trie. Complexity Worst case search time complexity: Θ(key_length) Average case search time complexity: Θ(key_length) Best case search time complexity: Θ(1) Worst case insertion time complexity: Θ(key_length) Worst case deletion time complexity: Θ(key_length) Worst case Space complexity: Θ(ALPHABET_SIZE * key_length * Number_of_keys) Pseudocode Searching boolean search(String s) { for(every char in String s) { if(child node is null) { return false; } } return true; } Insertion void insert(String s) { for(every char in string s) { if(child node belonging to current char is null) { child node=new Node(); } current_node=child_node; } } Deletion 1) If key 'k' is not present in trie, then we should not modify trie in any way. 2) If key 'k' is not a prefix nor a suffix of any other key and nodes of key 'k' are not part of any other key then: all the nodes starting from root node(excluding root node) to leaf node of key 'k' should be deleted. 3) If key 'k' is a prefix of some other key, then leaf node corresponding to key 'k' should be marked as 'not a leaf node'. No node should be deleted in this case. 4) If key 'k' is a suffix of some other key 'k1', then: all nodes of key 'k' which are not part of key 'k1' should be deleted. 5) If key 'k' is not a prefix nor a suffix of any other key but some nodes of key 'k' are shared with some other key 'k1', then: nodes of key 'k' which are not common to any other key should be deleted and shared nodes should be kept intact. Implementations - C++ C++ #include <iostream> // define character size #define CHAR_SIZE 128 // A Class representing a Trie node class Trie { public: bool isLeaf; Trie* character[CHAR_SIZE]; // Constructor Trie() { this->isLeaf = false; for (int i = 0; i < CHAR_SIZE; i++) this->character[i] = nullptr; } void insert(std::string); bool deletion(Trie*&, std::string); bool search(std::string); bool haveChildren(Trie const*); }; // Iterative function to insert a key in the Trie void Trie::insert(std::string key) { // start from root node Trie* curr = this; for (int i = 0; i < key.length(); i++) { // create a new node if path doesn't exists if (curr->character[key[i]] == nullptr) curr->character[key[i]] = new Trie(); // go to next node curr = curr->character[key[i]]; } // mark current node as leaf curr->isLeaf = true; } // Iterative function to search a key in Trie. It returns true // if the key is found in the Trie, else it returns false bool Trie::search(std::string key) { // return false if Trie is empty if (this == nullptr) return false; Trie* curr = this; for (int i = 0; i < key.length(); i++) { // go to next node curr = curr->character[key[i]]; // if string is invalid (reached end of path in Trie) if (curr == nullptr) return false; } // if current node is a leaf and we have reached the // end of the string, return true return curr->isLeaf; } // returns true if given node has any children bool Trie::haveChildren(Trie const* curr) { for (int i = 0; i < CHAR_SIZE; i++) if (curr->character[i]) return true; // child found return false; } // Recursive function to delete a key in the Trie bool Trie::deletion(Trie*& curr, std::string key) { // return if Trie is empty if (curr == nullptr) return false; // if we have not reached the end of the key if (key.length()) { // recurse for the node corresponding to next character in the key // and if it returns true, delete current node (if it is non-leaf) if (curr != nullptr && curr->character[key[0]] != nullptr && deletion(curr->character[key[0]], key.substr(1)) && curr->isLeaf == false) { if (!haveChildren(curr)) { delete curr; curr = nullptr; return true; } else { return false; } } } // if we have reached the end of the key if (key.length() == 0 && curr->isLeaf) { // if current node is a leaf node and don't have any children if (!haveChildren(curr)) { // delete current node delete curr; curr = nullptr; // delete non-leaf parent nodes return true; } // if current node is a leaf node and have children else { // mark current node as non-leaf node (DON'T DELETE IT) curr->isLeaf = false; // don't delete its parent nodes return false; } } return false; } // C++ implementation of Trie Data Structure - Insertion, Searching and Deletion int main() { Trie* head = new Trie(); head->insert("hello"); std::cout << head->search("hello") << " "; // print 1 head->insert("helloworld"); std::cout << head->search("helloworld") << " "; // print 1 std::cout << head->search("helll") << " "; // print 0 (Not found) head->insert("hell"); std::cout << head->search("hell") << " "; // print 1 head->insert("h"); std::cout << head->search("h"); // print 1 std::cout << std::endl; head->deletion(head, "hello"); std::cout << head->search("hello") << " "; // print 0 ("hello" deleted) std::cout << head->search("helloworld") << " "; // print 1 std::cout << head->search("hell"); // print 1 std::cout << std::endl; head->deletion(head, "h"); std::cout << head->search("h") << " "; // print 0 ("h" deleted) std::cout << head->search("hell") << " "; // print 1 std::cout << head->search("helloworld"); // print 1 std::cout << std::endl; head->deletion(head, "helloworld"); std::cout << head->search("helloworld") << " "; // print 0 ("helloworld" deleted) std::cout << head->search("hell") << " "; // print 1 head->deletion(head, "hell"); std::cout << head->search("hell"); // print 0 std::cout << std::endl; if (head == nullptr) std::cout << "Trie empty!!\n"; // Trie is empty now std::cout << head->search("hell"); // print 0 return 0; } Applications Importance of Trie:.
https://iq.opengenus.org/tries/
CC-MAIN-2021-43
refinedweb
1,497
59.47
Dist::Man - a simple starter kit for any module version 0.0.1 Nothing in here is meant for public consumption. Use pl-dist-man from the command line. pl-dist-man create --module=Foo::Bar,Foo::Bat \ --author="Andy Lester" --email=andy@petdance.com. (required) email => $email, # author's email address (required) verbose => $verbose, # bool: print progress messages; defaults to 0 force => $force # bool: overwrite existing files; defaults to 0 Dist::Man itself doesn't actually do anything. It must load plugins that implement create_distro and other methods. This is done by the class's import routine, which accepts a list of plugins to be loaded, in order. For more information, refer to Dist::Man::Plugin.> You can find documentation for this module with the perldoc command. perldoc Dist::Man You can also look for information at: FILL IN Please report any bugs or feature requests to bug-dist-man at rt.cpan.org, or through the web interface. Modified by Shlomi Fish, 2009 - all rights disclaimed - may be used under any of the present or future terms of Module-Starter.
http://search.cpan.org/~shlomif/Dist-Man-v0.0.4/lib/Dist/Man.pm
CC-MAIN-2017-09
refinedweb
182
58.38
Good clicklog datasets are hard to come by. Luckily CriteoLabs released a week’s worth of data — a whopping ~11GB! — for a new Kaggle contest. The task is to predict the click-through-rate for ads. We will use online machine learning with Vowpal Wabbit to beat the logistic regression benchmark and get a nr. 1 position on the leaderboard. Updates Demo with data from this contest added to Vowpal Wabbit. Now that this contest is over: Go here if you want to download the dataset freely made available by Criteo. The Winning team also won the following Avazu CTR prediction challenge and released Field-Aware Factorization Machines. Winning team used a mixture of Factorization Machines and GBRT. Code here. Highest scoring team using Vowpal Wabbit was Guocong Song for 3rd place. Method and code here. In short: Multiple models, polynomial learning and featuremasks. Highest scoring team using this benchmark (and cubic features) was Silogram for 14th place. Our team got 29th place out of 718 competing teams. tinrtgu posted a very cool benchmark on the forums that uses only standard Python libraries and under 200MB of memory. Now is your chance to play around with online learning, the hash trick, adaptive learning and logistic loss and get a score of ~0.46902 on the public leaderboard. FastML wrote a blog about this competition with some tips to improve this benchmark. The competition of optimizing online advertisements with machine learning is like strawberries with chocolate and vanilla: You have large amounts of data, an almost endless variety of features to engineer, and profitable patterns waiting to be discovered. Identifying (and serving) those ads that have a higher probability of a click, translates into more profit and a higher quality: - More profit, because in most online advertisement networks, advertisers are only charged when a user clicks on their ads. - A higher quality, because higher Click-Through-Rates (CTR) implies more relevant advertising (giving a user what he/she wants). Behavioral Retargeting Behavorial retargeting is a form of online advertising where the advertisements are targeted according to previous user behavior, often in the case where a visit did not result in a sale or conversion. ROI Like Kagglers may try to optimize AUC (Area under Curve) , online advertisers generally aim to optimize Return on Investment (ROI). Return on Investment = Net profit / investment Optimizing this formula may be done by: - keeping the investment low, for example by looking for cheap, but effective marketing opportunities. - increasing net profits, for example by optimizing the conversion ratio (the amount of web users that turn into paying customers). Behavioral retargeting can increase ROI through: - Lowering investment. The networks on which to serve the retargeted ads are usually cheaper than the market average. - Increasing profit. Shopping cart abandonment is a real problem for online retailers. These customers were lost in the latest stages of the conversion chain. Retargeting with products catered to the user wins a certain percentage of them back. Criteo Criteo is a retargeting company working together with online retailers to serve online advertisements. Prediction engine One of the core products of Criteo is a prediction engine. The engine is capable of predicting effective personalized advertisements on a web scale: real-time optimization of ad campaigns, click-through rates and conversion. For this prediction engine they are always looking for ways to engineer new informative features. Behavioral features A] Show us the data! For this contest Criteo’s R&D division, CriteoLabs, has released a week’s worth of click data. CriteoLabs is one of the biggest European R&D divisions with a focus on predictive advertising. The train set has 45.840.616 labelled ads (click-through “1” or not “0”). The test set has 6.042.135 unlabelled ads. Both sets are sampled to have a near even distribution of clicks and non-clicks. We have 13 columns of integer features (mostly count features), and 26 columns with hashed categorical features. Though the exact nature of the features is unknown to us, according to a competition admin (Olivier Chapelle), they fall in the following categories: - Publisher features, such as the domain of the url where the ad was displayed; - Advertiser features (advertiser id, type of products,…) - User features, for instance browser type; - Interaction of the user with the advertiser, such as the number of the times the user visited the advertiser website. Our task now is to create a model that will predict the probability of a click. Online Machine Learning with VW I think that sticking with your favorite machine learning tool or algorithm for all classification and regression problems, is like picking a chess opening and only playing that against all opponents. You can get lucky and pick a solid opening that will do well most of the times, or you are stuck with a quirky, outdated, or peculiar opening. Vowpal Wabbit is how Elmer Fudd would pronounce Vorpal Rabbit. I picture the Killer Rabbit of Caerbannog brandishing a +5 vorpal sword. It would give any player an unfair advantage if they found it early on in the game. One, two! One, two! And through and through. The vorpal blade went snicker-snack!He left it dead, and with its head he went galumphing back. — Jabberwocky If you follow my blogs, you’ll know that I’ve tried Vowpal Wabbit on many Kaggle competitions. It won’t perform the best on all competitions, though it will perform in most (Multiclass Classification, Regression, online LDA, Matrix Factorization, Structured Prediction, Neural network reduction, Feature interactions), and is a robust addition to many ensembles. This competition is made for fast online machine learning (with Vowpal Wabbit or Sofia-ML). Models may quickly become outdated, so will probably constantly need to be retrained (we need fast convergence). The collected click data is huge (often far larger than fits into memory) or unbounded (you may constantly collect new categorical feature values). For a deeper understanding of large scale online machine learning watch this fine video tutorial with John Langford. I can also suggest this relevant seminal paper “A Reliable Effective Terascale Linear Learning System“, where one of the authors is a competition admin. Picking a loss function Online machine learning with VW learns from samples one at a time. When your model is trained it iterates through the train dataset and optimizes a loss function. Vowpal Wabbit has five loss functions: - Squared loss. Useful for regression problems, when minimizing expectation. For example: Expected return on a stock. - Classic loss. Vanilla squared loss (without the importance weight aware update). - Quantile loss. Useful for regression problems, for example: predicting house pricing. - Hinge loss. Useful for classification problems, minimizing the yes/no question (closest 0-1 approximation). For example: Keyword_tag or not. - Log loss. Useful for classification problems, minimizer = probability, for example: Probability of click on ad. Without seeing the evaluation page of the competition our hunch should be to pick logaritmic loss. That the competition metric really is logaritmic loss means we gain a massive amount of information even by training a model with Vowpal Wabbit: With its holdout functionality one-in-ten samples will be used to calculate and report on the average loss. Vowpal Wabbit is fast with its compiled C++ code, but also because it employs the hashing trick. Our feature space is now fixed to a number of bits. We do not need a lookup table in memory to convert text or categorical values into numerical features. Munging We are going to munge the CSV train and test set to Vowpal Wabbit files (VW files). For this I wrote a Python script csv_to_vw.py. There are no features to engineer, so we will just put the provided numerical and categorical features neatly into their own namespaces. A single line from the resulting VW train set (~12GB) now looks like: -1 '10000000 |i I9:181 I8:2 I1:1 I3:5 I2:1 I5:1382 I4:0 I7:15 I6:4 I11:2 I10:1 I13:2 |c 21ddcdc9 f54016b9 2824a5f6 37c9c164 b2cb9c98 a8cd5504 e5ba7672 891b62e7 8ba8b39a 1adce6ef a73ee510 1f89b562 fb936136 80e26c9b 68fd1e64 de7995b8 7e0ccccf 25c83c98 7b4723c4 3a171ecb b1252a9d 07b5194c 9727dd16 c5c50484 e8b83407 Where -1 means “no click”. '10000000 is the ID. |i is the namespace with the numerical features and |c contains the categorical features. The test set should look similar. Training We then train the model with the following command: ./vw -d click.train.vw -f click.model.vw --loss_function logistic Where -d click.train.vw says to use our train dataset. -f click.model.vw saves the model. --loss_function logistic is setting our loss function. This runs a single pass over the train dataset. Vowpal Wabbit 7.6.1 reports back an average loss of 0.473238. Certainly not the best possible with VW, but a promising start. Testing and submitting We are now ready to predict CTR on ~6 million advertisements from the test set. In Vowpal Wabbit we can do this with: ./vw -d click.test.vw -t -i click.model.vw -p click.preds.txt Where -t says to test only, -i click.model.vw specifies the input model and -p saves our predictions. (Edit: Thanks to Anuj for spotting that I forgot to specify the model when testing, code above updated.) After running the above command we should have our predictions in a text file (~100MB). We now want to turn these into probabilities (using a sigmoid function) and submit them to Kaggle in CSV format. You could use the provided script vw_to_kaggle.py to do this. The submission scores 0.48059 on public leaderboard which is good enough to beat the benchmark and at the time of writing will net you a second place. Code All code is available on the MLWave Github account. Improvements and feedback always welcome. Conclusion The process for creating baseline benchmark was: - All the features were encoded as sparse binary (standard “one hot” encoding); - To reduce the dimensionality, the features that took more than 10,000 different values on the training set were discarded; - The learning algorithm was linear logistic regression optimized with l-bfgs; - The regularization coefficient was set to 1. We beat the logistic regression benchmark with our first submission. Vowpal Wabbit truly is an industry-ready tool for machine learning on large and high dimensional datasets. Now the fun part starts: to optimize the parameters (BTW: Vowpal Wabbit has a utility script for this). Aim for the lowest average logistic loss on your own laptop and produce real business value. Also as the models increase in complexity, so do their training times. For now we were able to keep the munging, training and predicting under 1 hour. Acknowledgements I’d like to thank Kaggle for hosting the competition and Criteo for sharing this amazing dataset. FastML for introducing Vowpal Wabbit to my game. And of course all the authors of Vowpal Wabbit, by name its principal developer: John Langford. In particular I’d like to thank the Kaggle competitors. When not providing tips on the forums, you are after my leaderboard scores. I know I will probably not be #1 for much longer and I predict that it will only make me work harder, better, faster. 34 thoughts on “Predicting CTR with online machine learning” Hi, I am trying to predict CTR from set of 18 features much similar to Criteo’s CTR Prediction contest on kaggle. The data given on kaggle is sampled so that number of 1s (Clicked = True) and 0s (Clicked = False) are almost equal. However, the data I am using contains impression an click data for one day with around 0.4% CTR (i.e 4 out of 1000 1s and rest 0s). I wanted to ask whether such sampling is compulsory for good prediction? If sampling is necessary, how do I proceed so that I do not loose any pattern. Also, what is a good evaluation metrics for such a data set? P.S. : I have tried logistic regression using scikit learn and got poor results. However, after sampling the results were a little better but still not satisfactory. Thanks, Hi Anuj, Class imbalance problems are a tricky problems in machine learning. Convergence to a good-enough solution can be a troublesome task for many algo’s, especially when with online learning the order of labeled samples matters. Sub-sampling is often possible and eases the entire process, and the results. For VW somthing quite similar can be achieved using sample weights / sample importance. You can add a weight after the label, omit weight and it is assumed to be 1: -1 ‘very_common |f happens all the time 1 50 ‘rare_anomaly |f rare thus 50x importance This way one keeps all the data in train set (avoid subsampling majority class), while adjusting the importance of learning from the minority class. Evaluation metric also depends on the problem context itself (for example: do you care about the negative class? do you want probability estimates, ranks or 0-1 classification? Do you care about false positives?). Some metrics can be deceiving when you have a huge class imbalance, like accuracy or AUC. Never predicting the minority class can give scores of 0.99+. This leaves the learning algo little room for improvement. For Kaggle contests with imbalanced data I’ve seen metrics like mean squared error and log loss (log loss is used in this competition, so if you say your problem is similar, I’d research that). Thanks, that will be very helpful. However, I thought first I should play with the ‘nicely sampled’ criteo dataset and then move to my data. So, I am starting with VW itself. I am curious that how does the statement for testing: ./vw -d click.test.vw -t -p click.preds.txt know what model to use for predicting? I am beginner in ML and VW, so excuse me if I have missed something very obvious. P.S. : I have used this with the 12GB criteo train set and I am getting all 0s while predicting with test set and corresponding probability as 0.5 Thanks ./vw -d click.test.vw -t -p click.preds.txt for testing is incorrect. You indeed need to specify the model to use: ./vw -d click.test.vw -t -i click.model.vw -p click.preds.txt -i for input_model. If you are trying this Criteo challenge with VW, just follow along with the benchmark tutorial. It should give probabilities after running the output from VW through a sigmoid function. Good luck! Thanks a lot. You should change the code for testing in the post also. Thank you! I see now I simply forgot to add that in the article under testing. I updated it. Let me know if you spot anything else like this. I will go back to testing all commands before posting :). Hey, Thanks for the entire model, it works fine. How did u calculate the overall score . The overall score is different from the individual probabilities I am new to large data set, can you please tell me how to use R or Python along with code. Nope, that is not going to happen. Check the forums, maybe someone posts code for R or batch fitting in Python scikit-learn. Someone posted Python code to get a very good score: Beat the benchmark with less then 200MB of memory. It only uses Python and standard libraries to get a score around 0.469. Thanks a lot for making your code open. Its a terrific way for people like me appreciate the wonder that is vowpal wabbit. In your code for generating csv to vw, the categorical variables are all clumped together i.e you do not make a disinction between C1 and C15 but rather treat all of them as tokens. Am i correct in this interpretation. Why does this matter. As you can see here A variable like C9 which takes only 3 values is giving us some additional information than being tagged with everything else. Thanks again Yes, that is the correct interpretation. I basically lump all these categorical values together as a bag of tokens. Note that this is not the soundest way. Kaggler Foxtrot over at FastML has written an article about encoding the categorical features in a correct manner: For some unknown reason my wonky way works a bit better than the “right” way as proposed in the FastML article. Good luck! Thanks for the introduction to vowpal wabbit. What do you recommend for tuning. Also how do you call vw-varinfo or top errors. I prepended the command, and I keep on getting command not found I don’t think ./vw is in your PATH (so you can call it from any directory). Probably the easiest would be to copy the script from /utl/ to the directory where the ./vw executable resides. Then run it from that directory. For tuning there is vw-hypersearch and the almighty hunch. What a great site! I am curious your background – have you formally studied ML? I had a quick question on VW if you dont mind. I am trying to wrap my head around it. Lets say that we have a (silly) data set with 3 features. 1) State (one of the 50 American states) 2) Weather (three possible values: cloudy, sunny, raining) 3) Message (a text string/document) If you set up your input as (the first example record with a value of 1 for the target variable): 1 |state newyork |weather cloudy |message This is my first VW attempt Will VW perform in effect a bag-of-words representation on ‘message’, while seeing ‘state’ and ‘weather’ has being categorical variables that are self contained? Finally, if we use -q stateweatherwill VW create an interaction between state and weather? While if we used -q messagemessagewill VW create interactions between every column in the bag of words representation of message (which would be somewhat nonsensical, but I am just wondering if I understand this yet)? Thanks so much if you can provide any clarity! I have not formally studied ML, unless you count the university of Kaggle :). Yes. I am not 100% sure about using full strings for namespaces (ambiguity), so Ill substitute them with the first letter. 1 |s newyork:1 |w cloudy:1 |m This:1 is:1 my:1 first:1 VW:1 attempt:1 You could do -q swto create a newyork*cloudyfeature interaction. You could do --ngram m3to create 3-grams from the messages. -q mmwould create q-grams on the message (this would include 2-grams, but also 2-grams with all the --nskips). --cubic mmmWould create all 3-grams, but also all other cubic feature interactions. By that point you probably want a huge -bbitsize and regularization. I think you are indeed close to understanding it (or at least, understanding it better than I do). Thats great! One question, did you mean to say “would create q-grams on the message” or 2-grams? I assume that -q is not the order of the gram. q-gram is a fancy word I just made up. -q is not the order of the gram, as I understand it, every possible feature interaction is created. 1 ‘notsure |f i give up with -q ff would give: 2grams i*give, give*up, but also i*up (can be seen as 2gram with 1-skip). I dont know if -q also generates the reverse: give*i, up*give. I think so. If you find that out you already understand better than me :). I would hope that both i*give and give*i would not be included! I am not sure :). Since I can’t find this in the documentation it will probably be a perfect question to ask on the mailing list. Or use vw-varinfo and -q on a simple dataset to see what features are used by the model. Maybe I’ll collect a bunch of these questions (I have a few more) and make a single post for this. That way we won’t distract Langford (or Faigon) too much when he is busy conning multi-armed bandits :). A small test seems to confirm that VW does create both a*b and b*a in the interactions. I wonder if that is a bug? I cant think why you would want that redundancy and what it means for things like matrix factorization. I don’t think it’s a bug. With VW it is always a feature :). Quadratic or feature^2 would indeed mean all the combinations. Thank you for the test though as it confirms my intuition about “q-grams”. If it only created half a matrix of interactions, then information about word/token order would get lost: “is not” and “not is” would have the same interaction and no way for the model to distinguish. If I knew more about the hashing trick then this might make more sense to me. I think of it in terms of one-hot-encoding / bag of words model where is*not and not*is is the same thing. Generally for combinations of categories, you would not want repeated features like this. I think about factorization models (user / movie interactions) – and again think user1*movie1 and movie1*user1 is redundant. But maybe the hashing trick makes this different? Thought you may be interested: I am curious about this, how is such a model used- do you know? Would the various options (values of the variables) be run through the model to see for a given individual, should we give then ad 1 or ad2 or ad3 or……adN? Given then = Give Them I am not sure (keep this in mind), but I’ll hazard a guess. For ads, latency is important: You get a few milliseconds to start serving relevant ads. So probably it is a fast (linear) model which replies with an ad id in response to some variables. There are also ad auctions: companies can make a bid on a certain ad space. They get milliseconds to reply with a bid and when they win, they get to serve their ad. Also, with CTR models, concept drift is a big thing: Models get stale fast, and need to be retrained at least every day, maybe even every hour, or real-time. I also suspect some caching going on: Your computer or profile gets a unique ID. In response to this ID an ad is served. These ads could be pre-selected (so a different form of testing: it has already calculated the relevant ads for your user ID, and only needs this ID to serve you personalized ads). Great hazarded guess! 🙂 So such a model, in your thinking is used to simulate options and essentially take the argmax = which ad choice that could be presented is predicted to offer the highest CTR? Yes, basically. Or maybe there is hierarchical sequential modelling goin on? Very simple models first divide the ads: if male then [list_of_ads], then a more complex (still linear, or GBRT) does the testing on 100-1000 ads and you select the ad with argmax (probability of click). Langford does logarithmic time prediction: Also this Quora QA with Facebook Applied ML Director was relevant: Hi, you mention featuremasks? I have tried to find out what this means exactly but it makes very little sense to me for this case. Would you be able to explain what this is or post a link which might help explain this? Many thanks for such a great resource! vw -d data.vw --l1 0.001 -f features.model vw -d data.vw -i features.model --feature_mask features.model -f final.model You use L1-regularization from a simple model to find the features that do not contribute any (or just a tiny amount of) signal. Then you use this as a mask for another model. This other model will ignore the meaningless / noisy features found by the first model.
https://mlwave.com/predicting-click-through-rates-with-online-machine-learning/?replytocom=276839
CC-MAIN-2021-17
refinedweb
3,996
65.52
From: JOAQUIN LOPEZ MU?Z (joaquin_at_[hidden]) Date: 2007-06-14 17:16:04 ----- Mensaje original ----- De: Eric Niebler <eric_at_[hidden]> Fecha: Jueves, Junio 14, 2007 10:57 pm Asunto: Re: [boost] Unnamed namespaces? Para: boost_at_[hidden] > David Abrahams wrote: > > on Thu Jun 14 2007, Eric Niebler <eric-AT-boost-consulting.com> > wrote:> > >> template<typename T> struct static_const > >> { > >> static T const value; > >> }; > >> > >> template<typename T> > >> T const static_const<T>::value = {}; > >> > >> struct placeholder {}; > >> > >> // This is *supposed* to be statically initialized but many > >> // compilers do dynamic initialization for it. :-( > >> placeholder const &_1 = static_const<placeholder>::value; > > > > I thought it was just MSVC. Any others? > > Shoot, now I can't remember. How many did we test? Well, this much > is certain, there is at least one compiler that does dynamic > initialization > for it. :-/ > > I also seem to recall that there was still some question as to > whether the use of the reference violated the ODR, if the > reference is not optimized away. I don't think we ever got an > answer to that question. Maybe the following is not relevant to the discussion, but I recall a post by Anthony Williams which shows how to create a _1-like global entity in an entirely ODR-abiding way:
https://lists.boost.org/Archives/boost/2007/06/123373.php
CC-MAIN-2020-29
refinedweb
203
54.83
This does not happen on a fresh project. However on several of our web projects (imported with an existing sources, using shared libraries), the following sequence hangs the project: 1) Project properties > Libraries 2) click Add Library 3) click Import 4) select a library, say Absolute Layout 5) click Import library, the Import library window closes but the IDE hangs The IDE hangs. I can move the "Add Library" window and it redraws, but the IDE is frozen. The folder "absolutelayout" was created but nothing else. (Also happens on Windows XP) Removing all .svn directories from the project seems to help. Also deleting the whole content of the src folder helps. Not that either of them is a possible work around. Could you please attach thread dump? Created attachment 73303 [details] Thread Dump Following, I am setting priority to P1. Not sure if I understand the reproducibility correctly. If it happens for a project, it happens always for that project. But it does not happen for every projects. Subversion is somehow involved. P2. Could you please provide further information. What kind of project is that? ()j2e, web ...), please also attach messages.log it is a web project, with existing sources created in jdeveloper, the shared library folder is under WEB-INF. I will attach message log tomorrow, when I get to that particular machine (I assume you want the message.log created at the same time as the thread dump). Is there any workaround? Yes, the messages.log in which you've run into the issue. I've just tried the latest build of NB 6.5 for web project (standard and with existing sources) and I can't reproduce it. Any further details you could provide? Any chance to get your project? Further questions: 1. If the problem occurs, does the IDE hang or it finishes in reasonable time? 2. If the problem occurs, could you please do and attach more thread dumps? a) could reproduce with 6.5 - the shared lib folder has to be web-inf - create webapp - add library -> import -> ... b) couldn't reproduce with a trunk build possible workaround would be to deactivate the svn module for the time when setting up the libraries - main menu > tools > plugins > installed > ... To put libraries into WEB-INF is corner case and workaround exists. P2. Fix should be integrated into 65 PATCH1. It looks like you can reproduce it. Do you still want me to provide any further information? So it looks if we move the shared lib folder out of web-inf we should be fine. > It looks like you can reproduce it. Do you still want me to provide any further information? thanks. we are fine for now. fixed in trunk changeset: 107778:42ba13d42061 tag: tip user: Tomas Stupka <tstupka@netbeans.org> date: Wed Nov 12 14:27:31 2008 +0100 summary: #152354 - Freezes when trying to import a library Please verify this issue so it can be included in NetBeans 6.5 Patch1 Unfortunatelly trunk build (18.11) still does not work (even with new subversion jar which fixed it in previous version). Reproduction (nothing changed): create new web application import project into svn repository trying to add a library into project freezes IDE (right when I press Finish button) The same result was with new subversion jar, which seemed to fix this problem in previous versions, copied into modules folder. Then IDE auto-updated itself (found update for subversion module: updated from 1.4.1 to 1.5...), but the result remained the same. I will also add messages.log. Cannot mark this issue as verified, recommend to reopen. sys info: Product Version: NetBeans IDE Dev (Build 200811181401) Java: 1.6.0_10; Java HotSpot(TM) Client VM 11.0-b15 System: Linux version 2.6.24-21-generic running on i386; UTF-8; en_US (nb) Created attachment 73900 [details] messages.log file attach a threaddump please Created attachment 73913 [details] stack/thread dump my fault. changes weren't pushed yet. just try again ... Integrated into 'main-golden', will be available in build *200811200201* on (upload may still be in progress) Changeset: User: Tomas Stupka <tstupka@netbeans.org> Log: #152354 - Freezes when trying to import a library The issue didn't pass the nomination process by nomination cut-off date. It has been marked as 65fixes2-candidate. Verified in trunk. The changeset has been transplanted into release65_fixes repository as Verified.
https://netbeans.org/bugzilla/show_bug.cgi?format=multiple&amp;id=152354
CC-MAIN-2019-43
refinedweb
735
68.77
Break up the blocked_list into a hashtable, using the fl_owner as a key. This speeds up searching the hash chains, which is especially significant for deadlock detection. Note that the initial implementation assumes that hashing on fl_owner is sufficient. In most cases it should be, with the notable exception being server-side lockd, which compares ownership using a tuple of the nlm_host and the pid sent in the lock request. So, this may degrade to a single hash bucket when you only have a single NFS client. That will be addressed in a later patch. The careful observer may note that this patch leaves the file_lock_list alone. There's much less of a case for turning the file_lock_list into a hashtable. The only user of that list is the code that generates /proc/locks, and it always walks the entire list. Signed-off-by: Jeff Layton <jlayton redhat com> Acked-by: J. Bruce Fields <bfields fieldses org> --- fs/locks.c | 25 +++++++++++++++++-------- 1 files changed, 17 insertions(+), 8 deletions(-) diff --git a/fs/locks.c b/fs/locks.c index 32826ed..d93b291 100644 --- a/fs/locks.c +++ b/fs/locks.c @@ -126,6 +126,7 @@ #include <linux/time.h> #include <linux/rcupdate.h> #include <linux/pid_namespace.h> +#include <linux/hashtable.h> #include <asm/uaccess.h> @@ -160,12 +161,20 @@ int lease_break_time = 45; static HLIST_HEAD(file_lock_list); /* - * The blocked_list is used to find POSIX lock loops for deadlock detection. - * Protected by file_lock_lock. + * The blocked_hash is used to find POSIX lock loops for deadlock detection. + * It is protected by file_lock_lock. + * + * We hash locks by lockowner in order to optimize searching for the lock a + * particular lockowner is waiting on. + * + * FIXME: make this value scale via some heuristic? We generally will want more + * buckets when we have more lockowners holding locks, but that's a little + * difficult to determine without knowing what the workload will look like. */ -static HLIST_HEAD(blocked_list); +#define BLOCKED_HASH_BITS 7 +static DEFINE_HASHTABLE(blocked_hash, BLOCKED_HASH_BITS); -/* Protects the two list heads above, and fl->fl_block list. */ +/* Protects the file_lock_list, the blocked_hash and fl->fl_block list */ static DEFINE_SPINLOCK(file_lock_lock); static struct kmem_cache *filelock_cache __read_mostly; @@ -499,13 +508,13 @@ locks_delete_global_locks(struct file_lock *waiter) static inline void locks_insert_global_blocked(struct file_lock *waiter) { - hlist_add_head(&waiter->fl_link, &blocked_list); + hash_add(blocked_hash, &waiter->fl_link, (unsigned long)waiter->fl_owner); } static inline void locks_delete_global_blocked(struct file_lock *waiter) { - hlist_del_init(&waiter->fl_link); + hash_del(&waiter->fl_link); } /* Remove waiter from blocker's block list. @@ -730,7 +739,7 @@ static struct file_lock *what_owner_is_waiting_for(struct file_lock *block_fl) { struct file_lock *fl; - hlist_for_each_entry(fl, &blocked_list, fl_link) { + hash_for_each_possible(blocked_hash, fl, fl_link, (unsigned long)block_fl->fl_owner) { if (posix_same_owner(fl, block_fl)) return fl->fl_next; } @@ -866,7 +875,7 @@ static int __posix_lock_file(struct inode *inode, struct file_lock *request, str /* * New lock request. Walk all POSIX locks and look for conflicts. If * there are any, either return error or put the request on the - * blocker's list of waiters and the global blocked_list. + * blocker's list of waiters and the global blocked_hash. */ if (request->fl_type != F_UNLCK) { for_each_lock(inode, before) { -- 1.7.1
https://www.redhat.com/archives/cluster-devel/2013-June/msg00139.html
CC-MAIN-2014-15
refinedweb
495
58.58
How To Port Python 2 Code to Python 3 Introduction Python was developed in the late 1980s and first published in 1991. With a name inspired by the British comedy group Monty Python, Python was conceived as a successor to the imperative general-purpose ABC programming language. In its first iteration, Python already included exception handling, functions, and classes with inheritance. This tutorial will guide you through best practices and considerations to make when migrating code from Python 2 to Python 3 and whether you should maintain code that is compatible with both versions. Background Python 2 was published in 2000, signalling a more transparent and inclusive language development process. It included many more programmatic features and added more features throughout its development. Python 3 is regarded as the future of Python and is the version of the language that is currently in development. Released in late 2008, Python 3 addressed and amended intrinsic design flaws. However, Python 3 adoption has been slow due to the language not being backwards compatible with Python 2. Python 2.7 was published in 2010 as the last of the 2.x releases. The intention behind Python 2.7 was to make it easier for Python 2.x users to port features over to Python 3 by providing some measure of compatibility between the two. You can learn more about Python versions and choosing which to use by reading our tutorial “Python 2 vs Python 3: Practical Considerations.” bux. print: from __future__ import division Read more about division with integers. raise In Python 3, raising exceptions with arguments requires parentheses, and strings cannot be used as exceptions. except. String Formatting String formatting syntax has changed from Python 2 to Python 3. Learn How To Use String Formatters in Python 3. class There is no need to state object in Python 3. Python 2 class MyClass(object): pass Python 3 class MyClass: pass In Python 3, metaclasses are set with the metaclass keyword. Python 2 class MyClass: __metaclass__ = MyMeta class MyClass(MyBase): __metaclass__ = MyMeta Python 3 class MyClass(metaclass=type): pass class MyClass(MyBase, metaclass=MyMeta): pass Update Code There are two main tools you can use to automatically update your code to Python 3 while keeping it compatible with Python 2: future and modernize. Each of these tools behaves somewhat differently: future works to make Python 3 idioms and best practices exist in Python 2, while modernize aims for a Python 2/3 subset of Python that uses the Python six module to improve compatibility. Using these tools to handle the details of rewriting the code can help you identify and correct potential problems and ambiguities. You can run the tool over your unittest suite to visually inspect and verify the code, and ensure that the automatic revisions made are accurate. Once the tests pass, you can transform your code. From here, you will likely need to do some manual revision, especially targeting the changes between Python 2 and 3 noted in the section above. Leveraging future, you should consider adding this import statement to each of your Python 2.7 modules: from __future__ import print_function, division, absolute_imports, unicode_literals While this will also lead to rewrites, it will ensure that your Python 2 code aligns with Python 3 syntax. Finally, you can use the pylint package to identify any other potential issues in the code. This package contains hundreds of individual rules that cover a broad spectrum of problems that may occur, including PEP 8 style guide rules, as well as usage errors. You may find that there are some constructs in your code that could potentially confuse pylint and tools used for automatic migration. If you can’t simplify these constructs, you’ll need to employ thorough unittest cases. Continuous Integration If you’re going to maintain your code for multiple versions of Python, you’ll need to remain vigilant about running and re-running your unittest suite through continuous integration (rather than manually) as often as possible on the code as you develop it. If you make use of the six package as part of your Python 2 and 3 compatibility maintenance, you’ll need to use multiple environments for your testing. One environment management tool you may consider using is the tox package, as it will check your package installs with different Python versions, run tests in each of your environments, and act as a frontend to Continuous Integration servers.. It is worthwhile to look at projects that ported Python 2 to Python 3, including case studies such as Porting chardet to Python 3. 2 Comments
https://www.digitalocean.com/community/tutorials/how-to-port-python-2-code-to-python-3
CC-MAIN-2017-30
refinedweb
765
58.92
>> :damned faintly praising? (Score:5, Informative) Is picking a worse random number generation function (the default one in C and JS) really fucking up? And btw, it looks like their choice promotes all other browsers than IE almost 2x more! Position I.E. Firefox Opera Chrome Safari 1 1304 2099 2132 2595 1870 2 1325 2161 2036 2565 1913 3 1105 2244 1374 3679 1598 4 1232 2248 1916 590 4014 5 5034 1248 2542 571 605 I can already see all the comments how MS would be favoring IE with this (summary conveniently left that one out), but as it is they're promoting the other browsers almost double more., Informative) Yes, indeed, you've hit the nail on the head. A very sloppy shallow unworkmanlike solution to a very high profile legal issue. Almost as clever as the 'messing up pages shown to Opera' issue, though I suspect that that was deliberate and this not. Rgds Damon:5, Informative) The relevant code is in their Javascript: [browserchoice.eu] aBrowserOrderTop5.sort(RandomSort); (they repeat this twice for some reason) ... function RandomSort (a,b) { return (0.5 - Math.random()); } This takes the browser's built-in sorting function, tells it to sort by an essentially random criteria, and hopes that it all works out. Unfortunately, this is highly dependent on the implementation of the built-in sort function, and that's up to the browser designer to create. The only constraint on the structure of sort is that it must successfully order comprehensible data, which does not mean that it will properly randomize data when provided. Essentially, they overloaded a black-box function that wasn't designed for randomization in the hopes that it would work. For an instance of why this wouldn't work, consider the case of the last item. Say that you're sorting a list of 5 letters. Now say that you're most of the way through the list, having properly sorted the first 4 letters into "A, B, D, E", with just the 5th letter C left. So you step through. Does C come before E? Yes. Does C come before D? Yes. Does C come before B? No. C must go between B and D, and the list will look like "A , B , C , D , E." It will be sorted correctly every time. Now let's throw that randomization into the middle there. Let's start again with the list, though since we're randomizing let's call them item 1, 2, 3, and 4. If we're properly randomly sorting the last item 5 into the list, it should have equal chances of showing up everywhere. But remember, we're still using the sorting algorithm from above, we're just flipping a coin at each question instead of actually comparing. So what we get is: Does 5 come before 4? 50% yes, or stop Does 5 come before 3? 50% yes, or stop Does 5 come before 2? 50% yes, or stop etc. But because it's iterative, those 50% chances stack. You only get to the second question half of the time, so you only get to the third question half of that half of the time. And essentially what you wind up with is a % chance of the last number being sorted into each of the slots as: 3%, 6%, 12%, 25%, 50%. This is obviously not a random distribution curve. This is not necessarily the sort algorithm that Microsoft uses in I.E. (The 50% chance of staying as the last element is a bit suspicious, though, as is running their code twice). But it does point out unequivocably that you can't overload an off-the-shelf sort algorithm with a randomizing comparator and expect the outcome to follow a genuinely random distribution curve. They really ought to have an in-house random sort algorithm that their developers can pull from. (Thanks to another poster for finding the first google hit [slashdot.org] that describes this method.).:3, Informative) The default rand(3) in C doesn't have to suck -- it doesn't on Linux or the BSDs. I see no evidence that it does in *any* major systems today, though apparently it did back in the 1980s when it got that reputation.: (Score:3, Informative) It's not an issue of how to get a truly random number, or of seeding a random number generator, but rather how to you use a source of random numbers to randomly order a list. Some "reasonable sounding" methods don't actually work - e.g. attach random numbers to each list item and sort the list by these numbers (1). Microsoft used a similar method of sorting using a random comparator. Some simple methods that DO work are picking a random permutation or executing a bunch of random swap operations on the list. ..") Re:What? Why not? (Score:5, Informative) What the problem actually seems to be is not that they're using random, but how they're using it. What they essentially did was use something like qsort() to sort the list, but in their comparator function, instead of returning which of the two strings comes first, they return some random crap instead. qsort() or whatever they used was designed to have results that are consistent, and with input like that it could potentially abort and leave the list entirely unsorted. Or if you're really unlucky it could sit there sorting them forever. Re: ... Re: (Score:2, Informative) Out of curiosity - why would they need to seed the random number generator? Wouldn't -not- seeding it be better? I can't speak for Javascript but in most C libraries - at least in the DOS era when I last made this mistake - the library would default to a static seed of its own during program initialisation, probably 0 or something. As a result, if you made a program that started, output 15 random numbers and then quit, each time you ran it you would get the same 15 numbers.) Re:Good enough (Score:4, Informative) Given that each user is only going to see this screen once per computer, I'd say simply using the seconds of the current minute as a random seed should be OK This problem has nothing to do with how the PRNG is seeded. The word "seed" doesn't even appear in TFA at all. Re.
http://developers.slashdot.org/story/10/02/28/1837223/schooling-microsoft-on-random-browser-selection
CC-MAIN-2013-20
refinedweb
1,071
70.63
RECOMMENDED: If you have Windows errors then we strongly recommend that you download and run this (Windows) Repair Tool. "The vulnerability is caused due to an unspecified error when using the Adobe Flash Player plug. In the recent period, the battle for the most powerful browser was involving only Internet Explorer and Firefox, a lot of users considering. Frustrated Windows 10 users have reported the issue on an old Microsoft. After that, the CMS said it was withholding about one-third of the data for unspecified reasons. The e-mail announcing the downtime said visitors should use Internet Explorer versions 8-10 in accessing the website, and that it is “not. SCRIPT16389 unspecified error when loading large set of hi. – SCRIPT16389 unspecified error when loading large set of hi. unspecified error as well on a page with. IE DC no longer output error in the console as seen in. Canon Mp480 Error 2 140 0 The New York Times – But compared with their predecessors, these are gigantic, weighty machines, nearly double the size of the old Canon BJC55. At a tallish 13.3 by 6.5 by 3.2 inches (for the HP. battery is another $90, or $140 with a very clever stand that. # # List of USB ID’s # Version 2.0 introduces a new flyout, Internet Explorer trigger plugin and adds various tweaks. and comes with an improved sign-in error flow. FluffyApp 2.0 also re-engineers the way it uses hotkeys to follow the Windows-provided. I have a simple calendar popup window come up when a date on the calendar is clicked. The code below works in Opera, FF and Chrome but not in IE6-8. It. I had an unspecified error in IE8 in my jquery-1.3.2.min.js file at line:19; I dont know how to fix it because that file has lot of functions. is there any solution. Cdf-ms Error Vista Original Title: 2/9131 (_0000000000000000.cdf-ms) error message. Unable to start or repair Windows. Error message 2/9131 (_0000000000000000.cdf-ms). What to do? Vista SP1 – error booting !! 0xc0190002 !! 328/88027 ($$_boot_pcat_ja-jp_d98fca962b0246de.cdf-ms). I cannot get this error to go away and boot my PC now. Please help!!! Troubleshooting – Guy Leech's Blog – So I resumed the process, Open and Resolved Bugs. The open and resolved bugs for this release are accessible through the Cisco Bug Search Tool. This web-based tool provides you with access to. 1.When I click on many links to webpages, unspecified errors arise and do not let the webpages open in Internet Explorer 8. Sometimes they open if tried a second or. C#er : IMage: JQuery, IE6, and 'Could not set the selected property. Unspecified error.' Jan 22, 2015. Uncaught means the error was not caught in a catch statement, and. and recent versions of Internet Explorer also give simpler errors than Chrome. code for IE6, and it's notoriously unhelpful “unspecified error at line 1” :-O. Compile Netcat on Windows using MinGW -. – I wanted a way to compile Netcat on Windows using MinGW so I could have a version without the GAPING_SECURITY_HOLE option (-e command line option). It also provides the steps necessary to create IIS7 sites, applications, and virtual directories, and options for configuring them. If you are familiar with IIS6. JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand at first, and the line numbers given aren’t always helpful either. An additional update is required before IE8 RC can be installed: without it, IE8 RC1 will balk during setup and show an error message saying "Setup cannot continue because one or more updates required to install Windows Internet. Regression Error Term Stata Nov 9, 2011. Browser = "IE" for Internet explorer, and App.Test. patch installed, I get an unspecified error message on the line pertaining to "CHRO". I'm getting unspecified error when reading document.namespaces in IE8. I can't seem to reproduce the problem in a standalone page, my snippet is: function. This page has an unspecified potential security risk. – John. – Jun 16, 2007. This page has an unspecified potential security risk. Also, it's not dependent on IE7, as I still only had IE6 running in that virtual machine. I get this error message when i sign out of yahoo messenger…plz help me. is this. Your cache (6.5.4) and BananAlbum (5.0) with Intenret Explorer 7. Oturum aç the webserver itself, there are no problems for me. Outer Tie-rod removal Is there DOM. Primary RC = E_FAIL (0x80004005) – Unspecified error [!] Full error info present: true. VD: error opening image file 'd:miscvpcxpsp3-ie6XP SP3 with IE6.vhd'. Can someone please tell me how to disable Internet Explorer Script Error – says: An Error has occurred in the script on this page. Error: Unspecified error. RECOMMENDED: Click here to fix Windows errors and improve system performance
http://thesecondblog.com/ie6-unspecified-error/
CC-MAIN-2018-13
refinedweb
824
68.67
I have a ASP.NET Core API project and I'd like to utilize DirectoryServices and DirectoryServices.AccountManagement namespaces. After some research I thought I found some project.json references that would work: { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "EntityFramework.Commands": "7.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer.Design": "7.0.0-rc1-final", " }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } }, "dnxcore50": { }, "net451": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } using System.DirectoryServices; using System.DirectoryServices.AccountManagement; In ASP.NET Core (the new Name for ASP.NET 5 and vNext isn't being officially used for months) a project will by default target multiple platforms. You have added the references to dnx451 framework moniker, which targets the full .NET 4.5 Framework. Now if you use using System.DirectoryServices; using System.DirectoryServices.AccountManagement; inside a *.cs file, it will work for .NET 4.5, but fail for .NET Core, because there is no reference for .NET Core to this namespaces/assemblies. On build always both versions will be compiled, that's why you get this error. You don't see it in the Visual Studio Editor, because it shows you the code of .NET 4.5 (above the code window is a pulldown menu where you can switch between the target frameworks). That being said, you have two choices: You want to target only .NET 4.5 In this case, you just delete the dnxcore50 moniker from your frameworks section of the project.json file ( net451 too because it's for class libraries only). This will turn your project an ASP.NET Core project which targets only the full .NET 4.5. You want/need to target .NET Core w/o working against the full .NET 4.5 Framework This is a bit more difficult. You either need a replacement for the same library in .NET Core. If it uses the same namespaces, just add its references to the dnxcore50 moniker and you are good to go. If there is no direct replacement, you have to remove this code parts from .NET Core projects, by using preprocessor directives. #if DNX451 using System.DirectoryServices; using System.DirectoryServices.AccountManagement; #endif Now your namespace will be used only in the .NET 4.5 target, but not in the .NET Core target. On a sidenote: You can remove the net451 moniker, as it's only used for Class Library (Package), the new project type for .NET Core libraries which compiles into a package which targets multiple framework targets. See the RC1 announcement for more. For applications (ASP.NET Core Web Project or xUnit project) always use the application moniker ( dnx451 and dnxcore50 respectively). For class libraries it's net451 and dotnet5.x.
https://codedump.io/share/MHh6Rvsnf1hO/1/problems-with-directory-services-and-account-management-in-aspnet-core
CC-MAIN-2017-30
refinedweb
474
54.39
Webpy + Google App Engine This cookbook entry explains how to run web.py as a google app engine application Requirements - Google App Engine Python API - web.py .38 or later Resources Notes - The mechanisms for running GAE in python2.7 and 2.5 are different, change the app.yaml accordingly - code.py is the main file of your application (2.5) - code.app is the object that cointains the return value of gaerun() (2.7) - appname is the name that you specified while creating your GAE application - runtime for 2.5 is python, 2.7 is python27 - threadsafe is only required in 2.7, read about it on the google app engine site app.yaml for python 2.5 application: appname version: 1 runtime: python api_version: 1 handlers: - url: /.* script: code.py app.yaml for python 2.7 application: appname version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: code.app To serve static files, you must add this under handlers (where static is the name of your static dir): - url: /static static_dir: static Hello World! This is a sample application that can be run by using dev_appserver.py (it is bundled with the SDK download): import web urls = ( "/.*", "hello", ) app = web.application(urls, globals()) class hello: def GET(self): return 'Hello, world!' app = app.gaerun() Save this as code.py (or whatever you specified in app.yaml) and type: dev_appserver.py . Now visit localhost:8080 in your browser and you should see hello world! NOTES There is a blank page or an internal server error solution: Make sure that you are running the version of python specified in the app.yaml file dev_appserver.py is not found solution: Make sure that it is in your path
http://webpy.org/cookbook/google_app_engine
CC-MAIN-2015-18
refinedweb
289
70.5
How to Do Time Value Money Calculations Three Methods:Calculating Future ValueCalculating Present ValueUsing Time Value of Money CalculationsCommunity Q&A Time value of money is the simple concept that an amount of money now is worth more than the same amount of money in the future because of the money's ability to earn interest during that time. For example, receiving a dollar today is always worth more to you than receiving a dollar tomorrow. This concept is applied to many areas of finance and can be used to value future income streams or compare investments.[1] The time value of money distinguishes between present value, the current-day worth of a future value, and future value, the value a certain of money today will have at a specified date in the future. With these two tools, you can calculate a number of other financial concepts. Steps Method 1 Calculating Future Value - 1Know what future value measures. Future value is the value of an asset or amount of money at a specified date in the future. Future value is calculated by multiplying the present value of the asset or amount of money by the effects of compound interest over a number of years. This calculation relies on an interest rate that will be earned by the money or asset over those years.[2] - 2Learn the future value equation. The future value equation involves only three variables: the principal amount (also called present value), the interest rate, and the number of periods over which the interest will be accumulating. It measures the future value that will be attained through the growth of the principal. The exact equation is as follows: . In the equation, the variables represent the following figures: - 3Calculate the future value of an investment. Imagine that you have invested $5000 in an account that earns five percent annual interest. You want to know how much the account will be worth in ten years. Start by inputting all of your variables into the future value equation. - Your equation in this example would look like this: - Note that the interest rate, 5 percent, was converted to a decimal in the equation. This was done by dividing by 100 (5/100=0.05). - Start the calculation solving the addition in parentheses. Your equation should now look like this: - Solve the exponent. This is done on a calculator by typing the lower number (1.05 in this case), pressing the exponent button (usually ), and then entering the higher number (10 here) and pressing enter. Your equation should now look like this: - Note that the result of the exponent, 1.63, is a rounded figure (the actual result is 1.62889...). If you don't round this number off, your later calculations will vary from the example. - Solve the multiplication. This gives you - The future value of your $5,000 is $8,150. In other words, your $5,000 will have earned $3,150 in interest over the ten years and will then have a total value of $8,150. Method 2 Calculating Present Value - 1Learn the basics of present value. Present value can be defined as "the current-day value of a future sum of money or stream of cash flows given a specified rate of return (interest rate)."[4] This rate of return, called the discount rate, is used to decrease the future value of the payment or cash to find its present value. Finding the appropriate discount rate is important for properly valuing future cash flows. - In simpler terms, present value expresses the reality that a $10,000 payment now is worth more to an investor than a $10,000 payment in five years. - Put another way, to find the present value of the future $10,000, we need to find out how much we would have to invest today in order to receive that $10,000 in the future.[5] - 2Use the present value equation. The present value is equation is very similar to the future value equation, except the exponent for the number of years is negative. The equation is usually stated as . The variables stand for the following: - PV is the present value. - FV is the future value. This represents the stated value of the future payment. - r is the discount rate. This can be many different relevant rates, especially in corporate finance, but here we are using the interest earned on a compound interest-earning account. - n is the number of periods (years in this case).[6] - 3Calculate the required investment to reach a future amount. One of the uses of present value is to determine how much money would need to be put into an account now so that the value of the account reached a certain amount in a number of years. For example, imagine that you are saving for college and wish to have an account value of $50,000 in ten years. The account earns 7.5 percent interest each year. To find the investment needed now to reach this value, input your variables in the present value equation. - Your future value is $50,000, n is 10, and r is 0.075 (7.5% expressed as a decimal by dividing by 100). So, your completed equation is: - Start by adding the 1 to i in the parentheses to get: - Next, solve the exponent above the parentheses to get: - The exponent can be solved on a calculator by inputting the variable in parentheses first, pressing the exponent button (usually ), and then inputting the exponent and pressing enter. - Note that the result, 2.061, is a rounded number. If you do not round this number, you will get a different final result than in the example. - Finally, solve the remaining division to get - You only need to invest $24,260.07 in the account now to have $50,000 in ten years. - 4Calculate the present value of a future payment. Imagine that you are going to receive a payment of $10,000 in five years and you want to know how much less this will be worth than if you got the money now. For the discount rate, imagine that you have an account you could put the $10,000 into that would earn five percent annual interest. - First, put your variables into the present value equation. The completed equation is as follows: - Solve the addition within parentheses first. This yields: - Then, solve the exponent. This yields: - Note that the result, 1.276 is a rounded figure. You will get a different final result if you do not round this number. - Divide the last two numbers. Your result is $7,836.99. - So, getting $10,000 in five years is like getting $7,836.99 now. Method 3 Using Time Value of Money Calculations - 1Understand the implications of the time value of money. These calculations make it clear that time is literally money. The value of the money you have now is higher than the same amount of money in the future. This is why you should know how to calculate the time value of money. It allows you to determine which investments are better, based upon not just how much money they return to you, but when they return it. [7] - 2Decide between payments using present value. Present value can be used to determine whether a present payment of a certain value will end up being worth more or less than a future payment of a different value. For example, imagine that you have won the lottery and are offered either $1 million now or $2.5 million in ten years. Your money manager advises you that you can safely earn ten percent interest per year if you invest the money. Which payment should you take? - The present value of the $1 million is, obviously, $1 million. This is only two-fifths of the monetary value of the later payment, though. - However, the $2.5 million dollar payment is being made in ten years, during which time your $1 million could be earning ten percent interest (assuming you didn't spend it). If you apply the present value equation, you find that the present value of the $2.5 million is only about $964,000. - So, you would want to take the $1 million now and invest it. It will be worth almost $2.6 million in ten years. - 3Calculate the net present value of an investment. Present value calculations can also be used to analyze the profitability of business projects by using the concept "net present value." Net present value refers to the present value of projected sales revenues or interest earnings from a project or investment minus the present value of money invested in the investment or project. In this way, it is used to see whether or not the project will be profitable. Alternately, it can be used to determine susceptibility to interest rate fluctuations.[8] Community Q&A Video Sources and Citations - ↑ - ↑ - ↑ - ↑ - ↑ - ↑ - ↑ - ↑ Article Info Categories: Managing Your Money In other languages: Español: calcular el valor tiempo del dinero Thanks to all authors for creating a page that has been read 29,671 times. About this wikiHow
http://www.wikihow.com/Do-Time-Value-Money-Calculations
CC-MAIN-2016-18
refinedweb
1,528
64.51
> 220 PC Resident FTP 2.2TN/TC-D server, ready > 220 Macintosh Resident FTP server, ready If you have a non-unix based ftp server, I would appreciate it if you can run the following script and if it is something other that the above, send me the output. ( The above is from NCSA Telnet for DOS and the Mac - I don't know the version offhand.) [ Or just ftp manually, if you can cut and paste the banner and/or redirect the output. ] I'll thank you all now, in advance. Just in case I get 200 replies! - I'm not going to write you all a thank you note. However, if you do send me info on an machine I don't have access to, I may ask you for further information so that I can support it. I'll also accept unix banners in my collection - It's not as vital as unix/posix is going to be the default. ( and I can probably collect a big variety of those from various anonymous ftp sites. ) Thanks! - Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU> - UVA Department of Molecular Physiology and Biological Physics #!/usr/local/bin/python from ftplib import FTP def banner( host ): ftp = FTP().init( host ) try: except: pass return welcome import sys for arg in sys.argv[1:] : print banner( arg )
http://www.python.org/search/hypermail/python-1993/0491.html
CC-MAIN-2013-20
refinedweb
226
74.59
Announcing VI Java API 5.5 Beta Supporting vSphere 5.5 As it’s asked about when the vijava API 5.5 is ready, the answer is NOW. A couple of minutes ago, I uploaded the beta release to the sourceforge.net site. Please feel free to download the beta release and give me your feedbacks and bug reports as soon as possible. I plan to GA the release in about one month. The most important changes in this release is the support for vSphere 5.5 which was released on this Monday. We’ve added 6 more managed object types and new methods in existing managed object types. Even more are the new data object types, which are about 150 total. I’ll write a separate article on this subject later on. (Update: just published here) Another very important change is a major refactoring of the code base around the conversion of XML to Java objects and vice versa. Please note that these changes do not affect any applications. If you have an important product depending on the API, I do encourage you to run a full round of tests. Although I’ve tried best for highest quality, still these is a chance that I missed something. Also, the XML parsing/generation engine is meant to be private (even some of them are declared as public class). In other words, they should be used the other parts of the APIs, not your applications. Should you need help, don’t hesitate to contact me for consulting service. Before I wrap this article and head for lunch, here is the binary download link. You can still easily get to the download page as before from project home for source package. Hope you enjoy the beta and look forward to hear from you, good or bad. Thank you. We’ll try this release very soon. Hi Steve, Just wanted to figure out if there are any specific dates when the VIJava 5.5 api’s will be GA’d? Regards Samir Thanks for checking. I don’t see any bug filed yet, which is probably too good to believe. Have you tried out the API yet? Steve @Steve Jin Hi Steve, We’ve not tested the Beta build yet but are planning to do it very soon. Will let you know if we run into issues. -Samir Hi Steve, Just wanted to update you that we’ve been testing the 5.5 jars with our setup (Primarily 5.1 and 4.1 ESXi servers) and we havent seen any issues yet. We mainly use vijava for read operations and have not done any write operations. -Samir Thanks a lot for the update Samir! Steve Hi Steve, We also downloaded the 5.5 beta and tried lot of read operations on 5.5 vCenter as welll as some old ones. We did not find any issues till now. Please let me know when you plan to GA this. Regards, Madhusudan When is the 5.5 final release? I planned to get a new build with bug fixes but so far there is no bug filed. Steve Hi Steve, Since there are no new bugs, are you planning announce the GA soon (with the same build number as the Beta)? Sriram Steve, I am eager to try the 5.5 beta. Is there a maven repository available? Manas There is no maven repo, but you can try the jar or sync code to your project. Steve Hi Steve, I know this has been asked before but I wanted to know if there is a set date on when vijava 5.5 will be GA’d? Thanks Samir If I have a proposal for API extension (with implementation) how do I convey this to you? Steve, Any update on when the final release of 5.5 will be available? Manas Does ViJava 5.5 support querying and creating new VM storage policies? Whatever is supported by vSphere API itself should be supported by vijava. Open a ticket if it is not there. Steve @Steve Jin Thanks Steve. I checked the Vi Java src jar and see no VM storage policy related APIs. What VM storage policy? What do you want to do with it? Steve Hi Steve, Any updates on when we can get the ViJava 5.5 GA release? We are trying to decide on whether to wait for 5.5 to go GA or to still use 5.1. Would really appreciate some clarity on this so that we can make our decision. Thanks & Regards, Ashutosh It is understandable if you are not ready to publish 5.5 as GA yet, but please at least make the betas available on Maven Central. Otherwise it is much more cumbersome to even try the new version. I try to compile the vijava 5.5 source using jdk 1.5 and got errors. Also i got errors when i try to access the vijava5.5 classes from my jdk1.5 compiled class files. I have 1000 of java files from my own, i cannot change my jdk, is there any other solution for this problem. You can do it with a bit of tweaks. Hopefully you can upgrade your java to 6 and above. Steve Hi Steve, Any update on vijava5.5 final reslease? Hi Steve, Since there is no information available on 5.5 version being GA yet, have following question: Does the VI Java 5.5 beta version have any changes for existing Data Store managed object. Since we plan to use it for following use cases – create data store, modify the size of data store and delete data store, are these supported operations supported in VI java 5.5 ? Currently we are trying out with the API but just wanted to check if someone could help with this information. Also another question on similar lines, is it OK to use VI Java 5.1 version with vCenter/vSphere 5.5 installation for the 3 use cases that I mentioned Thanks, Nataraj Is there any news on a GA release of VI Java 5.5? Using 5.1 now, and would LOVE to get 5.5 when it is out of beta. Thanks for the work!!! Steve, Are you planning for a 5.5 GA release and is there a roadmap/future of this project ? Its more than year now the beta has released. Howdy Steve. First, I want to say thank you for creating vijava. We at EMC have been using it for quite some time now. Any plans for vijava 5.5 GA ? Since its been quite a long time (more than a year) since first vijava 5.5 beta came out. I suspect future versions of vijava wont be coming on time either. And perhaps 5.5 is the last release of it. I see lots of people have eagerly asked about the GA date, but you haven’t replied to any of them. I am afraid if vijava is not going to be maintained for longer period, we may have to start looking for other libraries. Kindly reply. Steve I am using vijava-5.0.1 and trying to call PropertyCollector::waitForUpdateEx() for a vcenter 5.5, and getting InvalidProperty exception, where as the same call works on a 5.0 version of the vcenter server. I do not want to use the PropertyCollecotr::waitForUpdate() API since it has been deprecated. Are you aware of this issue and do you know if moving to 5.5 version of vijava will fix this issue or not? Any help regarding this matter will be helpful. Thanks Dhrumin Hi Steve, I am new to VI java. My question is I only get the jar file. but where is docs( API) and how I get started? Thanks & Regards, Steven There is no javadoc in the open source version of vijava, but the commercial vijavaNG does come with javadoc, along with many other improvements. You can check out the vijava.sf.net to get started – there is a getting started tutorial. Hi Steve, I think vijava 5.5 has a regression compared to the old version. The error handling of WSClient#invoke(String, Argument[], String) has changed. vijava-51-20121125 has created a RemoteException like this: throw new RemoteException(“Exception in WSClient.invoke:”, e); vijava-55b-2013092 does no longer pass the exception as argument (cause), now its a string concatenation: throw new RemoteException(“VI SDK invoke exception:” + e1); In the old version it was possible to iterate through the exception causes and check, for example “instance of ManagedObjectNotFound”. Now its necessary to analyze to exception message. And btw it would be nice if WSClient is non-final (and keep the invoke/post method non-final public too). This gives the possibility to intercept the invoke and could be used to replace the existing transport layer. Hi Steve Love your product, its been a life saver for us for the last 3 years. We have recently updated our servers to 5.5 and have problems with our java installation code. In particular we use the GuestProcessDirector.readEnvironmentVariables to get the path on our guests so we can then make some decisions about what to do next This is now throwing an exception: [FTIInstaller] java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String; [FTIInstaller] at com.vmware.vim25.ws.VimStub.readEnvironmentVariableInGuest(VimStub.java:4041) [FTIInstaller] at com.vmware.vim25.mo.GuestProcessManager.readEnvironmentVariableInGuest(GuestProcessManager.java:73) [FTIInstaller] at org.doublecloud.vi.vmware.guest.GuestProcessDirector.readEnvironmentVariables(GuestProcessDirector.ja va:89) Any help on this would really be appreciated as its stopping us from deploying new guests Cheers Steve Good to know it helps. It seems to be a typing issue. Will take a look at it. Thanks! -Steve
http://www.doublecloud.org/2013/09/announcing-vi-java-api-5-5-beta-supporting-vsphere-5-5/
CC-MAIN-2018-43
refinedweb
1,634
77.13
Hey guys, I just wrote a simple program that takes 10 integers into a vector, and the goal of the program is to output the ten numbers, all multiplied by two, using iterators. Well, I wrote the code and it seems fine, and also compiles fine, but when I enter in the first ten numbers into the vector, it says "Project1.exe has stopped working..." I'm currently using Vista Home Basic. Can anyone tell me what's going on? Thanks for anything in advance. Here's the code: Code:#include <cstdlib> #include <iostream> #include <vector> using namespace std; int main(){ vector<int> str(10); int num, counter; while (cin >> num){ str.push_back(num); } for (vector<int>::iterator iter = str.begin(); iter != str.end(); ++iter){ *iter = str[counter] * 2; ++counter; cout << *iter << endl; } system("PAUSE"); return EXIT_SUCCESS; }
http://cboard.cprogramming.com/cplusplus-programming/100894-strange-problem-during-runtime-program-has-stopped-working.html
CC-MAIN-2015-48
refinedweb
137
66.13
Office Dev Content SharePoint Dev Content Blogs for Office developers > Apps for Office and SharePoint blog In this post, you’ll learn how to integrate OAuth 1.0a to access an external service from an app for Office. In the course of a recent development project, I was asked to show how apps for Office can be used to simplify citing sources in a Word document. The requirements were: · The app should connect to Zotero (a free and open-source reference management software to manage bibliographic data) on behalf of the user. · With one click, the app should pull down the user’s stored sources and insert the citations into a Word document. You can download the Zotero web service code sample to preview what I’m going to talk about. Figure 1. Zotero Citation Assistant app user interface Zotero is pretty easy to work with. Simply download the Firefox extension or stand-alone program, and you can begin storing and organizing your research sources. You can start with even a minimal amount of information—for example, the ISBN numbers of the sources you want to manage. Although you can pull the citation directly from Zotero’s program to the clipboard or save them as a file, Zotero really shines with its ease of integrating into other applications. Zotero provides an API that can be used to connect a third-party app to their system to retrieve and process a user’s research source data. Because that data needs to be secure, Zotero uses OAuth 1.0a to authorize the app to act on behalf of the user. OAuth is a standard for web authorization. It allows a “client” (what we developers call a server, or service, that we are implementing) to access “server resources” (for example, Facebook data) for a “resource owner” (the user). It does this by having the resource owner log on to the server and grant the client authorization. The server then grants the client a token that can be used in further calls to the server’s API. For this blog post, I’m going to focus on OAuth 1.0a, since that’s the version Zotero currently uses. Because we need to get cross-domain resources from Zotero, the web browser same-origin policy becomes an issue. Generally, JSONP (JSON with padding) would be used as a solution to get cross-domain resources; however, JSONP is not supported by many secure web services (including Zotero) due to potential security flaws (see Defining Safer JSON-P). Consequently, you’ll need a web service—I chose Windows Communication Foundation (WCF)—to place the actual calls to Zotero and return results to the user’s browser, as well as server-side logic to handle the initial authorization. We use a WCF REST service in the Zotero code sample. I chose to use ASP.NET to handle initial authorizing because it was a perfect opportunity to show that apps for Office can handle more than just HTML and JavaScript. For example, task pane apps are actually (specialized) web browsers that live in Office. This means that you could have one full-blown website for both regular browsers and apps for Office. I also chose to use DotNetOpenAuth and the extensions for ASP.NET, as these greatly simplify OAuth implementation. DotNetOpenAuth is an OAuth library for use in .NET applications that provides a well-known and simple way to integrate OAuth into applications. Since the new Visual Studio web application templates use DotNetOpenAuth, they are already set up for OAuth. Thus, using the library means better and easier integration with any existing ASP.NET web applications that you may have. So how simple is it to get up and running with the ASP.NET extension of DotNetOpenAuth? It can be very straightforward. In this case, it’s less than 200 lines of code! There is a little bit of setup to do if you don’t have an already existing web application. The Apps for Office template gives you two projects, an app for Office project and a website. You’ll first need to convert the website to a web application. To do this, right-click the project and select Convert to web application. Once the website is converted, you can host the web service in a web app (This is the preferred way of hosting WCF services in IIS). You can then also replace the Home.html file with an .aspx file (Home.aspx in the code sample). Now we’re ready to get coding! For the code sample, I followed conventions for OAuth 1.0 clients that already exist in the DotNetOpenAuth ASP.NET extension. The following is located in the ZoteroClient.cs code file. Simply create a class and have it inherit from DotNetOpenAuth.AspNet.Clients.OAuthClient, set the necessary information (endpoints, service provider description, etc.), and override the VerifyAuthenticationCore() method. public class ZoteroClient : OAuthClient { private const string UserAuthorizationRequestUrl =; private const string AccessTokenRequestUrl =; private const string RequestTokenRequestUrl = ""; In VerifyAuthenticationCore(), you’re basically just setting the properties of AuthenticationResult based on what Zotero will have passed back at this stage of OAuth, as well as any extra data your .aspx code-behind will need (in this case the access token). That’s all there is to setting up a simple custom OAuth client! //We don't care if this is empty or not. string userName = ""; if (response.ExtraData.ContainsKey("username")) { userName = response.ExtraData["username"]; } string accessToken = response.AccessToken; Dictionary<string, string> extraData = new Dictionary<string, string>(); extraData.Add("accessToken", accessToken); return new AuthenticationResult(true, this.ProviderName, userId, userName, extraData); Back in your .aspx code-behind, you’ll need to set up some logic to determine whether: · You already have a token for that user. · This is a brand new request. · You’ve just received results back from Zotero. In your “new request” logic, add your instantiated custom client to OpenAuth.AuthenticationClients, and then call OpenAuth.RequestAuthentication for the custom client. Then, in your logic for when a result is returned, you’ll need to get the access token from the results, as well as the user name (Zotero requires both). Section 9 of the OAuth 1.0a spec states that requests take a token and signature. This means that HTTPS is not needed. Furthermore, since the token by itself can’t accomplish anything, there are no security issues with passing the token down in a cookie for the user to store. Zotero went a slightly different route, requiring HTTPS and not requiring signing. Since the user can revoke a token at any time, the token is permanent and can thus be persisted. This means all that is needed is the access token. For the code sample, to save time and complexity, I simply stored the token in a cookie. If that cookie gets cleared, a new token gets issued. This isn’t ideal. In addition to being insecure, this implementation can clutter the user’s Zotero token management page with numerous requests. Here is an example: Figure 2. Zotero token management page It would be better to encrypt the key in the cookie, but the most secure option would be to store the token in a database and associate it with a user. That would require setting up an account system so that we can tie the token to a user securely. Such an approach was out of scope for this app; but since the token is permanent and is the only piece needed to actually make calls (the Zotero user ID is used as part of the URL to get at that user’s specific research sources), secure account access to a token database would be the preferred way to handle the token. Only one more step remains to make sure everything will work smoothly: making sure Word will trust Zotero’s domain. In the app for Word project, open the app manifest XML file and insert the following. <AppDomains> <AppDomain></AppDomain> </AppDomains> That line tells the task pane that we trust Zotero, and that redirects can be opened in the task pane and not in a new browser instance. Otherwise, Zotero will try to open in a new browser instead of in the task pane, making the app unusable. Now that everything is in place, we can run the app, which will take us to Zotero’s login page. Once we log in, we grant the app permission to work with Zotero on our behalf by creating a new key for the app. Once the key is created, Zotero redirects back to our page, and the app will have control. Figure 3. Zotero log in page Figure 4. Zotero app authorization page As you can see from this example, although it’s a bit time consuming and complex, OAuth 1.0 is not difficult to implement. By using DotNetOpenAuth, you decrease the complexity, and the app is more easily integrated with existing sites that use the library. After you get the hang of it, hooking up and getting Zotero working can take as little as a few hours. So what’s next? Well, we still need to get to the program’s logic, how to call APIs, and how to modify and insert the returned data into the Word document. In my next post, I will go over those details and show just how easy it is to work with the Word API. I hope you found this post informative, and I look forward to writing the continuation piece. Until next time! Today’s post was authored by Tyler Wagner. Tyler is an associate developer at 3Sharp. 3Sharp specializes in SharePoint consulting and Microsoft Office customizations, and offers a range of services from building custom business intelligence dashboards to software solutions for customized document generation—and so much more. You can find out more about 3Sharp at.
http://blogs.msdn.com/b/officeapps/archive/2013/08/21/use-oauth-1-0-to-access-the-zotero-web-service-from-apps-for-office.aspx
CC-MAIN-2014-41
refinedweb
1,642
65.22
#include <rpc/rpcsec_gss.h> bool_t rpc_gss_getcred(struct svc_req *req, rpc_gss_rawcred_ t **rcred, rpc_gss_ucred **ucred, void **cookie); rpc_gss_getcred() is used by a server to fetch the credentials of a client. These credentials may either be network credentials (in the form of a rpc_gss_rawcred_t structure) or UNIX credentials. For more information on RPCSEC_GSS data types, see the rpcsec_gss(3NSL) man page. Essentially, rpc_gss_getcred() passes a pointer to a request (svc_req) as well as pointers to two credential structures and a user-defined cookie; if rpc_gss_getcred() is successful, at least one credential structure is "filled out" with values, as is, optionally, the cookie. Pointer to the received service request. svc_req is an RPC structure containing information on the context of an RPC invocation, such as program, version, and transport information. A pointer to an rpc_gss_rawcred_t structure pointer. This structure contains the version number of the RPCSEC_GSS protocol being used; the security mechanism and QOPs for this session (as strings); principal names for the client (as a rpc_gss_principal_t structure) and server (as a string); and the security service (integrity, privacy, etc., as an enum). If an application is not interested in these values, it may pass NULL for this parameter. The caller's UNIX credentials, in the form of a pointer to a pointer to a rpc_gss_ucred_t structure, which includes the client's uid and gids. If an application is not interested in these values, it may pass NULL for this parameter. A four-byte quantity that an application may use in any manner it wants to; RPC does not interpret it. (For example, a cookie may be a pointer or index to a structure that represents a context initiator.) See also rpc_gss_set_callback(3NSL). rpc_gss_getcred() returns TRUE if it is successful; otherwise, use rpc_gss_get_error() to get the error associated with the failure. See attributes(5) for descriptions of the following attributes: rpc(3NSL), rpc_gss_set_callback(3NSL), rpc_gss_set_svc_name(3NSL), rpcsec_gss(3NSL), attributes(5) ONC+ RPC Developer’s Guide Linn, J. RFC 2078, Generic Security Service Application Program Interface, Version 2. Network Working Group. January 1997.
https://docs.oracle.com/cd/E36784_01/html/E36875/rpc-gss-getcred-3nsl.html
CC-MAIN-2021-21
refinedweb
339
54.22
Hi, Generally you will always have a public class that has the same name(exactly, as java is case-sensitive) as the file it resides in and it is common practice to include the name of the file in a comment at the first line of the file. e.g... //Test.java public class Test { public static void main(String[] args) { System.out.println("Hello World"); } } When I first started out in Java I thought the reason for this was to tell the compiler where to find the main method that would specify the application execution start point when you run it by typing java PublicClassName but in .java source files each class can still have it's own public static void main method(even non public classes) and when the .java source file gets compiled each class is created as a separate bytecode file and you can run a .class file on it's own if the class contains a main method in the source file. I'm not entirely sure why you have to name them rhis way other than helping the programmer while developing as a developer can look at a source file and see from the name of the file that the class of most interest is the class with the name of the file, the public and user creatable one. If you find out more let me know. The restriction of only one public class per source file is Java's way of sort of forcing you into organising/splitting your application up into logical units. Each public class in a file is the portion visible to the outside world and the user can make instances of that class, all other classes contained in the file should be support classes to the public class and not user creatable thereby making each source file its own functional unit. These files can also be grouped by using the package keyword, this allows you to group a number of class files into libraries of related classes. The way java makes you organise these classes also helps to prevent name clashes. hope that helps Brett "siva" <siva_mrs@usa.net> wrote: > >hello > siva <siva_mrs@usa.net> wrote in message news:3a520a57$1@news.devx.com... > .... Why must the name of the file must be the same of that of the public class it contains? Thanks in advance. > > -Siva > When you compile a source file into a class, the compiler will do you a favour and also compile all classes that your source file refers to, if their .class file is older than their .java file. To do this, it needs to be able to identify the source code for a .class file, and hence the naming convention. This is actually a very useful thing for the compiler to do. For example, if class A refers to class B and class B refers to class A, then there would be no way to compile this pair of classes when you first wrote them unless the compiler could deal with more than one source at a time. PC2 Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?28811-file-name-class-name-why&p=64324
CC-MAIN-2016-36
refinedweb
534
66.78
Namespace, CGroup, and Union file-system are the basic building blocks of a container. Let’s have our focus on file-system. Why yet another file-system for the container? Are Conventional Linux file-systems like ext2, ext3, ext4, XFS etc. not good enough to meet the purpose? In this blog post, I will try to answer these questions. Here we will be delving deeply into the Union File System and a few of its essential properties. Layered architecture A container is composed of multiple branches. In docker’s terminology, branches are also known as layers. A sandbox of a container is composed of one or more image layers and a container layer. Container layer is writable, image layers are read-only. Identifying the Problem Following are the 2 main challenges with conventional file-systems. Inefficient Disk Space Utilization Let’s take a hypothetical scenario. Suppose 10 instances of a docker container are up and running on your system. Image size is 1 G. If you use concrete file-systems like ext* or NFS for containers, at least 10 G of physical memory would be eaten up by containers. It is bad for disk space optimization. Latency in bootstrap A container is nothing but a process. In Linux, the only way to create a new process is forking the existing process. The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process. In order to create a new container, all the files of image layers would be copied into container namespace. A container is expected to start in a few milliseconds. If a huge payload is needed to be copied at the time of starting a container it increases the bootstrap time of a container. So, here we need some mechanism to efficiently share physical memory segments among containers. In order to address these challenges listed above, Union Capable File Systems came into existence. Union File System Union file system works on top of the other file-systems. It gives a single coherent and unified view to files and directories of separate file-system. In other words, it mounts multiple directories to a single root. It is more of a mounting mechanism than a file system. In the above figure, you can see that multiple directories on different file-systems are mounted on a common root. UnionFS, AUFS, OverlayFS are the few popular examples of the union file system. Properties of a Union File System we need a file-system service with following properties. - Logical merge of multiple layers. - Read-only lower layers, writable upper layer. - Start reading from the upper layer than defaults to lower layers. - Copy on Write (CoW) - Simulate removal from lower directory through whiteout file. In order to simplify the above properties, please substitute the term layer with directory. Here I will try to explain all the mentioned properties using a use case. Here I am going to simulate a container’s file-system layers using three directories named Frontend, Backend, and Fullstack. You can relate Frontend and backend directories with Create sample directory structure and virtual partitions. Experiment 1 : Mount multiple directories on a common mount point using ext* file-systems. Conclusion: Multiple volumes can’t be mounted on a single mount point. concrete filesystems won’t help here. Experiment 2: Mount multiple directories on a common mount point using Union File System (OverlayFS). Conclusion: Yes, Union-Filesystem is capable to mount multiple directories of different file-systems on a mount point. Experiment 3: Demonstrate Copy-on-write (CoR) Copy-on-write is a similar strategy of sharing and copying, in which the system processes that need access to the same data share the same instance of that data rather than having their own copy. At some point, if any one process wants to modify or write to the data, only then does the operating system make a copy of the data for that process to use. Only the process that needs to write has access to the data copy. All other processes continue to use the original data. File access through the OverlayFS retrieves data from the “upper” directory Modifications to files in the “upper” directory will take place as usual. Any modification to a file from the “lower” layer will create a copy in the upper layer, and that file will be the one modified. This leaves the base files untouched and available through direct access to the “lower” folder. Experiment 4: Deleting files from “lower” layer. A file removed from the union mount directory would directly remove a file from the “upper” directory, and simulate that removal from the “lower” directory by creating what is called a “whiteout” file. This file exists only within the “union” directory, without physically appearing in either the “upper” (fullstack/upper) or “lower” (frontend and backend) directories. When the union mount is dismounted, this state information will be lost, so care should be taken to reflect any necessary changes to the “lower” directory. Conclusion Containers can grow very high in numbers so it is a good idea to leverage union capable filesystem. It allows a sensible way of sharing the data among containers. At the same time, it ensures the integrity of filesystem.
https://blog.knoldus.com/unionfs-a-file-system-of-a-container/
CC-MAIN-2020-05
refinedweb
882
56.96
Introduction When you use print() in python the output goes to standard output or sys.stdout. You can directly call sys.stdout.write() instead of using print(), but you can also completely replace sys.stdout with another stream. This example will show you how to use StringIO memory files to capture and view stdout. As always, check the official StringIO documentation for the best information. Use StringIO to replace stdout This is good for testing and special cases where you may not have a terminal output. First, create the StringIO object and then replace sys.stdout with it. You can write to it directly, or when using print() it will default to going to sys.stdout and therefore go to our stream object. To get back the original output stream, it is stored from sys.__stdout__ a special dunder that always contains the original system stdout. from io import StringIO # Python 3 import sys # Create the in-memory "file" temp_out = StringIO() # Replace default stdout (terminal) with our stream sys.stdout = temp_out print("This is going in to the memory stream") temp_out.write("Can be written to like normal.\n") # The original `sys.stdout` is kept in a special # dunder named `sys.__stdout__`. So you can restore # the original output stream to the terminal. sys.stdout = sys.__stdout__ print("Now printing back to terminal") print("The 'fake' stdout contains: =======") sys.stdout.write(temp_out.getvalue()) print("=============================") Note that the StringIO object is the same type of object created when you call open() and open a file with the r flag. There is also an io.BytesIO object for byte streams, which is the type of object you get when calling open() with rb. Also note that there is sys.stderr and sys.stdin that you can manipulate in the same ways. They also have the corresponding sys.__stderr__ and sys.__stdin__ originals. Conclusion After reading this, you should know how to create in-memory files for both text and binary data as well as how to temporary replace the default system standard out with your own object to capture data.
https://www.devdungeon.com/content/python-use-stringio-capture-stdout-and-stderr
CC-MAIN-2022-40
refinedweb
348
68.77
0 Hi everyone, I'm trying to accomplish the following; I need to create 2 subprocesses and each subprocess should create a process of their own. Should look like this: I'm child xxxx parent xxxx I'm the subchild xxxx parent xxxx I'm the second child xxxx parent xxxx I'm the second subchild xxxx parent xxxx So far I have this #include <stdio.h> int main() { int pid; pid = fork(); if (pid) { printf("I'm the parent %d\n", getpid()); } else { printf("I'm the child %d parent %d\n", getpid(), getppid()); pid = fork(); if (pid) { } else { printf("I'm the subchild %d parent %d\n", getpid(), getppid()); } } return 0; } The above creates a child process and another process but for some reason it does not get the PPID from the child it's been created from. I wonder why is this. The current output looks like: I'm the parent 6213 I'm the child 6214 parent 6213 I'm the subchild 6215 parent 1 The subchild's parent should be 6214. Some help would be greatly appreciated Edited by MrDiaz: n/a
https://www.daniweb.com/programming/software-development/threads/286054/help-with-fork
CC-MAIN-2018-30
refinedweb
187
68.74
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Namespaces4:01 with Jeremy McLain In this video, we'll learn about namespaces and create a FitnessFrog namespace. To compile: mcs Program.cs To run: mono Program.exe written a couple of method calls, - 0:02 let's take a moment to dissect them a bit. - 0:04 Let's take a look at the names. - 0:06 You'll notice that the name of this method is actually three words, - 0:10 separated by dots. - 0:12 Actually, the name of the method is just Write. - 0:15 Console is the name of the class that the method is contained in. - 0:19 Remember that I said, all methods are contained in classes, - 0:22 just like our main method is in the Program class. - 0:25 System is the name of the namespace that the class is contained in. - 0:29 Classes are contained in namespaces. - 0:32 The purpose of a namespace is to make it so - 0:35 that we can potentially have multiple classes with the same name. - 0:39 Without a namespace, we could never make our own class named Console, - 0:42 because C# wouldn't know which Console class we wanted to use. - 0:48 You can think of the namespace and class name as parts of a mailing address. - 0:53 Just about every city in the US has a street named Main Street. - 0:57 We can't just address letters to go to Main Street, without a state or city name. - 1:02 The post office wouldn't know which city to send the letter to. - 1:05 You can think of the namespace name as the state. - 1:08 The class name has the city, and the method name has the street. - 1:13 By combining all three names together, - 1:15 we get the full address of the method to call. - 1:18 You may be wondering what namespace our program class is in. - 1:22 We haven't specified a namespace, which is actually a bad practice. - 1:26 Let's add a namespace now. - 1:28 To add a namespace we'll go up here above the class name and type namespace. - 1:33 I want the namespace to be called Treehouse. - 1:36 Then I'll surround the class with opening and closing curly braces. - 1:40 Then I'll indent everything in between the curly braces. - 1:43 You can indent in Workspaces by highlighting everything you want to - 1:46 indent and than typing Tab on your keyboard. - 1:49 You don't have to indent. - 1:51 But indenting does make the code more readable. - 1:54 These curly braces are really important. - 1:57 For every opening curly brace, there needs to be a closing curly brace. - 2:01 This is how we organize things in C#. - 2:04 The Main method is inside the Program class - 2:07 because it's inside of its curly braces. - 2:10 And likewise for the Program class. - 2:12 It's in the Treehouse namespace because it is contained within the curly braces. - 2:17 A very common coding mistake is missing a curly brace, or - 2:20 putting them in the wrong place. - 2:22 Keep an eye out for that. - 2:24 One more thing about namespaces. - 2:25 Namespaces can have multiple levels. - 2:28 Often times, if you're working at a company, the first name of the namespace - 2:32 that contains the code written by that company will be the company's name. - 2:36 This is why I've named this one, Treehouse. - 2:38 The second name can be used to further partition the classes - 2:42 into smaller namespaces. - 2:43 For instance, - 2:44 we can differentiate our Program class from other Program classes that may have - 2:49 been written here at Treehouse by adding the name of the app we are building. - 2:53 You can have as many name spaces as you want. - 2:56 Just put dots between each name. - 2:59 So when looking at a method call, you can tell what the namespace name, - 3:02 the class name, and the method name is by reading from right to left. - 3:06 The right-most name is the name of the method. - 3:09 Left of that is always the name of the class. - 3:13 Everything to the left of the class name is the namespace name. - 3:17 The last thing you need to know about namespaces is that you don't have to write - 3:20 them and leaving them out can greatly reduce typing. - 3:24 We can actually take every mention of the system namespace out of our code - 3:28 if we just write this line at the top of our file here, - 3:31 now we can delete every mention of system in our code. - 3:36 So long as we don't use two Console classes that aren't in the same namespace, - 3:40 we'll be fine. - 3:42 This is called a using directive. - 3:44 There are lots of different namespaces in the .NET framework, and - 3:47 we can put as many of these using directives up here as we want. - 3:51 Really, the only reason to use a using directive - 3:54 is to reduce the amount of typing that you have to do in the rest of the code. - 3:57 Some may say that it also makes the rest of the code more readable.
https://teamtreehouse.com/library/namespaces
CC-MAIN-2017-26
refinedweb
956
82.34
1 . Suppose s1 and s2 are two strings. Which of the following statements or expressions are incorrect? a. String s3 = s1 - s2; b. int i = s1.compareTo(s2); c. char c = s1[0]; char c = s1.charAt(s1.length() - 1); e. a and c. Your choice is ___B____ 2. How can you initialize a string with "123"? a. String[] string = {'1', '2', '3'}; b. String string = {'1', '2', '3'}; c. String s = "123"; d. String s = new String("123"); e. c and d are both fine, but c is better. Your choice is ___E_____ 3. A subclass inherits _____________ from its superclasses. a.private data b.protected data c.public data d.a and c e.b and c Your choice is _____E ___ 4. When you implement a method that is defined in a superclass, you __________ the original method. a. overload b. override c. copy d. call Your choice is ___B_____ 5. Analyze the following code. class Test { public static void main(String[] args) { Inner inner = new Inner(); System.out.println(inner.k); } private class Inner { protected int k; } } a. The program has a syntax error because the Inner class does not have a constructor and you cannot create an object from it. b. The program has a syntax error because the Inner class is private and it cannot be accessed in the main method . c. The program has a syntax error because k is protected in the Inner class and it cannot be accessed in the main method. d. The program has a syntax error because the Inner class is not static and it cannot be used to create an object in the main method. Your choice is ____D____ 6. . Which of the following possible modifications will fix the errors in this code? public class Test { private double code; public double getCode() { return code; } protected abstract void setCode(double code); } a. Remove abstract in the setCode method declaration. b. Change protected to public. c. Add abstract in the class declaration. d. b and c. Your choice is ___D_____ Thanks again for any insight. This forum has made my learning experience a lot easier.
http://www.dreamincode.net/forums/topic/39148-java-final-exam-review-sheet/
CC-MAIN-2016-50
refinedweb
356
79.56
Opened 11 years ago Closed 11 years ago Last modified 10 years ago #1530 closed enhancement (fixed) [patch] making distinct=True work with get_count Description Currently get_count() ignores a distinct=True argument. This patch fixes that. Unfortunately, company firewall issues don't allow me to use svn, so I don't have an svn-diff patch. Sorry about pasting code into the ticket body. For the same reason, I'm using the 0.91 tarball, not the svn version, though I believe the patch is the same for both (I don't think the method in question has changed). In magic-removal, the same idea should work, but it looks like the syntax would be slightly different. Here's the changed method in django/core/meta/__init__.py (commented out lines are the originals, with the changed version below them): def function_get_count(opts, **kwargs): kwargs['order_by'] = [] kwargs['offset'] = None kwargs['limit'] = None kwargs['select_related'] = False # _, sql, params = function_get_sql_clause(opts, **kwargs) select, sql, params = function_get_sql_clause(opts, **kwargs) cursor = db.db.cursor() # cursor.execute("SELECT COUNT(*)" + sql, params) cursor.execute("SELECT COUNT(" + (kwargs.get('distinct') and "DISTINCT %s" % select[0] or "*") + ")" + sql, params) return cursor.fetchone()[0] Change History (4) comment:1 Changed 11 years ago by comment:2 Changed 11 years ago by I was looking over this patch and had a "wait a minute" thought... What's the use-case for this? In which case would get_count(distinct=True) return a different result than get_count()? The distinct option uses SELECT DISTINCT across every row, and each row is guaranteed to be distinct because it requires a primary key. comment:3 Changed 11 years ago by Yeah, see, this is why I asked on django-dev first ;). Its possible I'm missing something, but here's my use case: class Category(meta.Model): name = meta.CharField(maxlength=100) class Business(meta.Model): name = meta.CharField(maxlength=100) category = meta.ManyToManyField(Category) >>> c1 = categories.Category(name='pizzarias') >>> c2 = categories.Category(name='pizza restaurants') >>> cpk = businesses.Business(name="Bob's pizza") >>> cpk.set_category([c1.id, c2.id]) >>> businesses.get_count(category__name__icontains='pizza') 2 >>> businesses.get_list(category__name__icontains='pizza') ["Bob's pizza", "Bob's pizza"] >>> businesses.get_count(category__name__icontains='pizza', distinct=True) # with this patch 1 >>> businesses.get_list(category__name__icontains='pizza', distinct=True) ["Bob's pizza"] (sorry about any errors introduced by simplifying this) Basically it looks like the generated SQL is causing a hit for each category that matches the criteria. Now that I think about it though, it may just be a coincidence that this patch is working for my case, because its distinguishing on the business.id, which just happens to be what select[0] gives in this case? I'm not enough of an SQL guru for this, I just know this works for my particular use. Oops, sorry, didn't mean to submit as anonymous.
https://code.djangoproject.com/ticket/1530
CC-MAIN-2016-50
refinedweb
473
51.55
The Resource Description Framework, or RDF, enables data to be decentralized and distributed. RDF models can be merged together easily, and serialized RDF can be simply exchanged over HTTP. Applications can be loosely coupled to multiple RDF data sources over the Web. At PlanetRDF.com, for example, we syndicate weblogs from authors who provide their content as RDF in a RSS 1.0 feed. The URLs of the authors' feeds are themselves held in an RDF graph, called bloggers.rdf. But how can you find and manipulate the data you need within RDF graphs? The SPARQL Protocol And RDF Query Language (SPARQL) is currently under discussion as a W3C Working Draft. SPARQL builds on previous RDF query languages such as rdfDB, RDQL, and SeRQL, and has several valuable new features of its own. In this article, we'll use the three types of RDF graph that drive PlanetRDF -- FOAF graphs describing contributors, their RSS 1.0 feeds, and the bloggers graph -- to demonstrate some of the interesting things SPARQL queries can do with your data. Implementations of SPARQL exist for a variety of platforms and languages; this article will focus on the Jena Semantic Web Toolkit for the Java platform. This article assumes that you have a working knowledge of RDF, and are familiar with RDF vocabularies such as Dublin Core, FOAF, and RSS 1.0. It also assumes you have some experience with the Jena Semantic Web Toolkit. To get up to speed on all of these technologies, check out the links in the Resources section below. Anatomy of a simple SPARQL query Let's start by looking at PlanetRDF's bloggers.rdf model. It is fairly straightforward, using the FOAF and Dublin Core vocabularies to provide a name, a blog title and URL, and an RSS feed description for each blog contributor. Figure 1 shows the basic graph structure for a single contributor. The full model simply repeats this structure for each blog that we aggregate. Figure 1. Basic graph structure for a single contributor in bloggers.rdf Now let's look at a very simple SPARQL query over the bloggers model. The query, in English, says, "Find the URL of the blog by the person named Jon Foobar," and is shown in Listing 1: Listing 1. SPARQL query to find the URL of a contributor's blog The first line of the query simply defines a PREFIX for the FOAF namespace, so that you don't have to type it in full each time it is referenced. The SELECT clause specifies what the query should return -- in this case, a variable named url. SPARQL variables are prefixed with either ? or $ -- the two are interchangeable, but I'll stick to ? in this article. FROM is an optional clause that provides the URI of the dataset to use. Here, it's just pointing to a local file, but it could also indicate the URL of a graph somewhere on the Web. Finally, the WHERE clause consists of a series of triple patterns, expressed using Turtle-based syntax. These triples together comprise what is known as a graph pattern. The query attempts to match the triples of the graph pattern to the model. Each matching binding of the graph pattern's variables to the model's nodes becomes a query solution, and the values of the variables named in the SELECT clause become part of the query results. In this example, the first triple in the WHERE clause's graph pattern matches a node with a foaf:name property of "Jon Foobar," and binds it to the variable named contributor. In the bloggers.rdf model, contributor will match the foaf:Agent blank-node at the top of Figure 1. The graph pattern's second triple matches the object of the contributor's foaf:weblog property. This is bound to the url variable, forming a query solution. SPARQL support in Jena is currently available via a module called ARQ. In addition to implementing SPARQL, ARQ's query engine can also parse queries expressed in RDQL or its own internal query language. ARQ is under active development, and is not yet part of the standard Jena distribution. However, it is available from either Jena's CVS repository or as a self-contained download. It's simple to get ARQ up and running. Just grab the latest ARQ distribution (see the Resources section below for a link), unpack it, and set the environment variable ARQROOT to point to the ARQ directory. You may also need to restore read and execute permissions to the contents of the ARQ bin directory. It's convenient to add the bin directory to your execution path, as it contains wrapper scripts to invoke ARQ from the command line. To make sure that you are all set, call sparql from the command line, and make sure you see its usage message. All these steps are illustrated in Listing 2, which assumes that you are working on a UNIX-like platform, or with Cygwin under Windows. (ARQ also ships with .bat scripts to use under Windows, but their usage will vary slightly from the example shown here.) Listing 2. Setting up your environment to use Jena ARQ Executing SPARQL queries from the command line Now you're ready to run a SPARQL query (see Listing 3). We'll use the dataset and query from Listing 1. Because the query uses the FROM keyword to specify the graph to use, it is necessary only to provide the location of the query file to the sparql command. However, the query needs to be run from the directory containing the graph, because it is specified using a relative URL in the query's FROM clause. Listing 3. Executing a simple query with the sparql command Sometimes, it makes sense to omit the FROM clause from a query. This allows a graph to be passed to the query when it is executed. Avoiding binding the dataset to the query is good practice when using SPARQL from application code -- it allows the same query to be reused with different graphs, for instance. A graph is specified at runtime on the command line with the sparql --data URL option, where URL is the graph's location. This URL could either be the location of a local file or the Web address of a remote graph. Executing SPARQL queries with the Jena API While the command-line sparql tool is useful for running standalone queries, Java applications can call on Jena's SPARQL capabilities directly. SPARQL queries are created and executed with Jena via classes in the com.hp.hpl.jena.query package. Using QueryFactory is the simplest approach. QueryFactory has various create() methods to read a textual query from a file or from a String. These create() methods return a Query object, which encapsulates a parsed query. The next step is to create an instance of QueryExecution, a class that represents a single execution of a query. To obtain a QueryExecution, call QueryExecutionFactory.create(query, model), passing in the Query to execute and the Model to run it against. Because the data for the query is provided programmatically, the query does not need a FROM clause. There are several different execute methods on QueryExecution, each performing a different type of query (see the sidebar entitled "Other types of SPARQL queries" for more information). For a simple SELECT query, call execSelect(), which returns a ResultSet. The ResultSet allows you to iterate over each QuerySolution returned by the query, providing access to each bound variable's value. Alternatively, ResultSetFormatter can be used to output query results in various formats. Listing 4 shows a simple way to put these steps together. It executes a query against bloggers.rdf and outputs the results to the console. Listing 4. Executing a simple query using Jena's API Writing more complex queries So far, you've seen two ways to run a simple SPARQL query: using the command-line sparql utility, and using Java code with the Jena API. In this section, I'll introduce more of SPARQL's features, and the more complex queries they enable. RDF is often used to represent semi-structured data. This means that two nodes of the same type in a model may have different sets of properties. For instance, a description of a person in a FOAF model may consist of only an e-mail address; alternatively, it could incorporate a real name, IRC nicknames, URLs of photos depicting the individual, and so on. Listing 5 shows a very small FOAF graph, expressed in Turtle syntax. It contains descriptions of four fictional people, but the descriptions each have different sets of properties. Listing 5. A small FOAF graph describing four people Suppose you want to write a query that returns the name of every person described by the graph in Listing 5, along with a link to a photograph for each, if one's available. A SELECT query whose graph pattern included foaf:depiction would only find three solutions. Liz Somebody would not form a solution, because she has a foaf:name but no foaf:depiction property, and needs both to match the query. Help is at hand in the form of SPARQL's OPTIONAL keyword. Optional blocks define additional graph patterns that do not cause solutions to be rejected if they are not matched, but do bind to the graph when they can be matched. Listing 6 demonstrates a query that finds the foaf:name of each person in the FOAF data in Listing 5, and then optionally finds the accompanying foaf:depiction. Listing 6. Querying FOAF data with an optional block Listing 7 shows the results of running the query in Listing 6. While all query solutions contain the person's name, the optional graph pattern is only bound when a foaf:depiction property exists; otherwise, it is simply omitted from the solution. In this regard, the query is similar to a left outer join in SQL. Listing 7. Results of the query from Listing 6 An optional block can contain any graph pattern, not just a single triple as shown in Listing 6. The whole query pattern in an optional block must be matched in order for the optional pattern to form part of a query solution. If a query has multiple optional blocks, they act independently of one another -- each one may be omitted from, or present in, a solution. Optional blocks can also be nested, in which case the inner optional block is only considered when the outer optional block's pattern matches the graph. FOAF graphs use people's e-mail addresses to uniquely identify them. In the interests of privacy, some people prefer to use hashcodes of e-mail addresses. Plain text e-mail addresses are expressed using the foaf:mbox property, while hashcodes of e-mail addresses are expressed using the foaf:mbox_sha1sum property; the two are usually mutually exclusive in a FOAF description of a person. In situations like this, you can use SPARQL's alternative matches feature to write queries that return whichever of the properties is available. Alternative matches are defined by stating multiple alternative graph patterns, with the UNION keyword between them. The query shown in Listing 8 finds the name of each person in the FOAF graph of Listing 5, along with either their foaf:mbox or their foaf:mbox_sha1sum. M Benn is not a query solution, because he has neither a foaf:mbox or a foaf:mbox_sha1sum property. In contrast with OPTIONAL graph patterns, exactly one of the alternatives must be matched by any query solution; if both branches of the UNION match, two solutions will be generated. Listing 8. A query with alternative matches, and its results The FILTER keyword in SPARQL restricts the results of a query by imposing constraints on values of bound variables. These value constraints are logical expressions that evaluate to boolean values, and may be combined with logical && and || operators. For instance, a query that returns a list of names could be modified with a filter to return only names that match a given regular expression. Or, as shown in Listing 9, items in an RSS feed published between two dates can be found with a filter that places bounds on items' publication dates. Listing 9 also shows how SPARQL's XPath-style casting feature is used (here to cast the date variable into an XML Schema dateTime value), and how you can specify the same datatype on literal date strings with ^^xsd:dateTime. This ensures that the date comparison is used in the query, rather than standard string comparison. Listing 9. Using a filter to retrieve RSS feed items published in April 2005 Working with multiple graphs So far, all of the queries I've demonstrated have involved datasets consisting of a single RDF graph. In SPARQL terminology, these queries have run against the background graph. The background graph is what is specified by a query's FROM clause, by the sparql command's --data switch, or by passing a model to QueryExecutionFactory.create() when using Jena's API. In addition to the background graph, SPARQL can query any number of named graphs. These additional graphs are identified by their URIs, and are each distinct within a query. Before examining the ways that named graphs can be used, I'll explain how to provide them to a query. As with the background graph, named graphs can be specified within the query itself, using FROM NAMED <URI>, where URI specifies the graph. Alternatively, named graphs can be provided to the sparql command with --named URL, with the URL giving the location of the graph. Finally, Jena's DataSetFactory class can be used to specify named graphs to be queried programmatically. Named graphs are used within a SPARQL query with the GRAPH keyword, in conjunction with either a graph URI or a variable name. This keyword is followed by a graph pattern to match against the graph in question. Finding matches in a specific graph When the GRAPH keyword is used with a graph's URI (or a variable already bound to a graph's URI), the graph pattern is applied to whichever graph is identified by that URI. If matches are found in the specified graph, they form part of a query solution. In Listing 10, two named FOAF graphs are passed to the query. Query solutions are those people's names that are found in both of the graphs. Note that the nodes representing people in each of the two FOAF graphs are blank nodes, and have scope only within the graph that contains them. This means that the same person node can not exist in both named graphs in the query, and so different variables ( x and y) must be used to represent them. Listing 10. A query to find people described in two named FOAF graphs Finding the graph that contains a pattern The other way to use GRAPH is to follow it with an unbound variable. In such a case, the graph pattern is applied to each of the named graphs available to the query. If the pattern matches against one of the named graphs, then that graph's URI is bound to the GRAPH's variable. Listing 11's GRAPH clause matches on each person node in the named FOAF graphs given to the query. The matched person's name is bound to the name variable, and the graph_uri variable binds to the URI of the graph that matched the pattern. The results of the query are also shown. One name, A. N. O'Ther, is matched twice, because that person is described in both jon-foaf.rdf and liz-foaf.rdf. Listing 11. Determining which graph describes different people Combining background data and named graphs Queries may also use background data in conjunction with named graphs. Listing 12 uses the live aggregated RSS feed from PlanetRDF.com as background data, and queries it in conjunction with a named graph containing my own FOAF profile. The idea is to create a personalized feed by finding the most recent ten posts by bloggers that I know. The first part of the query finds the node that represents me in the FOAF file, and then finds the names of the people that the graph says I know. The second part looks for items in the RSS feed that are created by those people. Finally, the result set is sorted by the items' creation date, and limited to return only ten results. Listing 12. Getting a personalized live PlanetRDF feed While this query simply returns a list of titles, names, and URLs, a more complex query could extract all of the data present in the matched items. Using SPARQL's XML results format (see the sidebar titled "Query results in XML format") in conjunction with an XSL stylesheet, it would be possible to create a personalized HTML view of the blog items, or even produce another RSS feed. The examples in this article should help you to understand the fundamental features and syntax of SPARQL, along with the benefits it brings to RDF applications. You've seen how SPARQL allows you to approach the semi-structured nature of real-world RDF graphs, with the aid of optional and alternative matches. Examples using named graphs have shown you how combining multiple graphs in SPARQL opens up your querying options. You've also seen how simple it is to run SPARQL queries from Java code using Jena's API. There's a lot more to SPARQL than it is possible to cover here, so do use the Resources below to find out more about SPARQL's features. Look at the SPARQL spec to learn in detail about SPARQL's built-in functions, operators, query forms, and syntax, or to see many more example SPARQL queries. Of course, the best way to learn about SPARQL is by writing some queries of your own. Just grab some RDF data from the Web, download the Jena ARQ module, and start experimenting! - "Introduction to Jena," also by Philip McCarthy (developerWorks, June 2004), provides an overview of the Jena Semantic Web Toolkit, including details of the RDQL query language. - The latest version of the SPARQL specification provides the definitive description of SPARQL's query syntax and functionality. - Dave Beckett has produced a compact SPARQL Language Quick Reference that you can print out and pin up in your cube. - SPARQL Query Results XML Format describes the results format discussed in "Query results in XML format." - The Jena SourceForge project hosts documentation and downloads of the Jena Semantic Web Toolkit. - SPARQLer is an online demo of Jena's SPARQL query engine. You can use it to experiment with SPARQL queries. - Dave Beckett's Rasqal RDF Query Library is an open source C library that supports SPARQL, and has various language bindings. - The FOAF Project is an experiment in describing people and relationships using a machine-readable RDF vocabulary. The FOAF Vocabulary Specification defines the FOAF terms used in this article. - The Dublin Core Metadata Element Set is standard collection of commonly-used metadata terms. It is employed by many RDF vocabularies and formats, such as FOAF and RSS 1.0. - SPARQL's graph patterns are based on the syntax of Turtle -- Terse RDF Triple Language. - PlanetRDF.com aggregates weblogs of developers in the semantic Web community, providing a convenient means to keep up with developments in the field. This article uses PlanetRDF's RSS feed and RDF blogroll in its examples. - Get involved in the developerWorks community by participating in developerWorks blogs. - You'll find articles about every aspect of Java programming in the developerWorks Java technology zone. - Browse for books on these and other technical topics..
http://www.ibm.com/developerworks/java/library/j-sparql/
crawl-003
refinedweb
3,295
60.95
Each Answer to this Q is separated by one/two green lines. What are the most common operations that would cause a NaN, in Python, which originate while working with NumPy or SciPy? For example: 1e500 - 1e500 >>> nan What is the reasoning for this behavior and why does it not return 0? If you do any of the following without horsing around with the floating-point environment, you should get a NaN where you didn’t have one before: 0/0(either sign on top and bottom) inf/inf(either sign on top and bottom) inf - infor (-inf) + infor inf + (-inf)or (-inf) - (-inf) 0 * infand inf * 0(either sign on both factors) sqrt(x)when x < 0 fmod(x, y)when y = 0or xis infinite; here fmodis floating-point remainder. The canonical reference for these aspects of machine arithmetic is the IEEE 754 specification. Section 7.1 describes the invalid operation exception, which is the one that is raised when you’re about to get a NaN. “Exception” in IEEE 754 means something different than it does in a programming language context. Lots of special function implementations document their behaviour at singularities of the function they’re trying to implement. See the man page for atan2 and log, for instance. You’re asking specifically about NumPy and SciPy. I’m not sure whether this is simply to say “I’m asking about the machine arithmetic that happens under the hood in NumPy” or “I’m asking about eig() and stuff.” I’m assuming the former, but the rest of this answer tries to make a vague connection to the higher-level functions in NumPy. The basic rule is: If the implementation of a function commits one of the above sins, you get a NaN. For fft, for instance, you’re liable to get NaNs if your input values are around 1e1010 or larger and a silent loss of precision if your input values are around 1e-1010 or smaller. Apart from truly ridiculously scaled inputs, though, you’re quite safe with fft. For things involving matrix math, NaNs can crop up (usually through the inf - inf route) if your numbers are huge or your matrix is extremely ill-conditioned. A complete discussion of how you can get screwed by numerical linear algebra is too long to belong in an answer. I’d suggest going over a numerical linear algebra book (Trefethen and Bau is popular) over the course of a few months instead. One thing I’ve found useful when writing and debugging code that “shouldn’t” generate NaNs is to tell the machine to trap if a NaN occurs. In GNU C, I do this: #include <fenv.h> feenableexcept(FE_INVALID);
https://techstalking.com/programming/python/what-are-some-possible-calculations-with-numpy-or-scipy-that-can-return-a-nan-closed/
CC-MAIN-2022-40
refinedweb
452
67.08
This post aims to show some first steps with the Stream Machine platform. The target audience is developers, data engineers and possibly data scientists. This post uses Python, but it can similarly be done with Stream Machine's Java driver. About me: I'm Bart van Deenen, lead engineer of Stream Machine, so I should sort of know what I'm talking about :-). This post is meant to be unbiased, and from the perspective of the developer. Stream Machine Stream Machine promises to provide Lightning fast, privacy secured, customer data - you can actually use. So what does this actually mean? It means that Stream Machine is a system that... - ...accepts events with a strictly defined serialization format (currently Apache Avro and Json-Schema are supported). Any valid schema can be used, but needs to be registered by Stream Machine. - ...events refer to a meta-schema (the so-called schema definition) that defines which fields in the event schema (the so-called serialization schema) contain Personally Identifiable Information (for convenience referred to as PII or PII Data). - ...events refer to customizable validation rules that define field value validity. - ...the events are processed with a highly available fault tolerant stream processing system that encrypts all PII field values. The encryption keys are rotated every 24 hours, and this leads to a GDPR compliant stream of event data that can be used by everyone in your company. During the 24 hours, the encrypted values remain static. - ...each event contains consent-level information, and only those events that allow decryption of PII data for certain purposes will be decrypted into decrypted stream(s) that can only be used by those inside your company that are allowed. This post uses a debugging output of the stream data that uses server-sent events. Production level output streams require hooking up our internal Apache Kafka streams. AWS S3 and Google Cloud Storage buckets can be used for batch processing. This will be explored in a next blog post. The plan I'm going to build a Python application that mimics users clicking around on a dummy web-shop, that will send a click stream to Stream Machine. I want to retrieve the anonymized data from a Google Cloud bucket, and show them in a Jupyter notebook. I also want to see that only for those simulated users that have given full personalized marketing permissions I retrieve their click stream events. This first post just gets the basics working, i.e. sending events to Stream Machine, and retrieving them. The steps An account I went to streammachine.io to register an account, and after confirming my email, I was shown this page: Let's create a new stream OK, I'm going to create a stream named clickies. It turns out there's currently just one schema, named 'clickstream', so let's pick that. Once you click the view credentials button, you get a Stream Machine credentials json. It's important to store this in a file somewhere, otherwise you can't get at your data. credentials.json { "IN": { "billingId": "bart-strm5", "clientId": "....", "secret": "..." }, "OUT": { "0": { "consentLevels": [ 0 ], "clientId": ".....", "secret": "......" }, "1": { "consentLevels": [ 1 ], "clientId": "....", "secret": "........." } } } The clientId and secret fields above are your secrets, that the Stream Machine driver uses to authenticate in order to retrieve a JWT. This is used for each subsequent communication with the Stream Machine endpoints. For the remainder, I assume you've saved this in a file named credentials.json in your working directory. Let's send an event! I'm following along with the Python example in the documentation. I'm going to use the syncsender because I want to play with it in ipython. python3 -m venv venv . venv/bin/activate pip install ipython streammachine-driver streammachine-schemas-catalog-clickstream-avro pip freeze | grep streammachine streammachine-avro==0.0.1 streammachine-driver==0.0.8 streammachine-schemas-catalog-clickstream-avro==0.0.3 streammachine-schemas-common==0.0.3 Ok, let's start ipython $> ipython Python 3.9.0 (default, Oct 10 2020, 14:22:51) # import a class that matches the structure of the clickstream schema from clickstream.io.streammachine.schemas.strmcatalog.clickstream \ import ClickstreamEvent from streammachine.driver import StreamMachineEvent, current_time_millis from streammachine.driver.client.syncsender import SyncSender event = ClickstreamEvent() import json creds = json.load(open("credentials.json")) sender = SyncSender(creds['IN']['billingId'], creds['IN']['clientId'], creds['IN']['secret']) sender.start() sender.wait_ready() sender.send_event(event) After the last line I got an html error which said basically 'no schema' and a 500 statuscode. Let's dig a little deeper in the example. Ah, I need to set the name of the schema inside the event: event.strmMeta.schemaId = "clickstream" sender.send_event(event) # Error while sending event to Stream Machine (), # response status = 400, response: # regex clickstream/customer/id '' doesnt match '^.+$' Nice, I'm talking to Stream Machine! So the customer needs at least one character? Weird... event.customer.id="hi there" sender.send_event(event) # Error while sending event to Stream Machine (), # response status = 400, response: regex # clickstream/url '' doesnt match '^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]' So how come? This is because the Stream Machine endpoint does not just validate the form of the event data, but also the contents. This is defined in the schema (in this case the clickstream schema). Here you see the various validations that are applied to the event after deserialization. So let's make a valid event from the example: from random import randint def create_avro_event(sessionid) -> StreamMachineEvent: event = ClickstreamEvent() event.abTests = ["abc"] event.eventType = "button x clicked" event.customer.id = "integration-test" event.referrer = "" event.userAgent = "Mozilla/5.0" event.producerSessionId = sessionid event.conversion = 1 event.strmMeta.timestamp = current_time_millis() event.strmMeta.schemaId = "clickstream" event.strmMeta.nonce = 0 event.strmMeta.consentLevels = [0, 1, 2] event.url = "" return event sessionid = f"session-{randint(1000,10000)}" event = create_avro_event(sessionid) r = sender.send_event(event) print(r) None Oh well, it's not complaining, so let's see about the output. For this we use a server-sent events endpoint that will provide JSON output of the event. Note that this is not suitable for production loads! It's merely intended for testing and debugging purposes. In another terminal in the same directory: import asyncio, json, logging, sys from streammachine.driver import StreamMachineClient, ClientConfig logging.basicConfig(stream=sys.stderr) creds = json.load(open("credentials.json")) async def event_handler(event): print(json.loads(event)) async def main(): config = ClientConfig(log_level=logging.DEBUG) client = StreamMachineClient(creds['IN']['billingId'], creds['IN']['clientId'], creds['IN']['secret'], config) await client.start_timers() await client.start_receiving_sse(True, event_handler) asyncio.run(main()) Ok back to the first terminal, and send an event: sender.send_event(create_avro_event()) Hmmm, nothing happens. And again! Well it turns out, that the receiver uses server-sent events, and there's some batching going one somewhere in a cloud loadbalancer. That's easy to solve. Run it in a loop, and you get a lot of data in your receiver! import time while True: sender.send_event(create_avro_event(sessionid)) time.sleep(0.2) You'll get an occasional warning in the output, there are still some improvements to be made with the Python asyncio client. Looking at one event in the receiving terminal, I get this: { "strmMeta": { "schemaId": "clickstream", "nonce": 190417502, "timestamp": 1603288736020, "keyLink": 44384987, "billingId": "bart-strm5", "consentLevels": [ 0, 1, 2 ] }, "producerSessionId": "AS7qq8aWID2mAnEISXK4Qwz+JhykZK3xGEjYu7oI+A==", "url": "", "eventType": "button x clicked", "referrer": "", "userAgent": "Mozilla/5.0", "conversion": 1, "customer": { "id": "AS7qq8YNkAEw2r4NuqJTEdoc/xCIUya1wzu/djO3XPbN6qcRNA==" }, "abTests": [ "abc" ] } Just looking at it, I can see that producerSessionId and customer/id seem to have been encrypted, which fits the clickstream definition. Because the event we create has maximum consentLevel included, we should be able to get a decrypted stream as well. Let's modify the receiver handler: async def main(): config = ClientConfig(log_level=logging.DEBUG) client = StreamMachineClient(creds['IN']['billingId'], creds['OUT']['1']['clientId'], creds['OUT']['1']['secret'], config) await client.start_timers() await client.start_receiving_sse(True, event_handler) asyncio.run(main()) Start sending data again and we get decrypted events { "strmMeta": { "schemaId": "clickstream", "nonce": 190417502, "timestamp": 1603288736020, "keyLink": 44384987, "billingId": "bart-strm5", "consentLevels": [ 0, 1, 2 ] }, "producerSessionId": "session-432", "url": "", "eventType": "button x clicked", "referrer": "", "userAgent": "Mozilla/5.0", "conversion": 1, "customer": { "id": "integration-test" }, "abTests": [ "abc" ] } Conclusions We can send data into Stream Machine, and receive them privacy safe and of guaranteed quality. The next post in this series will show how to get all these data into a Google Cloud bucket, and how to use those data in a Jupyter notebook. Discussion
https://practicaldev-herokuapp-com.global.ssl.fastly.net/bvdeenen/first-steps-with-streammachine-io-39n7
CC-MAIN-2020-50
refinedweb
1,422
59.3
RethinkDB supports a native binary object type, letting you use ReQL to store binary objects directly in the database. The ReQL driver will transparently translate between the ReQL type and the Ruby String class. Note: The binary object type is meant for data that cannot be reliably stored as UTF-8 strings, such as uploaded files. If you’re working with data that can be stored as strings, it’s usually easier to stick to the string data type. For these examples, we’ll assume that the RethinkDB connection is available in global scope as conn. It’s a common task for web applications to accept file uploads from users; with RethinkDB you can store these files directly in the database. def save_file(file_path, save_name, user_id) # Store the file at 'file_path' with the filename 'save_name'. fh = File.open(file_path, 'rb') contents = fh.read() fh.close() r.table('files').insert({ :user_id => user_id, :filename => save_name, :file => r.binary(contents) }).run(conn) end In save_file, we pass a path to the uploaded file (which may be in a temporary storage directory, even with a temporary name depending on the uploading library we’ve used), the name to save the file with, and the id of the user who’s uploaded the file. The binary ReQL command is used to store the file’s contents as a binary object in the file field. def get_user_file_ids(user_id) # Retrieve the IDs of previously-saved files for a user as an array of # hashes: [ { :id => x, :filename => y }, ...] return r.table('files').filter({ :user_id => user_id }). pluck('id', 'filename').run(conn) def get_file(file_id): """ Retrieve a file by its ID. Returns a hash with 'filename' and 'file' keys. """ return r.table('files').get(file_id).pluck('file', 'filename').run(conn) Then, there are two functions for retrieving files: one to retrieve a directory of a user’s uploaded files ( get_user_file_ids) and one to retrieve the actual file itself ( get_file). We don’t have to use binary again here; the ReQL driver will return the proper data type for the file field in our object. Here’s another, more fun example: adding Gravatar avatars to user accounts. We can use http to retrieve them. require 'digest' def add_gravatar(user_id): """ Add a gravatar field with the binary avatar icon to user accounts if they have an avatar associated with their email address. """ email = r.table('users').get(user_id)['email'].run(conn) hash = Digest::MD5.hexdigest email gravatar_url = '' + hash + '?d=retro' r.table('users').get(user_id).update({ 'gravatar': r.http(gravatar_url, :result_format => 'binary') }).run(conn) Where’s r.binary? You don’t need it in this case, because r.http will return a binary object with the :result_format => 'binary' option. (If the MIME type on the sending server is set correctly, you can even leave that off, and r.http will figure out the correct type.)
https://rethinkdb.com/docs/storing-binary/ruby/
CC-MAIN-2019-51
refinedweb
474
65.52
08 March 2010 16:27 [Source: ICIS news] By Nigel Davis ?xml:namespace> LONDON The cost driven move to lighter cracker feeds in the But the economics have not shifted sufficiently to encourage olefins makers to invest in additional C4s extraction. On-purpose butadiene production based on butane dehydrogenation does not appear to be an economic alternative. There would be no case of the “tail wagging the dog”, delegates at the 5th ICIS World Olefins Conference in Amsterdam were told last week. Butadiene has been and will continue to be a by-product of olefins production. Cracker operators could allow one or two furnaces to run on heavier feed but that appears to be as far as most are prepared to go. The world has changed in a relatively short period. Some of Europe’s crackers and units in Yet the butadiene markets are demanding more. The move towards lower-rolling resistance tyres is driving demand for styrene butadiene rubber (SBR). Other uses in SB latex production, in engineering plastics, nitrile rubbers and elsewhere seem also to be on the rise. The supply/demand situation is most acute in Asia and in ICIS reported on Monday that tightness in the Some in the European market argue for a shift away from quarterly to monthly pricing but customers are resistant. A more responsive pricing mechanism could be a driver for more extraction capacity. The consensus view at the conference, however, was that butadiene supply would remain short and that European customers, which had enjoyed the lowest global prices, would eventually have to pay more competitive rates to keep that supply in “The arbitrage window will have increasing influence on butadiene pricing within European consumers of butadiene have every right to be concerned. The big tyre makers need to keep their synthetic rubber plants filled. Other consumers continue to hunt around for supplies but find prices moving upwards fast. It looks as though demand will continue to put pressure on supply in The dynamic markets in For more on butadi
http://www.icis.com/Articles/2010/03/08/9340806/insight-feedstock-choice-and-operating-rates-will-keep-butadiene.html
CC-MAIN-2014-52
refinedweb
338
50.46
This build started as something simple: a lucky cat which would turn on and off automatically in response to some event. Since lucky cats are associated with good fortune the idea was to make one do this every time I got paid. This was working pretty well but unfortunately, after some over-zealous poking I managed to completely knacker the internals. What you see below is the result of asking ...what else can I do with a gold cat? If you can't see the video above, you can see a still here. The display uses the persistence of vision effect to generate an image 'in the air'. By repeatedly outputting light at a specific point in the rotation, and with a short enough cycle time, the viewer's eye does not register any change in brightness. The flicker in the video is caused by the camera running at 30fps and is less apparent in person. Managing to generate a static image depends on hitting the exact same point on the next turn around the loop. By adding a slight over- or under-scan you can make the message display rotate. The build is described below in parts, including the construction of the motor mechanism, the LED display and the driver board. If you just want the code, jump to the end. There should be enough detail here to hack together your very own lucky message cat! The cat Lucky cats are available to buy quite cheaply and come in various versions and colours. The model I ended up with seems quite common and is recommended, since it has a lot of working room inside. The shell is made entirely of moulded plastic, with a gold sheen. The plastic is flexible, apart from where the shape gives it structural strength. However, the gold colour is very susceptible to solvents in glues. My cat ended up quite patchy by the time I was finished with it. Despite appearances this is not a picture of the inside of my colon. Motor support The original mechanism inside a lucky cat uses an electromagnetic coil coupled with a small controller circuit powered by a single 1.5V battery. The arm is attached to a horizontal beam off which a magnet is suspended on a pendulum. The arm rocking mechanism rests inside on top of 4 legs, which we will use to hold our axel mount (a block of wood). The existing mechanism can be unscrewed from the top by removing the 4 tiny screws via the holes in the base. There wasn't a simple way to make use of the mount to hold a motor, so I replaced it outright with a block of wood 40mm x 40mm x 45mm. To position the axle the block was screwed onto the top of the mechanism legs, using the same screws, and then reassembled the cat. The axle was positioned to be in the middle of the arm hole, marked with a pencil and then drilled through on a drill press. When drilling the axle hole pick a size which is as close-as but slightly wider than the diameter of your axle. Too wide will give wobble, too narrow and it'll get stuck. Motor mechanism The gears, axle and arm-mount connector I used for this build were all taken from the remains of the tank chassis used in the KropBot Mk I. This is a pretty inefficient way to get parts, and you can find better axle and gear parts bundles online. The axle needs to be about 65-75mm long. The 3-6V motor sits on top of the mounting block and is then fastened into place with loops of zip ties. A couple of loops was enough to hold it in place, but still allow for manual adjustment. Because of the gears available the motor could sit directly above the axle gear. A small offset backwards gave it enough space for the gears to mesh, but then the motor gear bumped the inside of the shell. I had to trim the motor axle down with a rotary tool to get it to fit. Depending on whether you offset the motor forward or backward, it might run easier forwards or backwards. Bear that in mind later. To allow power for the LEDs to be transferred across the rotating joint, I used a slip ring. The ones I bought were pretty chunky and to be able to get them inside the cat they needed to be recessed into the support block. The simplest way to do this was cut a chunk out of it. The slip ring was then screwed onto the block for support. After reassembling the cat a few times it was lined up enough to work. While adjusting the block I screwed up my measurement and lopped off a bit too much. I then made things worse by using balsa to build it back up — balsa is too weak for the screws to hold it. Copious amounts of glue was the only answer. Use more glue. Once I was convinced everything lined up, the gear mechanism was disassembled and everything covered in silicone grease. Then it was reassembled, zip-tied and had the crap glued out of it. To fix (some of) the wobble rotating at full speed I packed some folded paper into the space between the axle and the rotating inner ring of the slip ring. With this in place the rotation of the arm pulls the slip-ring with it, and the arm doesn't pull the axle up and down so much. It's not great, but it helps things a little. Circuit The complete schematic for the motor & LED driver circuit for our message cat is shown below. The motor driver circuit is based on an L293D. The L293D is a 16 pin DIP containing two independent H-bridges circuits for dual-motor dual-direction control. Here we're only using a single motor, and usually only drive it in a single direction, so it's a bit of overkill — but it's what I had in my box. The inputs and outputs for each motor are on either side of the package, and there are 2 input pins, 2 output pins and 1 enable pin for each motor. The IC can handle heavy currents and may generate a lot of heat. The 4 grounding pins are provided as a simple way to shed some of this heat, by acting as a basic heatsink. Make sure to solder them all to the board. Since DC motors are inductive loads, and can generate back current when drive power is stopped or reversed. This voltage fluctuation could potentially damage the IC so a small ceramic capacitor is used to dampen this. LEDs The display uses 5 LEDs to give a reasonable, minimal horizontal resolution for text display. This was helpfully also about the right width using SMD LEDs and matched the number of wires available on the slip ring (6; 5 +ve, 1 GND). The vertical size of characters is entirely independent, as it is generated as the arm rotates. It might be possible to fit more SMDs horizontally if you're good at soldering, but you'll need to get a different slip ring and get a different font. Wiring In the initial build the arm was connected by a screw adapter, taken from the cat's original arm mount. With this setup the wires had to enter the arm from the 'outside', and a small hole was drilled in the base of the arm for the wires to feed in. This was replaced after the attachment failed (see later). I drilled a second hole at the knuckle, and the 6 wires were taped together and pushed up and out. Board Five red SMD LEDs were soldered on a small chunk of protoboard. I used red for the appearance, but white LEDs would be considerably brighter. The power wires were soldered from behind, and then the LEDs soldered on top. This wasn't ideal, and they ended up not exactly parallel, but it meant the wires could be kept out of view. There were a few different ways to mount the LED display board on the hand, but I opted to cut a larger hole and recess them into it. Cutting the hole to fit as closely as possible and then relying on glue to make it stay in place. It's a bit of a mess up close, but not noticeable from a distance or when rotating. Control Because there are only 5 LEDs the control can be handled directly by GPIO pins. This keeps the control circuit for those very simple, with just resistors in series. The photo below shows the LEDs wired up to GPIO pins on the Wemos D1 with all pins HIGH. For a quick test run, I wired the Wemos D1 and LEDs up using a breadboard and wrote a quick script to iterate over an array of values spelling out POOP — a palindrome, so it doesn't matter which way the arm spins. Fiddling with the speed showed there was a good bit of leeway for generating messages of different lengths, and I could tune the output so the LEDs landed on the same point (or thereabouts) on each rotation. You can see from the blur on the mounting block that this was shaking quite a bit at the time — the final version runs the arm quite a bit slower so it doesn't try and get airborne. Driver board The goal for the driver board itself was to be able to slot the board in under the main gear, with enough clearance for it to rotate cleanly. The board was wired up on a small chunk of protoboard — wide enough to fit the D1 across the board, with space below for the L293D. Resistors were mounted under the D1 to save vertical space. The completed & cropped control board, with motor drive wires (thick purple, thick yellow), LED driver wires (thin 5 colours) and motor power in (thick red, thick black). The underside is a bit messier than it should be as I stupidly tried to rework the L293D wiring in the process of moving from the breadboard. Thankfully I didn't release any magic smoke. Don't be me. If you need to change something, re-prototype on the breadboard first. With the wiring in place, I did a quick test everything with the control board to ensure everything was working as expected. After fixing a few dodgy solder joints, all the LEDs lit and the motor could turn both ways. The control board mounted with screws onto the side of the motor mount. It landed just short of where the drive cog, leaving it free to rotate without needed any adjustment. Assembly & final bodges Unfortunately the combined height of the D1 on top of the control board and motor mount was too large to fit through hole in the bottom of the cat shell. The shell was pared back with a craft knife until it fit. The motor mount rotated up and around until it poked out the arm hole. I also had to trim the motor drive shaft with a dremel as it was pressing against the inside. The hole in the back of the cat — from previous misadventures — was taped up to get rid of sharp edges. This is where the USB power lead enters to power the D1, the motor wires (seen in the photo below) actually exit via the base to the AA battery pack. The photo below shows the wires for the LEDs in the original arrangement where they enter the base of the arm. They knocked against the shell while rotating making an annoying knocking sound. I was looking for ways to fix this, when the mount-lock on the end of the arm cracked open presenting a solution: more glue. The mount was cut off, the wires moved to the inside and the arm pushed over the mount, then glued in place. The final step was to mount the cat on top of a battery pack — for stability/weight as well as power. The bottom of the battery case was also affixed to the table with velcro pads, to minimise the shaking while taking photo & video of it running. Code The display code needs to do a few things — - Get the arm spinning at a fast enough speed but not so fast we can't get text out in time. The speed should be constant(-ish). - Turn the LEDs on and off, as close to row-by-row as possible, to generate characters as the arm rotates. Using a font with max 5-pixel width. - Time both the above so that each time the arm rotates the display of text happens in roughly the same place as the last rotation. With all of those in place, we should have a functional persistance-of-vision LED display for short messages. Below is breakdown of the code I used to achieve this on my lucky cat. Character Set For the text we're using a simple 5x7 pixel display font, based on Adafruit's glcdfont.c. This has been converted to Python list of tuple structure. The character set is in ASCII order, including the first 128 symbols. A few custom symbols were added on top, including — You can generate your own custom characters using this tool. Make sure to select column major and little endian. There is no width 5 option, or height 7 option. Use 6 & 8 and keep to the top left. After generating copy the first 5 values only. Each character is represented by a tuple of 5 int values (with byte range 0-255) covering the 5 pixel width. The binary representation of each of these values determines whether a given pixel is on/off vertically down the character. This wastes a lot of memory, but keeps the later code simple. CHARSET = [ (0, 0, 0, 0, 0), (62, 91, 79, 91, 62), (62, 107, 79, 107, 62), (28, 62, 124, 62, 28), (24, 60, 126, 60, 24), (28, 87, 125, 87, 28), (28, 94, 127, 94, 28), (0, 24, 60, 24, 0), (255, 231, 195, 231, 255), (0, 24, 36, 24, 0), (255, 231, 219, 231, 255), (48, 72, 58, 6, 14), (38, 41, 121, 41, 38), (64, 127, 5, 5, 7), (64, 127, 5, 37, 63), (90, 60, 231, 60, 90), (127, 62, 28, 28, 8), (8, 28, 28, 62, 127), (20, 34, 127, 34, 20), (95, 95, 0, 95, 95), (6, 9, 127, 1, 127), (0, 102, 137, 149, 106), (96, 96, 96, 96, 96), (148, 162, 255, 162, 148), (8, 4, 126, 4, 8), (16, 32, 126, 32, 16), (8, 8, 42, 28, 8), (8, 28, 42, 8, 8), (30, 16, 16, 16, 16), (12, 30, 12, 30, 12), (48, 56, 62, 56, 48), (6, 14, 62, 14, 6), (0, 0, 0, 0, 0), # 32: space (0, 0, 95, 0, 0), (0, 7, 0, 7, 0), (20, 127, 20, 127, 20), (36, 42, 127, 42, 18), (35, 19, 8, 100, 98), (54, 73, 86, 32, 80), (0, 8, 7, 3, 0), (0, 28, 34, 65, 0), (0, 65, 34, 28, 0), (42, 28, 127, 28, 42), (8, 8, 62, 8, 8), (0, 128, 112, 48, 0), (8, 8, 8, 8, 8), (0, 0, 96, 96, 0), (32, 16, 8, 4, 2), (62, 81, 73, 69, 62), # 48: 0 (0, 66, 127, 64, 0), (114, 73, 73, 73, 70), (33, 65, 73, 77, 51), (24, 20, 18, 127, 16), (39, 69, 69, 69, 57), (60, 74, 73, 73, 49), (65, 33, 17, 9, 7), (54, 73, 73, 73, 54), (70, 73, 73, 41, 30), (0, 0, 20, 0, 0), (0, 64, 52, 0, 0), (0, 8, 20, 34, 65), (20, 20, 20, 20, 20), (0, 65, 34, 20, 8), (2, 1, 89, 9, 6), (62, 65, 93, 89, 78), (124, 18, 17, 18, 124), # 65: A (127, 73, 73, 73, 54), (62, 65, 65, 65, 34), (127, 65, 65, 65, 62), (127, 73, 73, 73, 65), (127, 9, 9, 9, 1), (62, 65, 65, 81, 115), (127, 8, 8, 8, 127), (0, 65, 127, 65, 0), (32, 64, 65, 63, 1), (127, 8, 20, 34, 65), (127, 64, 64, 64, 64), (127, 2, 28, 2, 127), (127, 4, 8, 16, 127), (62, 65, 65, 65, 62), (127, 9, 9, 9, 6), (62, 65, 81, 33, 94), (127, 9, 25, 41, 70), (38, 73, 73, 73, 50), (3, 1, 127, 1, 3), (63, 64, 64, 64, 63), (31, 32, 64, 32, 31), (63, 64, 56, 64, 63), (99, 20, 8, 20, 99), (3, 4, 120, 4, 3), (97, 89, 73, 77, 67), (0, 127, 65, 65, 65), (2, 4, 8, 16, 32), (0, 65, 65, 65, 127), (4, 2, 1, 2, 4), (64, 64, 64, 64, 64), (0, 3, 7, 8, 0), (32, 84, 84, 120, 64), # 97: a (127, 40, 68, 68, 56), (56, 68, 68, 68, 40), (56, 68, 68, 40, 127), (56, 84, 84, 84, 24), (0, 8, 126, 9, 2), (24, 164, 164, 156, 120), (127, 8, 4, 4, 120), (0, 68, 125, 64, 0), (32, 64, 64, 61, 0), (127, 16, 40, 68, 0), (0, 65, 127, 64, 0), (124, 4, 120, 4, 120), (124, 8, 4, 4, 120), (56, 68, 68, 68, 56), (252, 24, 36, 36, 24), (24, 36, 36, 24, 252), (124, 8, 4, 4, 8), (72, 84, 84, 84, 36), (4, 4, 63, 68, 36), (60, 64, 64, 32, 124), (28, 32, 64, 32, 28), (60, 64, 48, 64, 60), (68, 40, 16, 40, 68), (76, 144, 144, 144, 124), (68, 100, 84, 76, 68), (0, 8, 54, 65, 0), (0, 0, 119, 0, 0), (0, 65, 54, 8, 0), (2, 1, 2, 4, 2), (60, 38, 35, 38, 60), # Custom symbols. (0x0c, 0x1e, 0x3c, 0x1e, 0x0c), # Heart (0x18, 0x3a, 0x3e, 0x2e, 0x0c), # Python (0x1c, 0x3e, 0x7f, 0x73, 0x66), # Aubergine (0x40, 0x71, 0x78, 0x62, 0x40), # Poop (0x3c, 0x57, 0x4c, 0x57, 0x3c), # Cat ] Using the above character table, outputting each character as we rotate the arm would require us to convert each column to binary, select the current vertical position from this, and toggle LED based on the value ( 0 or 1). Rotating at full-whack this is quite a lot to accomplish. If it takes a long time to calculate each row the characters become very large (as the arm rotates while it is happening). If the inter-pixel delay is too large, the characters become distorted. To move as much delay out of the display loop as possible, we can pre-process the character data for a given message and convert it into a straight pixel-array. This eliminates the conversion and lookup from the display loop, turning into a simple iteration. We could speed this up even more using an external shift register. Each row would be drawn by sending a single byte to the register to update all LEDs in a single operation. def build_message_display(message, length): result = [] for char in reversed(message): glyph = CHARSET[ord(char)] build = [] for line in glyph: build.append([1 if c == '1' else 0 for c in "{0:07b}".format(line)]) for y in range(7): result.append([build[x][y] for x in range(5)]) # Blank line between letters result.append([0,0,0,0,0]) result.append([0,0,0,0,0]) # Pad to the vertical resolution of the display. text_len = len(result) if text_len < length: for _ in range(length-text_len): result.append([0,0,0,0,0]) return result Setup For the display we create 5 output pins, one for each LED, and arranged in a list LEDS so we can iterate over them easily in the display code. We also need to setup the output pin to control the LS motor driver. We only actually use Pin(4) since the arm needs to rotate in one direction only. A PWM object is created and set to 30Hz duty cycle. This duty cycle was selected by experimentation. At 30Hz the motor speed is stable enough to not affect the display, and provides a kick long enough to get the motor started against the mechanical resistance at standstill. from machine import Pin, PWM import time p1 = Pin(15, Pin.OUT) p2 = Pin(13, Pin.OUT) p3 = Pin(12, Pin.OUT) p4 = Pin(14, Pin.OUT) p5 = Pin(16, Pin.OUT) LEDS = [p1,p2,p3,p4,p5] m1 = Pin(4, Pin.OUT) m1.off() # Use this if you want the arm to go the other way. # m2 = Pin(0, Pin.OUT) # m2.off() motor = PWM(m1) motor.freq(30) motor.duty(0) Display The final code is our display() method, which we use to display a message. Optional parameters for duration, duty and length need to be tweaked for a given cat, since the max display length depends on how long a rotation takes and the required duty cycle for a given rpm is affected by mechanical weirdness. The default values work for my cat, giving a message which is relatively static visually, with a slight rotation upwards (the right way). def display(message, duration=1000, duty=585, length=101): motor.duty(duty) dispm = build_message_display(message, length) for n in range(duration): for line in dispm: for p, v in zip(LEDS, line): p.on() if v else p.off() time.sleep(0.001) motor.duty(0) The length parameter is the maximum length of message which can be displayed, and is also the length to which any message is padded with space. To display longer messages we could rotate a window over the generated dispm, but this would need some sort of rotation sync detection to ensure the split doesn't end at the front. Complete The video below shows the cat in action, displaying a long-running message including some custom characters. It looks pretty neat. Retrospective This poor cat was been hacked, poked, cut, drilled, sanded and left with a gaping hole in it's back. The motor mechanism was slightly too large and had to be bodged to fit with a wedge on the base, and the axle is slightly misaligned amplifying the wobble. If the alignment and weight distribution was better it might not need to be Velcro'd down while running. It might also sound less like a blender — though that could be wishful thinking. There is quite a bit of space inside the cat (particularly the head). I reckon with a bit better planning I could fit the entire mechanism, batteries and a power supply for the D1 in there. This would allow the unit to run standalone disconnected from power. But that will have to wait til I get a 3D printer for the parts.
https://www.mfitzp.com/turning-a-lucky-cat-into-a-persistence-of-vision-display/
CC-MAIN-2022-27
refinedweb
3,818
75.44
When to Use Categorical Scatterplots - Jul 22 • 5 min read - Key Terms: scatter plot Often times in businesses we want to visualize the distribution from several categorical variables provided in a dataset. To display the distribution of a category of data, typically people use a box plot or histogram. However, sometimes those visualizations may be improperly used. If you have a small number of data points for one category - often 5 - 80 points, I'd recommend you start with a categorical scatter plot for comparison. Below, I'll illustrate a few examples. Import Modules import pandas as pd import seaborn as sns import matplotlib.pyplot as plt % matplotlib inline Set Global Styles for Visualizations sns.set_context('talk') sns.set_style("darkgrid") Example: Tips Dataset In the examples below, I utilize the dataset tips provided in the Seaborn visualization library. Each row in this dataset is a record of a meal at a restaurant. For each meal, the restuarant recorded values for the total bill amount in U.S. dollars, tip amount, gender/sex of the waiter, day, meal and table size. Load flights Dataset df_tips = sns.load_dataset("tips") Preview the First 5 Rows of Data df_tips.head(8) Visualize Total Bill Amount by Table Size This categorical scatter plot below, more specifically called a swarm plot, helps illustrate the count of records for each table size and the distribution of bill amounts by table size. A swarm plot is ideal here because we have so few records of meals with several table sizes such as 1, 5, and 6. Alternatively, if we tried to use a histogram or box plot to illustrate these few records for category, we'd get a false representation of the bill amounts by table size. The reason for that is that it's bad practice to compare just 4 records for a table size of 1 to 156 record for a table size of 2. For the 4 records of table size of 1 person, those could be a false representation since they may have all made very very small purchases and therefore small total_bill amounts in our dataset. sns.catplot(x="size", y="total_bill", kind="swarm", data=df_tips, height=8.5, aspect=.9) plt.xlabel("table size [number of people]", labelpad=15) plt.ylabel("total bill amount [$]", labelpad=15) plt.title("Distribution of Bill Amounts by Table Size", y=1.013); Interpretation of Distribution of Bill Amounts by Table Size There's few records of bill amounts for table sizes of 1, 5, and 6. The restaurant mostly gets table sizes of 2 and 3. Generally, as the table size increases, total bill amount increases. For a table size of 2, most bill amounts are between 10 and 20 U.S. dollars. Visualize Total Bill Amount by Table Size and Gender/Sex To improve on the visualization from above, I'm curious if there's any patterns of bill amounts for tables by waiter or waitresses' gender. sns.catplot(x="size", y="total_bill", kind="swarm", hue='sex', data=df_tips, height=8.5, aspect=.9) plt.xlabel("table size [number of people]", labelpad=15) plt.ylabel("total bill amount [$]", labelpad=15) plt.title("Distribution of Bill Amounts by Table Size", y=1.013); Interpration of Visualization of Total Bill Amount by Table Size and Gender/Sex There's no clear pattern of bill amounts by table size and gender. At a glance, it's likely males have served more tables than females. Males often hold the top few spots for highest bill amount by table size too.
https://dfrieds.com/data-visualizations/when-use-categorical-scatterplots
CC-MAIN-2019-26
refinedweb
591
64.1
DBIx::Class::Manual::Cookbook - Miscellaneous recipes%', '%Fear of Fours%'. Other queries might require slightly more complex logic: my @albums = $schema->resultset('Album')->search({ -or => [ -and => [ artist => { 'like', '%Smashing Pumpkins%' }, title => 'Siamese Dream', ], artist => 'Starchildren', ], }); This results in the following WHERE clause: WHERE ( artist LIKE '%Smashing Pumpkins%' AND title = 'Siamese Dream' ) OR artist = 'Starchildren' For more information on generating complex queries, see "WHERE CLAUSES" in SQL::Abstract.: my $top_cd = $cd_rs->search({}, { order_by => 'rating' })->single; my $top_cd = $cd_rs->search ({}, { order_by => 'rating', rows => 1 })->single; Sometimes you have to run arbitrary SQL because your query is too complex (e.g. it contains Unions, Sub-Selects, Stored Procedures, etc.) or has to be optimized for your database in a special way, but you still want to get the results as a DBIx::Class::ResultSet. This is accomplished by defining a ResultSource::View for your query, almost like you would define a regular ResultSource. package My::Schema::Result::UserFriendsComplex; use strict; use warnings; use base qw/DBIx::Class::Core/; __PACKAGE__->table_class('DBIx::Class::ResultSource::View'); # For the time being this is necessary even for virtual views __PACKAGE__->table($view_name); # # - will exclude this "table": sub sqlt_deploy_hook { $_[1]->schema->drop_table ($_[1]) } When you only want specific columns from a table, you can use columns to specify which ones you need. This is useful to avoid loading columns with large amounts of data that you aren't about to use anyway: my $rs = $schema->resultset('Artist')->search( undef, { columns => [qw/ name /] } ); # Equivalent SQL: # SELECT artist.name FROM artist This is a shortcut for select and as, see below. columns cannot be used together with select and as. The combination of select and as can be used to return the result of a database function or stored procedure as a column value. You use select to specify the source for your column value (e.g. a column name, function, or stored procedure name). You then use as to set the column name you will use to access the returned value: my $rs = $schema->resultset('Artist')->search( {}, { select => [ 'name', { LENGTH => 'name' } ], as => [qw/ name name_length /], } ); # Equivalent SQL: # SELECT name name, LENGTH( name ) # FROM artist Note that the as attribute has absolutely nothing to If your alias exists as a column in your base class (i.e. it was added with add_columns), you just access it as normal. Our Artist class has a name column, so we just use the name accessor: my $artist = $rs->first(); my $name = $artist->name(); If on the other hand the alias does not correspond to an existing column, you have to fetch the value using the get_column accessor: my $name_length = $artist->get_column('name_length'); If you don't like using get_column, you can always create an accessor for any of your aliases using either of these: # Define accessor manually: sub name_length { shift->get_column('name_length'); } # Or use DBIx::Class::AccessorGroup: __PACKAGE__->mk_group_accessors('column' => 'name_length'); See also "Using SQL functions on the left hand side of a comparison". my $rs = $schema->resultset('Artist')->search( {}, { columns => [ qw/name/ ], distinct => 1 } ); my $rs = $schema->resultset('Artist')->search( {}, { columns => [ qw/name/ ], group_by => [ qw/name/ ], } ); my $count = $rs->count; # Equivalent SQL: # SELECT COUNT( * ) FROM (SELECT me.name FROM artist me GROUP BY me.name) me: }); Subqueries are supported in the where clause (first hashref), and in the from, select, and +select attributes. my $cdrs = $schema->resultset('CD'); my $rs = $cdrs->search({ year => { '=' => $cdrs->search( { artist_id => { -ident => 'me.artist_id' } }, { alias => 'sub_query' } )->get_column('year')->max_rs->as_query, }, }); That creates the following SQL: SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE year = ( SELECT MAX(sub_query.year) FROM cd sub_query WHERE artist_id = me.artist_id ) by resorting to literal SQL: $rs->search( \[ 'YEAR(date_of_birth) = ?', 1979 ] ); # Equivalent SQL: # SELECT * FROM employee WHERE YEAR(date_of_birth) = ? To include the function as part of a larger search, use the '-and' keyword to collect the search conditions: $rs->search({ -and => [ name => 'Bob', \[ 'YEAR(date_of_birth) = ?', 1979 ] ]}); # Equivalent SQL: # SELECT * FROM employee WHERE name = ? AND YEAR(date_of_birth) = ? Note: the syntax for specifying the bind value's datatype and value is explained in "DBIC BIND VALUES" in DBIx::Class::ResultSet. See also "Literal SQL with placeholders and bind values (subqueries)" in SQL::Abstract. When your RDBMS does not have a working SQL limit mechanism (e.g. Sybase ASE) and GenericSubQ is either too slow or does not work at all, you can try the software_limit DBIx::Class::ResultSet attribute, which skips over records to simulate limits in the Perl layer. For example: my $paged_rs = $rs->search({}, { rows => 25, page => 3, order_by => [ 'me.last_name' ], software_limit => 1, }); You can set it as a default for your schema by placing the following in your Schema.pm: __PACKAGE__->default_resultset_attributes({ software_limit => 1 }); WARNING: If you are dealing with large resultsets and your DBI or ODBC/ADO driver does not have proper cursor support (i.e. it loads the whole resultset into memory) then this feature will be extremely slow and use huge amounts of memory at best, and may cause your process to run out of memory and cause instability on your server at worst, beware!.name /] } ); # Equivalent SQL: # SELECT cd.* FROM cd # JOIN artist ON cd.artist = artist.id # WHERE artist.name = 'Bob Marley' # ORDER BY artist.name Note that the join attribute should only be used when you need to search or sort using columns in a related table. Joining related tables when you only need columns from the main table will make performance worse! Now let's say you want to display a list of CDs, each with the name of the artist. The following will work fine: while (my $cd = $rs->next) { print "CD: " . $cd->title . ", Artist: " . $cd->artist->name; } There is a problem however. We have searched both the cd and artist tables in our main query, but we have only returned data from the cd table. To get the artist name for any of the CD objects returned, DBIx::Class will go back to the database: SELECT artist.* FROM artist WHERE artist.id = ? A statement like the one above will run for each and every CD returned by our main query. Five CDs, five extra queries. A hundred CDs, one hundred extra queries! Thankfully, DBIx::Class has a prefetch attribute to solve this problem. This allows you to fetch results from related tables in advance: my $rs = $schema->resultset('CD')->search( { 'artists.name' => 'Bob Marley' }, { join => 'artists', order_by => [qw/ artists.name /], prefetch => 'artists' # return artist data too! } ); # Equivalent SQL (note SELECT from both "cd" and "artist"): # SELECT cd.*, artist.* FROM cd # JOIN artist ON cd.artist = artist.id # WHERE artist.name = 'Bob Marley' # ORDER BY artist.name The code to print the CD list remains the same: while (my $cd = $rs->next) { print "CD: " . $cd->title . ", Artist: " . $cd->artist->name; } DBIx::Class has now prefetched all matching data from the artist table, so no additional SQL statements are executed. You now have a much more efficient query. Also note that prefetch should only be used when you know you will definitely use data from a related table. Pre-fetching related tables when you only need columns from the main table will make performance worse!' AND liner_notes.notes LIKE '%some text%' # ORDER BY artist.name Sometimes you want to join more than one relationship deep. In this example, we want to find all Artist objects who have CDs whose LinerNotes contain a specific string: # Relationships defined elsewhere: # Artist->has_many('cds' => 'CD', 'artist'); # CD->has_one('liner_notes' => 'LinerNotes', 'cd'); my $rs = $schema->resultset('Artist')->search( { 'liner_notes.notes' => { 'like', '%some text%' }, }, { join => { 'cds' => 'liner_notes' } } ); # Equivalent SQL: # SELECT artist.* FROM artist # LEFT JOIN cd ON artist.id = cd.artist # LEFT JOIN liner_notes ON cd.id = liner_notes.cd # WHERE liner_notes.notes LIKE '%some text%' Joins can be nested to an arbitrary level. So if we decide later that we want to reduce the number of Artists returned based on who wrote the liner notes: # Relationship defined elsewhere: # LinerNotes->belongs_to('author' => 'Person'); my $rs = $schema->resultset('Artist')->search( { 'liner_notes.notes' => { 'like', '%some text%' }, 'author.name' => 'A. Writer' }, { join => { 'cds' => { 'liner_notes' => 'author' } } } ); # Equivalent SQL: # SELECT artist.* FROM artist # LEFT JOIN cd ON artist.id = cd.artist # LEFT JOIN liner_notes ON cd.id = liner_notes.cd # LEFT JOIN author ON author.id = liner_notes.author # WHERE liner_notes.notes LIKE '%some text%' # AND author.name = 'A. Writer'; It is possible to get a Schema object from a result object like so: my $schema = $cd->result_source->schema; # use the schema as normal: my $artist_rs = $schema->resultset('Artist'); This can be useful when you don't want to pass around a Schema object to every method. AKA getting last_insert_id Thanks to the core component PK::Auto, this is straightforward: my $foo = $rs->create(\%blah); # do more stuff my $id = $foo->id; # foo->my_primary_key_field will also work. If you are not using autoincrementing primary keys, this will probably not work, but then you already know the value of the last primary key anyway.; Suppose we have two tables: Product and Category. The table specifications are: Product(id, Description, category) Category(id, Description) category is a foreign key into the Category table. If you have a Product object $obj and write something like print $obj->category things will not work as expected. To obtain, for example, the category description, you should add this method to the class defining the Category table: use overload "" => sub { my $self = shift; return $self->Description; }, fallback => 1; Just use find_or_new instead, then check in_storage: my $obj = $rs->find_or_new({ blah => 'blarg' }); unless ($obj->in_storage) { $obj->insert; # do whatever else you wanted if it was a new row }; AKA multi-class object inflation from one table DBIx::Class classes are proxy classes, therefore some different techniques need to be employed for more than basic subclassing. In this example we have a single user table that carries a boolean bit for admin. We would like like to give the admin users objects (DBIx::Class::Row) the same methods as a regular user but also special admin only methods. It doesn't make sense to create two separate proxy-class files for this. We would be copying all the user methods into the Admin class. There is a cleaner way to accomplish this. Overriding the inflate_result method within the User proxy-class gives us the effect we want. This method is called by DBIx::Class::ResultSet when inflating a result from storage. So we grab the object being returned, inspect the values we are looking for, bless it if it's an admin object, and then return it. See the example below: Schema Definition package'; __PACKAGE__->table('users'); __PACKAGE__->add_columns(qw/user_id email password firstname lastname active admin/); __PACKAGE__->set_primary_key('user_id'); sub inflate_result { my $self = shift; my $ret = $self->next::method(@_); if( $ret->admin ) {### If this is an admin, rebless for extra functions $self->ensure_class_loaded( $admin_class ); bless $ret, $admin_class; } return $ret; } sub hello { print "I am a regular user.\n"; return ; }::Schema->connection('dbi:Pg:dbname=test'); $schema->resultset('User')->create( $user_data ); $schema->resultset('User')->create( $admin_data ); ### Now we search for them my $user = $schema->resultset('User')->single( $user_data ); my $admin = $schema->resultset('User')->single( $admin_data ); print ref $user, "\n"; print ref $admin, "\n"; print $user->password , "\n"; # pass1 print $admin->password , "\n";# pass2; inherited from User print $user->hello , "\n";# I am a regular user. print $admin->hello, "\n";# I am an admin. ### The statement below will NOT print print "I can do admin stuff\n" if $user->can('do_admin_stuff'); ### The statement below will print print "I can do admin stuff\n" if $admin->can('do_admin_stuff'); Alternatively you can use DBIx::Class::DynamicSubclass that implements exactly the above functionality. DBIx::Class is not built for speed, it's built for convenience and ease of use, but sometimes you just need to get the data, and skip the fancy objects. To do this simply use DBIx::Class::ResultClass::HashRefInflator. my $rs = $schema->resultset('CD'); $rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); my $hash_ref = $rs->find(1); Wasn't that easy? Beware, changing the Result class using "result_class" in DBIx::Class::ResultSet will replace any existing class completely including any special components loaded using load_components, eg DBIx::Class::InflateColumn::DateTime.). To get the DBIx::Class::Schema object from a ResultSet, do the following: $rs->result_source->schema AKA Aggregating Data If you want to find the sum of a particular column there are several ways, the obvious one is to use search: my $rs = $schema->resultset('Items')->search( {}, { select => [ { sum => 'Cost' } ], as => [ 'total_cost' ], # remember this 'as' is for DBIx::Class::ResultSet not SQL } ); my $tc = $rs->first->get_column('total_cost'); Or, you can use the DBIx::Class::ResultSetColumn, which gets returned when you ask the ResultSet for a column using get_column: my $cost = $schema->resultset('Items')->get_column('Cost'); my $tc = $cost->sum; With this you can also do: my $minvalue = $cost->min; my $maxvalue = $cost->max; Or just iterate through the values of this column only: while ( my $c = $cost->next ) { print $c; } foreach my $c ($cost->all) { print $c; } ResultSetColumn only has a limited number of built-in functions. If you need one that it doesn't have, then you can use the func method instead: my $avg = $cost->func('AVERAGE'); This will cause the following SQL statement to be run: SELECT AVERAGE(Cost) FROM Items me Which will of course only work if your database supports this function. See DBIx::Class::ResultSetColumn for more documentation. Sometimes you have a (set of) result; my $author = $book->create_related('author', { name => 'Fred'}); Only searches for books named 'Titanic' by the author in $author. my $books_rs = $author->search_related('books', { name => 'Titanic' }); Deletes only the book named Titanic by the author in $author. $author->delete_related('books', { name => 'Titanic' }); If you always want a relation to be ordered, you can specify this when you create the relationship. To order $book->pages by descending page_number, create the relation as follows: __PACKAGE__->has_many('pages' => 'Page', 'book', { order_by => { -desc => 'page_number'} } ); If you want to get a filtered result set, you can just add add to $attr as follows: __PACKAGE__->has_many('pages' => 'Page', 'book', { where => { scrap => 0 } } );'; __PACKAGE__->table('address'); __PACKAGE__->add_columns(qw/id street town area_code country/); __PACKAGE__->set_primary_key('id'); __PACKAGE__->has_many('user_address' => 'My::UserAddress', 'address'); __PACKAGE__->many_to_many('users' => 'user_address', 'user'); $rs = $user->addresses(); # get all addresses for a user $rs = $address->users(); # get all users for an address my $address = $user->add_to_addresses( # returns a My::Address instance, # NOT a My::UserAddress instance! { country => 'United Kingdom', area_code => 'XYZ', town => 'London', street => 'Sesame', } );. As of version 0.04001, there is improved transaction support in DBIx::Class::Storage and DBIx::Class::Schema. Here is an example of the recommended way to use it: my $genus = $schema->resultset('Genus')->find(12); my $coderef2 = sub { $genus->extinct(1); $genus->update; }; my $coderef1 = sub { $genus->add_to_species({ name => 'troglodyte' }); $genus->wings(2); $genus->update; $schema->txn_do($coderef2); # Can have a nested transaction. Only the outer will actualy commit return $genus->species; }; use Try::Tiny; my $rs; try { $rs = $schema->txn_do($coderef1); } catch { # try block succeeds. use Try::Tiny; my $exception; try { $schema->txn_do(sub { # SQL: BEGIN WORK; my $job = $schema->resultset('Job')->create({ name=> 'big job' }); # SQL: INSERT INTO job ( name) VALUES ( 'big job' ); for (1..10) { # Start a nested transaction, which in fact sets a savepoint. try { ); } }); } catch { #; } }); } catch { $exception = $_; }; if ($exception) { # There was an error while handling the $job. Rollback all changes # since the transaction started, including the already committed # ('released') savepoints. There will be neither a new $job nor any # $thing entry in the database. # SQL: ROLLBACK; print "ERROR: $exception try-block around txn_do fails, a rollback is issued. If the try succeeds, the transaction is committed (or the savepoint released). While you can get more fine-grained control using svp_begin, svp_release and svp_rollback, it is strongly recommended to use txn_do with coderefs.. DBIx::Class::Schema::Loader will connect to a database and create a DBIx::Class::Schema and associated sources by examining the database. The recommend way of achieving this is to use the dbicdump utility or the Catalyst helper, as described in Manual::Intro. Alternatively, use the make_schema_at method: perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib \ -e 'make_schema_at("My::Schema", \ { db_schema => 'myschema', components => ["InflateColumn::DateTime"] }, \ [ "dbi:Pg:dbname=foo", "username", "password" ])' This will create a tree of files rooted at ./lib/My/Schema/ containing source definitions for all the tables found in the myschema schema in the foo database.. The following example shows simplistically how you might use DBIx::Class to deploy versioned schemas to your customers. The basic process is as follows:, and defaults to . if not supplied.]. To ensure WHERE conditions containing DateTime arguments are properly formatted to be understood by your RDBMS, you must use the DateTime formatter returned by "datetime_parser" in DBIx::Class::Storage::DBI to format any DateTime objects you pass to search conditions. Any Storage object attached to your Schema provides a correct DateTime formatter, so all you have to do is: my $dtf = $schema->storage->datetime_parser; my $rs = $schema->resultset('users')->search( { signup_date => { -between => [ $dtf->format_datetime($dt_start), $dtf->format_datetime($dt_end), ], } }, ); Without doing this the query will contain the simple stringification of the DateTime object, which almost never matches the RDBMS expectations. This kludge is necessary only for conditions passed to "search" in DBIx::Class::ResultSet, whereas create, find, "update" in DBIx::Class::Row (but not "update" in DBIx::Class::ResultSet) are all DBIx::Class::InflateColumn-aware and will do the right thing when supplied an inflated DateTime object.. Information about Oracle support for unicode can be found in "Unicode" in DBD::Oracle.} ); You want to start using the schema-based approach to DBIx::Class (see "Setting it up manually" in DBIx::Class::Manual::Intro), but have an established class-based setup with lots of existing classes that you don't want to move by hand. Try this nifty script instead: use MyDB; use SQL::Translator; my $schema = MyDB->schema_instance; my $translator = SQL::Translator->new( debug => $debug || 0, trace => $trace || 0, no_comments => $no_comments || 0, show_warnings => $show_warnings || 0, add_drop_table => $add_drop_table || 0, validate => $validate || 0, parser_args => { 'DBIx::Schema' => $schema, }, producer_args => { 'prefix' => 'My::Schema', }, ); $translator->parser('SQL::Translator::Parser::DBIx::Class'); $translator->producer('SQL::Translator::Producer::DBIx::Class::File'); my $output = $translator->translate(@args) or die "Error: " . $translator->error; print $output; You could use Module::Find to search for all subclasses in the MyDB::* namespace, which is currently left as an exercise for the reader.. It's as simple as overriding the new method. Note the use of next::method. sub new { my ( $class, $attrs ) = @_; $attrs->{foo} = 'bar' unless defined $attrs->{foo}; my $new = $class->next::method($attrs); return $new; } For more information about next::method, look in the Class::C3 documentation. See also DBIx::Class::Manual::Component for more ways to write your own base classes to do this. People looking for ways to do "triggers" with DBIx::Class are probably just looking for this. For example, say that you have three columns, id, number, and squared. You would like to make changes to number and have squared be automagically set to the value of number squared. You can accomplish this by wrapping the number accessor with the around method modifier, available through either Class::Method::Modifiers, Moose or Moose-like modules): around number => sub { my ($orig, $self) = (shift, shift); if (@_) { my $value = $_[0]; $self->squared( $value * $value ); } $self->$orig(@_); }; Note that the hard work is done by the call to $self->$orig, which redispatches your call to store_column in the superclass(es). Generally, if this is a calculation your database can easily do, try and avoid storing the calculated value, it is safer to calculate when needed, than rely on the data being in sync. } Problem: Say you have a table "Camera" and want to associate a description with each camera. For most cameras, you'll be able to generate the description from the other columns. However, in a few special cases you may want to associate a custom description with a camera. Solution: In your database schema, define a description field in the "Camera" table that can contain text and null values. In DBIC, we'll overload the column accessor to provide a sane default if no custom description is defined. The accessor will either return or generate the description, depending on whether the field is null or not. First, in your "Camera" schema class, define the description field as follows: __PACKAGE__->add_columns(description => { accessor => '_description' }); Next, we'll define the accessor-wrapper subroutine: sub description { my $self = shift; # If there is an update to the column, we'll let the original accessor # deal with it. return $self->_description(@_) if @_; # Fetch the column value. my $description = $self->_description; # If there's something in the description field, then just return that. return $description if defined $description && length $descripton; # Otherwise, generate a description. return $self->generate_description; } Data::Dumper can be a very useful tool for debugging, but sometimes it can be hard to find the pertinent data in all the data it can generate. Specifically, if one naively tries to use it like so, use Data::Dumper; my $cd = $schema->resultset('CD')->find(1); print Dumper($cd); several pages worth of data from the CD object's schema and result source will be dumped to the screen. Since usually one is only interested in a few column values of the object, this is not very helpful. Luckily, it is possible to modify the data before Data::Dumper outputs it. Simply define a hook that Data::Dumper will call on the object before dumping it. For example, package My::DB::CD; sub _dumper_hook { $_[0] = bless { %{ $_[0] }, result_source => undef, }, ref($_[0]); } [...] use Data::Dumper; local $Data::Dumper::Freezer = '_dumper_hook'; my $cd = $schema->resultset('CD')->find(1); print Dumper($cd); # dumps $cd without its ResultSource If the structure of your schema is such that there is a common base class for all your table classes, simply put a method similar to _dumper_hook in the base class and set $Data::Dumper::Freezer to its name and Data::Dumper will automagically clean up your data before printing it. See "EXAMPLES" in Data::Dumper for more information. When you enable DBIx::Class::Storage's debugging it prints the SQL executed as well as notifications of query completion and transaction begin/commit. If you'd like to profile the SQL you can subclass the DBIx::Class::Storage::Statistics class and write your own profiling mechanism: package My::Profiler; use strict; use base 'DBIx::Class::Storage::Statistics'; use Time::HiRes qw(time); my $start; sub query_start { my $self = shift(); my $sql = shift(); my @params = @_; $self->print("Executing $sql: ".join(', ', @params)."\n"); $start = time(); } sub query_end { my $self = shift(); my $sql = shift(); my @params = @_; my $elapsed = sprintf("%0.4f", time() - $start); $self->print("Execution took $elapsed seconds.\n"); $start = undef; } 1; You can then install that class as the debugging object: __PACKAGE__->storage->debugobj(new My::Profiler()); __PACKAGE__->storage->debug(1); A more complicated example might involve storing each execution of SQL in an array: sub query_end { my $self = shift(); my $sql = shift(); my @params = @_; my $elapsed = time() - $start; push(@{ $calls{$sql} }, { params => \@params, elapsed => $elapsed }); } You could then create average, high and low execution times for an SQL statement and dig down to see if certain parameters cause aberrant behavior. You might want to check out DBIx::Class::QueryLog as well. When inserting many rows, for best results, populate a large number of rows at a time, but not so large that the table is locked for an unacceptably long time. If using create instead, use a transaction and commit every X rows; where X gives you the best performance without locking the table for too long. }, });
http://search.cpan.org/~ribasushi/DBIx-Class-0.08250/lib/DBIx/Class/Manual/Cookbook.pod
CC-MAIN-2014-23
refinedweb
3,937
51.18
![if gte IE 9]><![endif]> Hi, I'm trying to integrate OpenOffice in our software. It can be done using com-handles, albeit in a limited way. So I tried using real objects instead. I keep running into problems when using CAST however. Probably because of the UNO-structure-thingie, but I'm not sure. I always get an "Invalid Cast"-error. However, passing the object to a procedure with an input parameter does work. I've included an example to clarify my problem: using System.*. using unoidl.com.sun.star.lang.*. using unoidl.com.sun.star.uno.*. using unoidl.com.sun.star.bridge.*. def var oStrap as XComponentContext no-undo. def var oServ as XMultiServiceFactory no-undo. def var oStrTmp as XMultiComponentFactory no-undo. oStrap = uno.util.Bootstrap:bootstrap(). oStrTmp = oStrap:getServiceManager(). run pTest (input oStrTmp). /* OK */ oServ = cast(oStrTmp , XMultiServiceFactory). /* NOK */ procedure ptest: def input param p as XMultiServiceFactory. oServ = p. end procedure. The run pTest will work (I've made a complete working sample generating a spreadsheet). The CAST will fail. I was hoping a class using methods would work in the same way as a procedure, but it does a check of it's types and generates the same error as a cast. Any ideas why the CAST fails, but the procedure works? (If you want to test, you'd need to include the cli*-dll's into assemblies.xml) Progress 101a & 102b (soon to be 11.??) Thx 101a ??? I guess 10.2a as 10.1a did not have access to .NET objects. I remeber that there were issues on 10.1a with access to COM-Interop objects. What message does CAST give you? Yes 10.2A, not 10.1A. My mistake... But 10.2B gives the same error: Invalid cast from System.Object to unoidl.com.sun.star.lang.XMultiServiceFactory, cli_uretypes (12869) ... Btw, The same cast in C# does work. Did you try the latest 10.2B service pack? 07 when I am not mistaking? Yep. 10.2B07 OE 11.2.1 / Win7 x64 I was curious - and wanted to have a quick spin with OpenOffice - but was stopped in my tracks after a few minutes (excluding download time). The cli_cppuhelper.dll is 'currently' (since 2010 it seems) broken and will only work on a 32-bit machine - see also 'new' bug for the other branch Just a heads up. The dll is indeed a 32-bit version. I believe it'll work correctly if you compile a 32-bit application. At least for me that worked in Visual Studio. My Progress did not pose any problems. But I see you're using version 11. Perhaps there are more options concerning 32/64 bit in this version. btw, I'm using the exact same OS. Also tested on a 32 bit XP.
https://community.progress.com/community_groups/openedge_general/f/26/t/7436
CC-MAIN-2017-47
refinedweb
467
70.9
On Mon, Sep 16, 2019 at 7:49 PM Riccardo Iaconelli <riccardo.iacone...@gmail.com> wrote: > > Hi Ben, Hi Riccardo, > > On lunedì 16 settembre 2019 08:03:31 CEST Ben Cooksley wrote: > > The content of notes.kde.org will be exported - likely in ODT format - > > prior to us shutting it down. > > The resulting files will be made available on share.kde.org. > > > > If there are things which need to be resolved prior to the shutdown of > > notes.kde.org we can look into those. > > > > While it is unfortunate that the links will be broken, we should be > > able to make them relatively close (ie. send the user to a public view > > of the folder on share.kde.org which contains all of the content > > exported from notes.kde.org) so the user isn't too far from the > > original link. > > will we expose any content to the public indexing? I know of a few documents > which relied on the protection of being unlisted from Google to draft emails > or other group notes which are not entirely for the public to search through. Group notes that were created within a group namespace previously registered with Sysadmin (which will have a corresponding group on Identity) will only be made accessible to that group (via a special folder on share.kde.org) following the export/shutdown of Notes. These pads can be denoted by the -private- in the name of the pad. For all other files, they'll be made publicly accessible to a certain degree, so i'd recommend blanking the content of any notes that shouldn't be made public prior to the shutdown. > > Riccardo > > > Cheers, Ben
https://www.mail-archive.com/kde-community@kde.org/msg05513.html
CC-MAIN-2019-43
refinedweb
276
64.81
This article presents a group of shapes that you can use in your applications. Some of these, the Epitrochoids and Epicycloids, may be familiar if you had a Spirograph as a child. All of the shapes included here are defined by simple mathematical relations. The Farris Wheel is the only one that is even mildly complex. However, converting functions defined mathematically into vector visuals has until recently been rather laborious. The change was my last article (GraphDisplay: a Bezier based control for graphing functions and curves), in which I developed a procedure for the generation of PathGeometry elements that represented mathematically defined curves and functions. One use for such code is to make practical business or scientific applications. Another, the one chosen here, is to make it possible to include some pleasing mathematical vector shapes in applications with effectively no effort. In particular, absolutely no understanding of the math behind all of this is required to use these shapes in your applications. It is only for creating your own additional shapes that some math will be needed, but even then, understanding the algorithm behind all of this is completely optional. PathGeometry There is quite a bit of background one might find interesting, on both the internal workings of the shapes and the shapes themselves. If you want to understand how the application works, please see my article GraphDisplay: a Bezier based control for graphing functions and curves. For the shapes, the following references may he helpful: There is also an article in Mathematics Magazine by F. A. Farris, "Wheels on Wheels on Wheels - Surprising Symmetry", Mathematics Magazine 69(3), 1996 pp. 185-189. Unfortunately, the article is not available online (for free at least), but can be easily found in almost any college library. The shapes can be used just as if they were any other shapes. <f:Rose creates a Rose very similar to the one pictured above. You need to add the XML namespace for f. Rose f xmlns:f="clr-namespace:FunctionalShapes;assembly=FunctionalShapes" There is really not much more to say. The issue is that on may not know how to control the shape's appearance via the parameters. To that end, the demo application is a demonstration of the variety of possibilities inherent in the shapes. The main tool for experimenting with the various shapes is the Shape Explorer. alt="Image 2" data-src="/KB/WPF/SpirographShapes/ShapeExplorer.gif" class="lazyload" data-sizes="auto" data-> It shows the shape selected along with the formula used to calculate it. The various parameters can be adjusted, either through the sliders or the textboxes. You can also choose the fill stroke and background color. Finally, you can adjust the number of Bezier segments used to construct the shape. SegmentAdjustment is the exponent of a power of 2 that multiplies the expected number of segments for the shape. So, if SegmentAdjustment is 0, then we have 2 to the 0 power, which is 1 or no change. For 3, we would have 8 times as many segments, and for -2, we would have 1/4 the number. Increasing the number makes the shape track the curve better at the cost of more calculations. (Note: Dramatically lowering the SegmentAdjustment can lead to unpredictable and at times beautiful curves.) This may seem strange, but the intention was to make the adjustment unbiased with respect to being larger or smaller. If I used straight multiplication, the slider would run from 0 to 16 and almost all of the space would be dedicated to increasing the number of segments. This illustrates the important point that there are often many ways you could choose to organize your parameters. SegmentAdjustment This is all good, but it does not give the full flavor of the shapes. To assist in this, each of the seven shapes has its own window that displays grids of shapes. These will be detailed along with their respective shapes. The Epicycloid is an old and famous curve. As far as we know, it was first discovered by Hipparchus of Rhodes (190-120 BC). It was put to very practical use in Astronomy through the long used Ptolemaic system. Thought of geometrically, a hypocycloid represents a circle rolling along the edge of another circle without slipping, which is equivalent to the following equations, with R1 being the radius of the base circle and R2 being the radius of the rolling circle. This formula can be improved upon for geometric purposes. Instead of R1 and R2, we can use the ratio of R1/R2 and R2 to represent the Epicycloid. R1/R2 or k represents the shape, and R2 represents the size of the shape. The Epicycloid curve will only repeat if k is rational. To ensure repeating shapes, I chose N (for Numerator) and D (for Denominator) in place of K and R as a scaling factor. I also added a phase shift P which has the effect of rotating the shape. This gives the following formula for the Hypocycloid that is used in the Hypocycloid class. Hypocycloid In code, this corresponds to: int gcd = Mathematics.NumberTheory.GCD(N, D);//GCD for Greatest common Denominator); Lots of details of how this code works can be found at GraphDisplay: a Bezier based control for graphing functions and curves, but the thing I would note here is that: t => R * m * Math.Cos(t + P) + R * Math.Cos(m * t + P corresponds to fx, while: fx t => R * m * Math.Sin(t + P) - R * Math.Sin(m * t + P) corresponds to fy. At this point, you might note that instead of a pair of functions fx and fy, you could think of this shape as being defined by a single complex function z(t), where fx is the real part of z and fy is the imaginary part of z(t). fy Since we are defining the shape by a complete cycle of t, there is no reason why you cannot replace t by D*t, which gives the following interesting formulation. Thus we can represent an Epicycloid by a sum of two complex exponentials with integral modifiers. The demo application also allows you to view grids of Epicycloids. alt="Image 8" data-src="/KB/WPF/SpirographShapes/Epicycloids.gif" class="lazyload" data-sizes="auto" data-> The Epitrochoid is an abstraction of the Epicycloid, which only took 1600 years to come about. Albrecht Dürer, of great artistic fame, wrote about these "spider lines" in 1525. Geometrically, an Epitrochoid defines the curve at a different radius than the rotating circle. It is the curve made in a spirograph when one of the circles is rotated on the outside of another circle. (Note that you can get pretty close to having an Epicycloid by using the hole at the very edge, but technically, it would need to be at the exact edge to get an Epicycloid rather than an Epitrochoid.) As far as the formula is concerned, the only difference is that the second R2 is replaced by an additional parameter D to represent the additional radius. Just as with the Epicycloid, this formula can be improved upon for geometric purposes. Instead of R1 and R2, we can use the ratio of R1/R2 and R2 to represent the Epitrochoid. R1/R2 or k represents the shape, and R2 represents the size of the shape. This shape uses the following version of the equation for an Epitrochoid. The parameter M is used in place of D so that when D=0 we have an Epitrochoid. int gcd = Mathematics.NumberTheory.GCD(N, D); double p = (double)N / gcd; double q = (double)D / gcd; Double k = (double)p / q;); We can see). Not surprisingly, you can make the same substitution of t with D*t to get integer coefficients for the t variables. The Epitrochoid display grid allows you to see a group of Epitrochoids together. Moving the M slider has a significant effect on their appearance. alt="Image 14" data-src="/KB/WPF/SpirographShapes/Epitrochoids.gif" class="lazyload" data-sizes="auto" data-> Moving forward in time, Hypocycloids were first invented/discovered by Ole Romer (of speed of light fame) while studying gears in 1674. The hypocycloid can be thought of as the path formed by one circle rolling around within another circle. The following formula can be easily shown to represent a Hypocycloid: It can then be written in terms of the ratio of R1 and R2. The following version is the one used for the shape. Note that it has an extra parameter P for an overall phase shift (rotation) of the shape. These equations are written in code as follows: t => R * m * Math.Cos(t + P) + R * Math.Cos(m * t + P) corresponds to fy. Again, this can be represented by a single complex function z(t), where fx is the real part of z and fy is the imaginary part of z(t). Also, it is worth noting that cos(t) is an even function (cos(-t) = cos(t)) while sin(t) is odd (sin(-t) = -sin(t)). If you substitute t with D*t, you get the integer coefficients for the t variables. The Hypocycloid display grid allows you to see a group of Hypocycloids together. alt="Image 20" data-src="/KB/WPF/SpirographShapes/Hypocycloids.gif" class="lazyload" data-sizes="auto" data-> Hyptrochoids were first envisioned by Charles de Bovelles (Carolus Bovillus Latinized) in 1501. They are noted for being the curves created in a spirograph when a small wheel is rotated around inside a bigger ring. They can be represented mathematically by the following formula: The Hypotrochoid equations can be written in terms of the ratio of R1 and R2, but with an additional parameter D. If D is equal to R2, then we have a Hypocycloid. The shape uses the following version of the equation for a Hypotrochoid. The parameter M is used in place of D so that when D=0, we have a Hypocycloid. int gcd = Mathematics.NumberTheory.GCD(N, D); double p = (double)N / gcd; double q = (double)D / gcd; Double k = (double)p / q; K =). z(t) If you substitute t with D*t, you get integer coefficients for the t variables. The Hypotrochoid display grid allows you to see a group of Hypotrochoids together. Moving the M slider has a significant effect on their appearance. alt="Image 26" data-src="/KB/WPF/SpirographShapes/Hypotrochoids.gif" class="lazyload" data-sizes="auto" data-> The Farris wheel brings us up to the present time. The curve was brought to aesthetic attention by Dr. Fark Farris in 1996, hence the name. We have seen that all of the curves so far can be written in the form: where a and b are integers and A and B are complex. You could imagine extending z(t) to include a third term, and thus we have: This can be expressed directly in terms of x(t) and t(t) as: P refers to an overall phase shift. P, P1, P2, P3 have been scaled so that they go from -1 to 1 instead of -PI to PI. S is an overall scale factor, so W1, W2, W3 should be thought of as relative weights. In code, this corresponds to: double maxRadius = Math.Abs(W1) + Math.Abs(W2) + Math.Abs(W3); Double scaleFactor = R / maxRadius; double pp1PI = (P + P1) * Math.PI; double pp2PI = (P + P2) * Math.PI; double pp3PI = (P + P3) * Math.PI; Function fx = new Function(t => scaleFactor * (W1 * Math.Cos(F1 * t + pp1PI) + W2 * Math.Cos(F2 * t + pp2PI) + W3 * Math.Cos(F3 * t + pp3PI)), t => scaleFactor * (-F1 * W1 * Math.Sin(F1 * t + pp1PI) - F2 * W2 * Math.Sin(F2 * t + pp2PI) - F3 * W3 * Math.Sin(F3 * t + pp3PI))); Function fy = new Function(t => scaleFactor * (W1 * Math.Sin(F1 * t + pp1PI) + W2 * Math.Sin(F2 * t + pp2PI) + W3 * Math.Sin(F3 * t + pp3PI)), t => scaleFactor * (F1 * W1 * Math.Cos(F1 * t + pp1PI) + F2 * W2 * Math.Cos(F2 * t + pp2PI) + F3 * W3 * Math.Cos(F3 * t + pp3PI))); CyclicCurve c = new CyclicCurve(fx, fy, 0, 2 * Math.PI); Some of the factors have been combined to reduce the number of arithmetic operations. This is a much richer shape than those that have preceded it, one capable of a great variety of forms. Note that for this one, the row and column can be changed as there are three frequencies, F1, F2, F3. alt="Image 30" data-src="/KB/WPF/SpirographShapes/FarrisWheels.gif" class="lazyload" data-sizes="auto" data-> Lissajous curves were discovered/invented by Nathaniel Bowditch in 1815. They were later independently rediscovered by Antoine Lissajous in 1857 after whom they are named. (They are sometimes referred to as Bowditch curves.) The curves are most often seen on oscilloscopes. The shape uses the following version of the formula where N and D are integers: int gcd = Mathematics.NumberTheory.GCD(Alpha,Beta); double p = (double)Alpha / gcd; double q = (double)Beta / gcd; Function fx = new Function(t => A * Math.Sin(p * t + Delta ), t => A * p * Math.Cos(p * t + Delta )); Function fy = new Function(t => B * Math.Sin(q * t), t => B * q * Math.Cos(q * t )); CyclicCurve c = new CyclicCurve(fx, fy, 0, 2 * Math.PI ); t => A * Math.Sin(p * t + Delta ) t => B * Math.Sin(q * t) corresponds to fy. The Lissajous demonstration shows the variety this shape is capable of. Note that changing Delta has an interesting effect on the shape. alt="Image 33" data-src="/KB/WPF/SpirographShapes/LissajousCurves.gif" class="lazyload" data-sizes="auto" data-> Rose curves were discovered/invented by Luigi Guido Grandi around 1725. He thought they looked like flowers, hence the name. They can be represented in polar form as: If alpha is rational, then the curve will close. For the shape, the following form is used with N and D as integers: The shape is represented in code as: int gcd = Mathematics.NumberTheory.GCD(N, D); double p = (double)N / gcd; double q = (double)D / gcd; double omega = p / q; Function fr = new Function(t => A * Math.Sin(omega * t), t => omega * A * Math.Cos(omega * t)); CyclicPolarCurve rc = new CyclicPolarCurve(fr, 0, 2 * q * Math.PI); t => A * Math.Sin(omega * t) corresponds to r, which corresponds to fy. The Rose demonstration shows the variety this shape is capable of. alt="Image 36" data-src="/KB/WPF/SpirographShapes/Roses.gif" class="lazyload" data-sizes="auto" data-> The included shapes represent a tiny fraction of the possible shapes that can be made from mathematically defined curves. It is extremely easy to create others. Throughout this section, I will use the Hypocycloid as an example as it is the simplest that shows all the features. In order to create a shape, there are three things that must be done. First, you must inherit from FunctionalShapes.FunctionalClosedShapeBase. Second, you must override the Curve property. This is where you define the cure mathematically. In this case, the curve is being composed of two functions, fx and fy. The Function class takes two delegates in its constructor: one representing the values of the function, and one representing the derivative. Details on the definition of functions and curves can be found at GraphDisplay: a Bezier based control for graphing functions and curves. FunctionalShapes.FunctionalClosedShapeBase Curve Function protected override Mathematics.BaseClasses.CyclicCurveBase Curve { get { //GCD for Greatest common Denominator int gcd = Mathematics.NumberTheory.GCD(N, D);); K = (double)p / q; return c; } } The third requirement is that the segments property be defined. This defines the base number of Bezier segments to use before adjustment by SegmentAdjust. SegmentAdjust protected override int Segments() { return 200 + N*N + D*D; } Now it seems very likely that if you were going to go through the effort of defining a shape, it would not just be for a single shape but a parameterized family of shapes. This will work much better if dependency properties are used. That will enable you to use animation and the WPF dynamic render updating. Here is the property for the Hypocycloids phase shift. public static DependencyProperty PProperty = DependencyProperty.Register("P", typeof(double), ClassType, new FrameworkPropertyMetadata(0.0, options, new PropertyChangedCallback(OnPropChanged))); [MathParameter("P", -Math.PI, Math.PI, false)] public double P { get { return (double)GetValue(PProperty); } set { SetValue(PProperty, value); } } Note that there is a PropertyChangedCallback. It nulls out the cached copy of the geometry. All dependency properties that affect the rendering need to do this. Setting FrameworkPropertyMetadataOptions is not sufficient. PropertyChangedCallback FrameworkPropertyMetadataOptions private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Hypocycloid ps = (Hypocycloid)d; ps.mGeom = null; } Speaking of FrameworkPropertyMetadataOptions, I would advise the following options to be used. Also, once a variable like this is defined, it can be used in multiple dependency properties. static FrameworkPropertyMetadataOptions options = FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange; I would very strongly advise the use of the ClassType property when working with families of classes with dependency properties. It is simple, but it allows you to copy and paste between different classes. ClassType static Type ClassType { get { return typeof(Hypocycloid); } } One of the things that you might want to do to test out your new shape is use it in the Shape Explorer. While developing this article, one of the things I decided was that I was absolutely unwilling to make individual property editors for each shape. To solve this problem, a custom attribute was added to the class, the MathParameterAttribute. MathParameterAttribute public sealed class MathParameterAttribute:Attribute { /// <summary> /// The Friendly Name for the Parameter /// </summary> public string DisplayName { get; private set; } /// <summary> /// The Default Minimum value for the parameter(used by sliders) /// </summary> public Double MinValue { get; private set; } /// <summary> /// The default Maximum value for the parameter(used by sliders) /// </summary> public Double MaxValue { get; private set; } /// <summary> /// Is the parameter an integer(used by sliders) /// </summary> public bool IsInteger { get; private set; } /// <summary> /// Is the parameter Read only /// </summary> public bool IsReadOnly { get; set; } public MathParameterAttribute(String displayName, Double minValue, Double maxValue, bool isInteger) { DisplayName = displayName; MinValue = minValue; MaxValue = maxValue; IsInteger = isInteger; IsReadOnly = false; } public MathParameterAttribute(String displayName) { DisplayName = displayName; IsReadOnly = true; } } It deals with the two kinds of parameters that we have. In particular, the attribute supports sliders, giving minimum and maximum values to them as well as info on if they need to be restricted to integer values. Remember that you are free to put larger or smaller values into the textbox; the attributes only affect the sliders. A regular parameter would have an attribute like this: [MathParameter("P", -Math.PI, Math.PI, false)] This parameter has a display name of P. (The display name is there to support Greek letters and spaces in names.) The parameter runs form -PI to PI, and is not required to be an integer. The second type of parameter is the read only parameter. It only needs the display name. I am still working on my attribute UI framework, so I will give it the explanation it deserves in the future. [MathParameter("K" )] You might also want to display grids of shapes. To use GridDemonstration, the Clone method must be defined and that is pretty much it. GridDemonstration Clone public override FunctionalClosedShapeBase Clone() { Hypocycloid clonedShape = new Hypocycloid() { N = this.N, D = this.D, R = this.R, P =this.P, Stretch = this.Stretch, Fill = this.Fill, Stroke = this.Stroke, StrokeThickness = this.StrokeThickness, SegmentAdjustment = this.SegmentAdjustment }; return clonedShape; } The shapes included also have drawing brushes for their formulae, but I am not sure I would advise adding them in a non-demo situation, as getting them to look nice is a bit of work. I hope that these shapes serve you all well. It was a bit of work, but also quite fun. These shapes, especially the Farris Wheel, are a delight to play around with. Even after all this, there is so much exciting stuff left to do. There are some further steps I am considering, and I would appreciate.
https://codeproject.freetls.fastly.net/Articles/76878/Spirograph-Shapes-WPF-Bezier-Shapes-from-Math-Form?msg=3951226#xx3951226xx
CC-MAIN-2021-49
refinedweb
3,314
57.27
? Using read() method we can read a file in python. file.read() file = open(“testfile.text”, “r”) print file.read() Is there a better way to do that: def Read_CSV_File(filename): file = open(filename, "r") reader = csv.DictReader(file) line = 1 for row in reader: if line < 6: reader.next() line++ # process the CSV How to want to read the combo box in excel by using "xlrd" but in the output it is showing empty message, its not reading the combo box can u guys help me how to read the combo box in excel by "xlrd" code written like this workbook = xlrd.open_workbook('path of the file') worksheet = workbook.sheet_by_name('sheetname') TargetSystem = worksheet.cell_value(4,. Forgot Your Password? 2018 © Queryhome
https://www.queryhome.com/tech/170018/how-to-read-file-in-python
CC-MAIN-2019-09
refinedweb
121
67.96