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 |
|---|---|---|---|---|---|
#include <gsmunonieoperations.h>
Status Reporting.
This should be the last thing that should be configured in CSmsMessage. If anything is changed after this then the number of PDUs might change which will affect status reporting.
Gets the current scheme being used.
Gets the selective status for a PDU if the scheme is set to the TPSRR Scheme.
If the current scheme is set to TPSRR Scheme then this method sets the scheme to the Default scheme.
Sets the default value of the status report to requested or not requested as per aEnable.
Sets the TPSRR bit for the last PDU depending on the value of aEnable. First the scheme is obtained by calling the GetStatusReportScheme. Then the array iTPSRRStatusReport is traversed to find the last segement. Once that is done the TPSRR bit for it is updated. If the last segment is not present in the array then it is appended to it with its TPSRR status.
This method is called to set the scheme to TPSRR Scheme. First iStatusReportScheme, which is obtained by calling GetStatusReportScheme, is deleted and the set to NULL. Then a new scheme is created and a default value is set. The last segment is set to have TPSRR bit as Requested. This should be the last method to be called in a message sending process as all the operations in this interface depend on the number of PDUs being set.
Sets the TPSRR bit for any PDU depending on the value of aEnable. First the scheme is obtained by calling the GetStatusReportScheme. Then the array iTPSRRStatusReport is traversed to find the segment which has the reference number = aSegmentSequenceNum. Once that is done the TPSRR bit for it is updated.
If the refernce number is not found then it is added to the array.
Reimplemented from CSmsNonIEOperation::ValidateOperationL()const
Identifies whether the message type or version supports this operation
Prevent clients from using the assignment operator by including it in the class definition but making it protected and not exporting it. | http://devlib.symbian.slions.net/belle/GUID-C6E5F800-0637-419E-8FE5-1EBB40E725AA/GUID-6D83694A-93FF-3F91-ADD1-845437632EEC.html | CC-MAIN-2021-25 | refinedweb | 335 | 65.32 |
Particle_Adafruit_IS31FL3731 (community library)
Summary
Particle library for the Adafruit IS31FL3731 Charlieplex LED driver and CharliePlex FeatherWing. Particle library for the Adafruit IS31FL3731 Charlieplex LED driver and CharliePlex FeatherWing.
Library Read Me
This content is provided by the library maintainer and has not been validated or approved.
Particle_Adafruit_IS31FL3731
A Particle library for the Adafruit IS31FL3731 Charlieplex LED driver and CharliePlex FeatherWing. Forked from adafruit/Adafruit_IS31FL3731
Installation
via the Particle CLI:
particle library add Particle_Adafruit_IS31FL3731
via Particle Workbench:
- run the
Particle: Install Librarycommand
- enter
Particle_Adafruit_IS31FL3731
Usage
Start by creating a new matrix object with something like:
#include "Particle_Adafruit_IS31FL3731.h" // If you're using the full breakout... // Particle_Adafruit_IS31FL3731 ledmatrix = Particle_Adafruit_IS31FL3731(); // If you're using the FeatherWing version Particle_Adafruit_IS31FL3731_Wing ledmatrix = Particle_Adafruit_IS31FL3731_Wing();
Then in your setup, call
.begin(<address>) to initialize the driver.
.begin() will return false if the matrix was not found, and
true if initialization succeeded.
void setup(){
14 inclusive, and
y ranges between
0 and
7 inclusive. Brightness is the PWM of the LED,
0 is off, and
255 is all the way on.
This loop will light up every LED in increasing brightness:
int i = 0; for (uint8_t x = 0; x < 15; ++x) { for (uint8_t y = 0; y < 7; ++y) { ledmatrix.drawPixel(x, y, ++i]); } }
See the examples folder for more details.
Browse Library Files | https://docs.particle.io/cards/libraries/p/Particle_Adafruit_IS31FL3731/ | CC-MAIN-2021-21 | refinedweb | 214 | 56.45 |
This is part 4 and the final post of this JSON series. We are going to play with Smartsheet data because its adds to our examples of varying JSON structure. Note that Power BI already has a connector for Smartsheet. There is also a Python SDK for Smartsheet, but we are going to use the Python requests library so that we can start from scratch and learn how to navigate the JSON structure.
We will follow the same approach as the previous post i.e. focus on understanding the structure, draw from our existing patterns and add one or two new techniques to our arsenal.
Below is the screenshot of the actual Smartsheet we will be working with.
Accessing the Smartsheet API
API access is available during the free trial period. If you want to play, have a look at how to generate the token so that you can authenticate your API access. If you have been following my posts, you would know by now that I store my secure information (such as API tokens) in the user environment variables on by development computer.
To access the API we need to create the endpoint from the Smartsheet API URL and the sheet ID for the sheet you want to access. We also need the token which we pass to the request header. The code to do this is as follows:
import json auth = os.getenv('SMARTSHEET_TOKEN') smartsheet = '' sheetid = '3220009594972036' uri = smartsheet + sheetid header = {'Authorization': "Bearer " + auth, 'Content-Type': 'application/json'} req = requests.get(uri, headers=header) data = json.loads(req.text)
In the above script, the last line converts the request text into a Python dictionary structure.
Understanding the data structures
This is the critical step. Understand the problem … and in this case it means read the Smartsheet documentation and compare it to the physical structure. This time round we are going to use the pretty print (pprint) library for the latter.
import pprint pprint.pprint(data)
The documentation tells us that there is a sheet which is the main object. The sheet contains the columns (metadata) object, a rows object and cells object. It also tells us that a collection of cells form a row. When we explore the physical structure we see that this is indeed the case.
So the column metadata and rows are referenced directly from the sheet object, and the cells are referenced from the row object. We could thus access the columns and rows dictionaries directly.
pprint.pprint(data['columns']) pprint.pprint(data['rows'])
Building the dataframe
The process we are going to follow is to create an empty dataframe from the column metadata (using the ‘title’ key: value pair). We are then going to iterate over the rows and cells and append the values to the new dataframe.
We are firstly going to create a list of columns. This has a dual purpose. We will use it to create the empty dataframe, then we will re-use it to create row dictionaries that we will append to the dataframe.
cols = [] for col in data['columns']: cols.append(col['title'])
Creating the empty dataframe from this is straightforward.
import pandas df = pandas.DataFrame(columns=cols)
To append the rows, we iterate over the rows with a loop and we use a nested loop to iterate over the cells. The cells in each row are added to a list, but first we trap empty values in the VAT field.
for row in data['rows']: values = [] #re-initialise the values list for each row for cell in row['cells']: if cell.get('value'): #handle the empty values values.append( cell['value']) else: values.append('') print(values)
Now we need a new trick to added these lists to the dataframe. We are going to use a function called zip. Zip must be used in conjunction with an iterator such as a list or dictionary.
We are going to use this to combine our columns and rows into a dictionary that we append to the dataframe. The complete script is below.
import json, pandas auth = os.getenv('SMARTSHEET_TOKEN') smartsheet = '' sheetid = '3220009594972036' uri = smartsheet + sheetid header = {'Authorization': "Bearer " + auth, 'Content-Type': 'application/json'} req = requests.get(uri, headers=header) data = json.loads(req.text) cols = [] for col in data['columns']: cols.append(col['title']) df = pandas.DataFrame(columns=cols) for row in data['rows']: values = [] #re-initilise the values list for each row for cell in row['cells']: if cell.get('value'): #handle the empty values values.append( cell['value']) else: values.append('') df = df.append(dict(zip(cols, values)), ignore_index=True)
The moral of the story
While JSON provides a great data interchange standard, implementation of the file format will vary. This means we will always need to make sure we understand the structure and select the required techniques to create an analysis ready format.
This post concludes the JSON series, but will revisit the topic when new scenarios pop up.
THANK YOU very much for this very useful article. I thought I was going to get a heart attack working with Python Smartsheets SDK until I found your article.
God bless you.
Thank you for sharing this technique! I thought it would be straight forward to pull a sheet into a Pandas dataframe, but that’s not the case. | https://dataideas.blog/2018/11/13/loading-json-it-looks-simple-part-4/comment-page-1/ | CC-MAIN-2020-34 | refinedweb | 882 | 66.33 |
In the last installment, I covered innovative ways in which the Java.next languages reduce the ceremony and complexity that bedevil the Java language. In this installment, I show how these languages improve several Java sore spots: exceptions, statements versus expressions, and edge cases around
null.
Expressions
One legacy that the Java language inherited from C is the distinction between programming statements and programming expressions. Examples of Java statements are code lines that use
if or
while, and ones that use
void to declare methods that have no return value. Expressions, such as
1 + 2, evaluate to a value.
This split started in the earliest programming languages, such as Fortran, where the distinction was based on hardware considerations and a nascent understanding of programming-language design. It remained in many languages as an indicator of action (statement) versus evaluation (expression). But language designers independently and gradually realized that languages can consist entirely of expressions, ignoring the result when the outcome isn't of interest. Virtually all functional languages eliminate the distinction entirely, using only expressions.
Groovy's
if and
?:
In the Java.next languages, the split between traditional imperative (Groovy) and functional (Clojure and Scala) languages illustrates the evolution toward expressions. Groovy still has statements, which are based on Java syntax, but adds more expressions. Scala and Clojure use expressions throughout.
Inclusion of both statements and expressions adds syntactic clumsiness to languages.
Consider the
if statement in Groovy, inherited from Java. It
has two versions, which are compared in Listing 1: the
if
statement for decisions, and the cryptic ternary operator
?::
Listing 1. Groovy's two
ifs
def x = 5 def y = 0 if (x % 2 == 0) y = x * 2 else y = x - 1 println y // 4 y = x % 2 == 0 ? (x *= 2) : (x -= 1) println y // 4
In the
if statement in Listing 1, I
must set the value of
x as a side effect because the
if statement has no return value. To perform the decision and assignment at the same time, you must use the ternary assignment, as in the second assignment in Listing 1.
Scala's expression-based
if
Scala eliminates the need for the ternary operator by allowing the
if expression to handle both cases. You can use it just like the
if statement in Java code (ignoring the return value) or use it in assignments, as in Listing 2:
Listing 2. Scala's expression-based
if
val x = 5 val y = if (x % 2 == 0) x * 2 else x - 1 println(y)
Scala, like the other two Java.next languages, doesn't require an explicit
return statement for methods. In its absence, the last line of the method is the return value, emphasizing the expression-based nature of methods in these languages.
As when you act and set values in Java and Groovy code, you can encapsulate each response as a code block, as in Listing 3, and include any desired side effects:
Listing 3. Scala
if + side effects
val z = if (x % 2 == 0) { println("divisible by 2") x * 2 } else { println("not divisible by 2; odd") x - 1 } println(z)
In Listing 3, I print a status message for each case in addition
to returning the newly calculated value. The order of the code lines within the block
is important: The last line of the block represents the return value for that
condition. Thus, you must exercise special care when you mix evaluation and side effects with expression-based
if.
Clojure's expressions and side effects
Clojure also consists entirely of expressions but goes even further in differentiating side-effect code from evaluation. The Clojure version of the previous two examples is expressed in a
let block, in Listing 4, which allows the definition of locally scoped variables:
Listing 4. Clojure's expression-based
if
(let [x 5 y (if (= 0 (rem x 2)) (* x 2) (- x 1))] (println y))
In Listing 4, I assign
x a value of
5, then create the expression with
if to calculate the two conditions:
(rem x
2) calls the remainder function, similar to the Java
% operator, and compares the result to zero, checking for a zero
remainder when you divide by 2. In Clojure's
if expression, the first argument is the condition, the second the true branch, and the third is the optional else branch. The result of the
if expression is assigned to
y, which is then printed.
Clojure also allows blocks (which can include side effects) for each condition
but requires a wrapper such as
(do ...).
The wrapper evaluates each expression in the block, by using the last line as the block's return value.
Evaluating a condition and a side effect is illustrated in Listing 5:
Listing 5. Explicit side effects in Clojure
(let [x 5 a (if (= 0 (rem x 2)) (do (println "divisible by 2") (* x 2)) (do (println "not divisible by 2; odd") (- x 1)))] (println a))
In Listing 5, I assign
a the return
value of the
if expression. For each of the conditions, I
create a
(do ...) wrapper, allowing an arbitrary number of statements.
The last line of the block is the return for the
(do...)
block, similar to the Scala example in Listing 3.
Ensure that the target return value is evaluated last. The use of
(do...) blocks in this way is so common that many constructs in Clojure (such as
(let [])) already include implicit
(do ...) blocks, eliminating their need in many cases.
The contrast in treatment of expressions between Java/Groovy code and Scala/Clojure code is indicative of the general trend in programming languages to eliminate the unnecessary statement/expression dichotomy.
Exceptions
For me, the most "seemed like a good idea at the time" feature of Java programming was checked exceptions and the ability to broadcast (and enforce) exception awareness. In practice, it became a nightmare, forcing needless handling (and mishandling) of exceptions out of context.
All the Java.next languages use the exception mechanism that is already built into the
JVM, with syntax based on Java syntax and modified for their unique syntax. And they all eliminate checked exceptions, converting them into
RuntimeExceptions when they're encountered during Java interop.
Scala exhibits a couple of interesting behaviors in the translation of the Java exception-handling mechanism to work in its expression-based world. First, consider the fact that exceptions can be the return value of expressions, as illustrated in Listing 6:
Listing 6. Exceptions as return values
val quarter = if (n % 4 == 0) n / 4 else throw new RuntimeException("n must be quarterable")
In Listing 6, I assign either one-fourth the value of
n or an exception. If the exception triggers, the return value means
nothing because the exception propagates before the return is evaluated. The
legality of this assignment might seem odd, considering that Scala is a typed
language. The Scala exception type is not a numeric type, and developers are
unaccustomed to considering the return value of a
throw
expression. Scala solves this problem in an ingenious way, by using the special
Nothing type as the return type of the
throw.
Any is at the top of the
inheritance hierarchy in Scala (like
Object in Java),
meaning that all classes extend it. Conversely,
Nothing
lives at the bottom, making it an automatic subclass of all other classes. Thus, it is
legal for the code in Listing 6 to compile: either it returns
a number, or the exception triggers before a return value is set. The compiler reports
no error because
Nothing is a subclass of
Int.
Second, the
finally block has interesting behaviors in an expression-based world. Scala's
finally block works like the others functionally but exhibits a nuanced behavior around return values. Consider the code in Listing 7:
Listing 7. Scala's return from
finally
def testReturn(): Int = try { return 1 } finally { return -1 }
In Listing 7, the overall return value is
-1. The
finally block's return "overrides" the one from the body of the
try statement. This surprising result occurs only when the
finally block includes an explicit
return statement; the implicit return is ignored, as illustrated in Listing 8:
Listing 8. Scala's implicit return
def testImplicitReturn(): Int = try { 1 } finally { -1 }
In Listing 8, the return value of the function is
1, illustrating the intended use of the
finally block as a place for cleaning up side effects rather than for resolving expressions.
Clojure is also wholly expression-based. The return value of a
(try ...) is always either:
- The last line of the
tryblock in the absence of an exception
- The last line of the
catchblock that caught the exception
Listing 9 shows the syntax for exceptions in Clojure:
Listing 9. Clojure's
(try...catch...finally) block
(try (do-work) (do-more-work) (catch SomeException e (println "Caught" (.getMessage e)) "exception message") (finally (do-clean-up)))
In Listing 9, the return value of the happy path is the return from
(do-more-work).
The Java.next languages take the best parts of the Java exception mechanism and discard the cumbersome parts. And, despite some implementation differences, they manage to incorporate exceptions into an expression-based perspective.
Emptiness
In a legendary conference presentation at QCon London in 2009, Tony Hoare called his
invention of the "null" concept for ALGOL W — an experimental object-oriented
language that he introduced in 1965 — "a billion dollar mistake" because of all
the problems it caused in the programming languages that it influenced. The Java
language itself suffers from edge cases around
null, which the Java.next languages address.
For example, a common idiom in Java programming guards against a
NullPointerException before you attempt method invocation:
if (obj != null) { obj.someMethod(); }
Groovy has encapsulated this pattern into the safe navigation operator,
?.. It automatically does a null check of the left side and attempts only the method invocation if it is non-null; otherwise it returns
null.
obj?.someMethod(); def streetName = user?.address?.street
Invocations of the safe navigation operator can also be nested.
Groovy's closely related Elvis operator,
?:, shortens
the Java ternary operator in the case of default values. For example, these lines of code are equivalent:
def name = user.name ? user.name : "Unknown" //traditional ternary operator usage def name = user.name ?: "Unknown" // more-compact Elvis operator
When the left side might already have a value (generally a default), the Elvis operator preserves it, otherwise setting a new value. The Elvis operator is a shorter, expression-leaning version of the ternary operator.
Scala enhanced the concept of
null and made it a class (
scala.Null), along with a related class,
scala.Nothing.
Null and
Nothing are at the bottom of the Scala class hierarchy.
Null is a subclass of every reference class, and
Nothing is a subclass of every other type.
Scala offers an alternative to both
null and exceptions to indicate absence of value. Many Scala operations on collections (such as
get on a
Map) return an
Option instance, which contains either of two parts (but never both):
Some or
None. The REPL interaction in Listing 10 shows an example:
Listing 10. Scala's return of
Option
scala> val designers=Map("Java" -> "Gosling", "c" -> "K&R", "Pascal" -> "Wirth") designers: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Java -> Gosling, c -> K&R, Pascal -> Wirth) scala> designers get "c" res0: Option[java.lang.String] = Some(K&R) scala> designers get "Scala" res1: Option[java.lang.String] = None
Notice in Listing 10 that the return from the successful
get is an
Option[java.lang.String] =
Some(value), whereas a failed lookup results in a
None.
A technique for unwrapping values from collections uses pattern matching, which is itself an expression that allows access and unpacking in a single terse expression:
println(designers get "Pascal" match { case Some(s) => s; case None => "?"})
Option allows a better expression of emptiness than
null alone, especially considering the syntactic support for its use.
Conclusion
In this installment, I delved into three problem areas in the Java language: expressions,
exceptions, and
null. Each of the Java.next languages addresses the pain points from Java, but each in its idiomatic way. The presence of expressions changes the idioms and options for seemingly unrelated concepts such as exceptions — further illustration that language features are highly coupled to one another.
Java developers sometimes fall into the habit of thinking that inheritance is the only way to extend behavior. In the next installment, I show how the Java.next languages offer many more-powerful alternatives.
Resources
Learn
-: The Java.next languages (Neal Ford, developerWorks, January 2013): Explore the similarities and differences of three next-generation JVM languages (Groovy, Scala, and Clojure) in this overview of the Java.next languages and their benefits.
- Scala: Scala is a modern, functional language on the JVM.
- Clojure: Clojure is a modern, functional Lisp that runs on the JVM.
- Groovy: Groovy is a dynamic language for the JVM.
- Explore alternative languages for the Java platform (May 2012): Follow this knowledge path to investigate developerWorks content about various alternative JVM languages.
- Language designer's notebook (April 2010-Octover 2011): In this developerWorks series, Java Language Architect Brian Goetz explores some of the language design issues that presented challenges for the evolution of the Java language in Java SE 7, Java SE 8, and beyond.
-. | http://www.ibm.com/developerworks/opensource/library/j-jn4/index.html | CC-MAIN-2014-42 | refinedweb | 2,214 | 53.81 |
cuserid - character login name of the user (LEGACY)
#include <stdio.h> char *cuserid(char *s);
The cuserid() function generates a character representation of the name associated with the real or effective user ID of the process.
If s is a null pointer, this representation is generated in an area that may be static (and thus overwritten by subsequent calls to cuserid()), the address of which is returned. If s is not a null pointer, s is assumed to point to an array of at least {L_cuserid} bytes; the representation is deposited in this array. The symbolic constant {L_cuserid} is defined in <stdio.h> and has a value greater than 0.
If the application uses any of the _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS interfaces, the cuserid() function must be called with a non-NULL parameter.
If s is not a null pointer, s is returned. If s is not a null pointer and the login name cannot be found, the null byte `\0' will be placed at *s. If s is a null pointer and the login name cannot be found, cuserid() returns a null pointer. If s is a null pointer and the login name can be found, the address of a buffer (possibly static) containing the login name is returned.
No errors are defined.
None.
The functionality of cuserid() defined in the POSIX.1-1988 standard (and Issue 3 of this specification) differs from that of historical implementations (and Issue 2 of this specification). In the ISO POSIX-1 standard, cuserid() is removed completely. In this specification, therefore, both functionalities are allowed.
The Issue 2 functionality can be obtained by using:
getpwuid(getuid())
The Issue 3 functionality can be obtained by using:
getpwuid(geteuid())
None.
getlogin(), getpwnam(), getpwuid(), getuid(), geteuid(), <stdio.h>.
Derived from System V Release 2.0. | http://pubs.opengroup.org/onlinepubs/7908799/xsh/cuserid.html | CC-MAIN-2018-05 | refinedweb | 298 | 56.15 |
Results
A result is a record of data or a file that has been published to a storage bucket. It contains the information necessary to retrieve this data from its storage location.
Attributes
Signed URLs
If signed URL generation is enabled on the storage config used to publish the result, the
signed_url will be set to a dictionary with the format:
{ "url": "<signed URL value here>", "date_expires": "2020-02-29T11:59:15.110451Z" }
The
date_expires attribute indicates when the signed URL will cease to be valid. After this date, the result's
signed_url attribute will be set to
null.
See more details on configuring signed URLs in the storage config docs.
States
available
- The result is ready to be downloaded from the bucket.
consumed
- The result has been downloaded and the API has been informed.
expired
- The result has been deleted from the bucket by a scheduled cleanup. This state does not apply to client-owned buckets.
Retrieve
GET /results/{result ID}
Using cURL
curl<result ID> \ -H 'Authorization: Token <your key_token>'
Using ricloud-py
import ricloud results = ricloud.Result.retrieve(<result ID>)
List
GET /results
Results in the states
consumed or
expired do not appear in the list by default.
Parameters
Using cURL
curl \ -H 'Authorization: Token <your key_token>'
Using ricloud-py
import ricloud results = ricloud.Result.list()
Acknowledge
POST /results/{result ID}/ack
Acknowledge the result as having been consumed.
Using cURL
curl<result ID>/ack \ -X POST \ -H 'Authorization: Token <your key_token>'
Using ricloud-py
import ricloud result = ricloud.Result.acknowledge_with_id(<result ID>) # OR result = ricloud.Result.retrieve(<result ID>) result.acknowledge()
Batch acknowledge
POST /results/ack
Acknowledge a batch of results as having been consumed.
The endpoint will not raise an error if any of the specified results have already been acknowledged or cannot be found.
Using cURL
curl \ -X POST \ -H 'Authorization: Token <your key_token>' \ -H 'Content-Type: application/json' \ -d '{ "ids": ["<result ID>", "<result ID>"] }'
Changelog
2020-02-27
- Adds the
signed_urlattribute to the result object. This is a nested dictionary containing the signed URL in the
urlattribute and when it expires in
date_expires.
- Adds the ability to acknowledge results in batches with the new
POST /results/ackendpoint. | https://reincubate.com/support/ricloud/results/ | CC-MAIN-2021-31 | refinedweb | 364 | 56.25 |
Hi,
i need to do a HttpWebRequest against a SharePoint 2007 Server with NTLM Authentification.
For this purpose i need to use the CredentialCache in Systen.Net namespace.
VisualStudio says "The type or namespace name 'CredentialCache could not be found...".
But HttpWebRequest Class is found in this namespace.
Is this an error? Is there an alternative for doing a WebRequest with NTLM Authentification?
Thanks!
Which Xamarin.Forms template are you using? According to MSDN
CredentialCachedoesn't appear to be available in PCL.
HttpWebRequestis available in PCLs.
You could try using the Shared Project template for your app, or use the
DependencyServiceand implement your web request in the application projects if you wish to use the PCL template.
Ok thanks. I'm using PCL and now i have fixed the problem so that i can use the Credential Cache.
Johannes,
Can you elaborate on how you authenticated to Sharepoint with .NET CredentialCache in a PCL?
Any sample code would help as I want to do the same
Thanks!
ahmed | https://forums.xamarin.com/discussion/comment/78036 | CC-MAIN-2019-43 | refinedweb | 168 | 59.6 |
In C#, concatenating strings can be done with the
Concat() method of the
String class.
In other cases, you can use the
+ operator. This method returns a string which is the concatenation of the first and second strings.
string.Concat(stringA, stringB)
stringA: This is the first string that you want to concatenate.
stringB: This is the second string that you want to concatenate with the first string.
The value returned is a string that is the concatenation of
stringA and
stringB.
In the code snippet below, we have implemented the example illustrated in figure above. First, we defined and initialized the two strings
Edpr and
esso. Then with the help of
Concat() method, we concatenated the two strings.
using System; // create Concat class class Concat { // The main method static void Main() { // define and initialize strings string stringA = "Edpr"; string stringB = "esso"; // Concatenate strings string concatString = string.Concat(stringA, stringB); // print the concatenation System.Console.WriteLine(concatString); } }
RELATED TAGS
CONTRIBUTOR
View all Courses | https://www.educative.io/answers/how-to-use-the-string-concat-in-c-sharp | CC-MAIN-2022-33 | refinedweb | 163 | 66.74 |
In this section, you will learn how to format the time using a custom format.
Formatting and parsing is now become a simple task. We have so many classes
to format different objects like data, time, message etc. Here we are going to
format the time using a custom format. For this task, the class SimpleDateFormat
is more approriate. It uses unquoted letters from
'A' to
'Z'
and from
'a' to
'z' and interpret them as pattern
letters for representing the components of a date or time string. For
example,
h: It denotes the hour in am/pm.
m: It denotes minute in hour.
s: It denotes the second in minute.
a: It denotes the am/pm marker.
Here is the code:
import java.text.*; import java.util.*; public class FormattingTime { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a"); String dateString = sdf.format(new Date()); System.out.println(dateString); } }
Output:
Advertisements
Posted on: October+ | http://roseindia.net/tutorial/java/corejava/javatext/formattingTimeUsingCustomFormat.html | CC-MAIN-2015-22 | refinedweb | 160 | 60.82 |
Python API
The Python API is a concise API for using LiberTEM from Python code. It is suitable both for interactive scripting, for example from Jupyter notebooks, and for usage from within a Python application or script.
Basic example
This is a basic example to load the API, create a local cluster, load a file and run an analysis. For complete examples on how to use the Python API, please see the Jupyter notebooks in the example directory.
For more details, please see Loading data, Data Set API and format-specific reference. See Sample Datasets for publicly available datasets.
import sys import logging # Changed in 0.5.0: The thread count is set dynamically # on the workers. No need for setting environment variables anymore. import numpy as np import matplotlib.pyplot as plt from libertem import api logging.basicConfig(level=logging.WARNING) # Protect the entry point. # LiberTEM uses dask, which uses multiprocessing to # start worker processes. # if __name__ == '__main__': # api.Context() starts a new local cluster. # The "with" clause makes sure we shut it down in the end. with api.Context() as ctx: try: path = sys.argv[1] ds = ctx.load( 'auto', path=path, ) except IndexError: path = ('C:/Users/weber/Nextcloud/Projects/' 'Open Pixelated STEM framework/Data/EMPAD/' 'scan_11_x256_y256.emd') ds = ctx.load( 'hdf5', path=path, ds_path='experimental/science_data/data', ) (scan_y, scan_x, detector_y, detector_x) = ds.shape mask_shape = (detector_y, detector_x) # LiberTEM sends functions that create the masks # rather than mask data to the workers in order # to reduce transfers in the cluster. def mask(): return np.ones(shape=mask_shape) analysis = ctx.create_mask_analysis(dataset=ds, factories=[mask]) result = ctx.run(analysis, progress=True) # Do something useful with the result: print(result) print(result.mask_0.raw_data) # For each mask, one channel is present in the result. # This may be different for other analyses. # You can access the result channels by their key on # the result object: plt.figure() plt.imshow(result.mask_0.raw_data) plt.show() # Otherwise, results handle like lists. # For example, you can iterate over the result channels: raw_result_list = [channel.raw_data for channel in result]
Connect to a cluster
See Starting a custom cluster on how to start a scheduler and workers.
from libertem import api from libertem.executor.dask import DaskJobExecutor # Connect to a Dask.Distributed scheduler at 'tcp://localhost:8786' with DaskJobExecutor.connect('tcp://localhost:8786') as executor: ctx = api.Context(executor=executor) ...
Customize CPUs and CUDA devices
To control how many CPUs and which CUDA devices are used, you can specify them as follows:
from libertem import api from libertem.executor.dask import DaskJobExecutor, cluster_spec from libertem.utils.devices import detect # Find out what would be used, if you like # returns dictionary with keys "cpus" and "cudas", each with a list of device ids devices = detect() # Example: Deactivate CUDA devices by removing them from the device dictionary devices['cudas'] = [] # Example: Deactivate CuPy integration devices['has_cupy'] = False # Example: Use 3 CPUs. The IDs are ignored at the moment, i.e. no CPU pinning devices['cpus'] = range(3) # Generate a spec for a Dask.distributed SpecCluster # Relevant kwargs match the dictionary entries spec = cluster_spec(**devices) # Start a local cluster with the custom spec with DaskJobExecutor.make_local(spec=spec) as executor: ctx = api.Context(executor=executor) ...
For a full API reference, please see Python API reference.
To go beyond the included capabilities of LiberTEM, you can implement your own using User-defined functions (UDFs).
Integration with Dask arrays
The
make_dask_array() function can generate a distributed Dask array from a
DataSet using its partitions as blocks. The typical LiberTEM partition size is close to the optimum size for Dask array blocks under most circumstances. The dask array is accompanied with a map of optimal workers. This map should be passed to the
compute() method in order to construct the blocks on the workers that have them in local storage.
from libertem.contrib.daskadapter import make_dask_array # Construct a Dask array from the dataset # The second return value contains information # on workers that hold parts of a dataset in local # storage to ensure optimal data locality dask_array, workers = make_dask_array(dataset) # Use the Dask.distributed client of LiberTEM, since it may not be # the default client: result = ctx.executor.client.compute( dask_array.sum(axis=(-1, -2)) ).result() | https://libertem.github.io/LiberTEM/api.html | CC-MAIN-2021-43 | refinedweb | 701 | 50.84 |
I have different Python environments installed in different directories in Windows. How can I ensure I am using the pip for one particular version of Python?
Unfortunately, due to the groups I work with using a variety of Python flavors, I need all of the Python installations I have. I'm finding it very difficult, however, to use a version of pip that's not in my PATH.
I work with multiple Python installations, all of them in my PATH. A good way to manage this is to rename (or copy) the
python.exe and
pip.exe executables such that they describe the environment.
For example, for Python 3.5, my python executable is named
python35.exe and the pip executable is
pip35.exe For Python 2.7 The executable name is
python27.exe and the pip executable is
pip27.exe
When you install using the Windows installer from Python.org, PIP actually ships with a similar naming convention by default
pip2.7.exe for Python 2.7 or
pip3.5.exe for Python 3.5
I follow the same scheme for the various installations I have. If I want to install a package in Python 3.5 I run
pip35 install <package>
You can also use the full path to the Python or pip executable and use
pip that way. IE
C:\Python35\python.exe -m pip install <package> #or C:\Python35\Scripts\pip.exe install <package>
Another method of installing via pip is in a script/shell that you call using the appropriate version of Python.
import pip pip.main(["install", "MyPackage"]) | https://codedump.io/share/OY2IHiw9Vw7h/1/python-on-windows-which-pip | CC-MAIN-2017-51 | refinedweb | 264 | 78.85 |
In this article, we will learn how to set up a Flask MySQL database connection. So let’s get started!!
Structured Query Language
SQL allows us to access and manipulate databases. In SQL, we can perform various tasks such as:
- Adding records to databases
- Creating tables
- Perform CRUD (Create, Read, Update, Delete) operations
SQL is the query language that the database systems use. To set-up databases, we require RDMS like MySQL, PostgreSQL etc.
Do check out our SQL tutorial on the JournalDev website to gain more knowledge about the query language.
More about MySQL Database Tables
Let us now look at a typical MySQL DB table:
The rows are called records and the columns are called fields.
Therefore, in the above table, we have six records and four fields. To interact with the Table elements, we use SQL statements.
Some of the SQL statements are:
- SELECT FROM – This statement SELECTs fields(all or a few) FROM a table.
- WHERE – This conditional statement is usually used with other statements. Using this, we can select specific records satisfying some given conditions.
- UPDATE – This statement updates a table
- EDIT – This statement edits a field of record/records
- DELETE – This statement deletes a record/records
Setting-up MySQL server for our Application
In this section, we will download and establish our MySQL server
1. Installing XAMPP on your Server
Now to use MySQL, we require a software tool to handle the administration of MySQL over the web.
In this tutorial, we will work with phpMyAdmin. If you are familiar with any other software; You can use that as well.
Xampp software provides the PHPMyAdmin web interface. You can download XAMPP from here.
Or directly go to Google and search for download Xampp. The first link itself will do the job !!
Download the right version for your operating system and architecture.
2. Start Apache and MySQL
Once XAMPP is installed and loaded, start the following two processes:
- Apache Webserver – to serve HTTP requests
- MySQL Server – for the database
Do note the default port for MySQL is 3306. Now in the browser, go to.
This is the Host webpage for Xampp. Click on phpMyAdmin on the top right, to go to the php web interface.
Here,
- Create a new Database by clicking new in the left column.
- Keep a suitable Name for the DB. In my case, it is simply Flask
Go ahead and create a table in the DB. Enter the table name in the space given as shown in the picture and hit Go.
3. Installing Flask- MySQL library in our system
Flask uses flask_mysqldb connector to use MySQL. Run the following command to install the package:
pip install flask_mysqldb
Perfect !!
Setting up a Flask MySQL Database Connection
Now we will connect and use MySQL to store data into our DB. If you’re not sure how to create a flask application, check out the flask introduction tutorial.
1. Connecting Flask Application with MySQL
The procedure we follow to connect Flask-MySQL is as follows:
from flask import Flask,render_template, request from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'flask' mysql = MySQL(app)
2. Setting up MySQL connection cursor
Just with the above set-up, we can’t interact with DB tables. For that, we need something called a cursor.
So Cursor provides a way for Flask to interact with the DB tables. It can scan through the DB data, execute different SQL queries, and as well as Delete table records.
The cursor is used in the following way:
mysql = MySQL(app) #Creating a connection cursor cursor = mysql.connection.cursor() #Executing SQL Statements cursor.execute(''' CREATE TABLE table_name(field1, field2...) ''') cursor.execute(''' INSERT INTO table_name VALUES(v1,v2...) ''') cursor.execute(''' DELETE FROM table_name WHERE condition ''') #Saving the Actions performed on the DB mysql.connection.commit() #Closing the cursor cursor.close()
Since MySQL is not an auto-commit DB, we need to commit manually, ie, save the changes/actions performed by the cursor execute on the DB .
3. Coding a Flask application
Now we will build a small Flask application that will store data submitted by the user in the MySQL DB Table. Consider the following Application Code:
from flask import Flask,render_template, request from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'flask' mysql = MySQL(app) @app.route('/form') def form(): return render_template('form.html') @app.route('/login', methods = ['POST', 'GET']) def login(): if request.method == 'GET': return "Login via the login Form" if request.method == 'POST': name = request.form['name'] age = request.form['age'] cursor = mysql.connection.cursor() cursor.execute(''' INSERT INTO info_table VALUES(%s,%s)''',(name,age)) mysql.connection.commit() cursor.close() return f"Done!!" app.run(host='localhost', port=5000)
When the user submits the data, it is added into the MySQL DB via the cursor.execute command. My table name is info_table.
The form.html will be:
<form action="/login" method = "POST"> <p>name <input type = "text" name = "name" /></p> <p>age <input type = "integer" name = "age" /></p> <p><input type = "submit" value = "Submit" /></p> </form>
4. Implementing the Code
Now fire up the server and go to “/form” (see Flask forms)
Enter the details and hit Submit
Now let’s check it in the phpMyAdmin web interface
Perfect!!
Conclusion
That’s it, guys!! This was all about setting up Flask MySQL connections. In the next article, we will look into Flask-PostgreSQL.
See you in the next time 🙂 | https://www.askpython.com/python-modules/flask/flask-mysql-database | CC-MAIN-2021-31 | refinedweb | 925 | 67.55 |
JMS Over HTTP using OpenMQ (Sun Java System Message Queue and HTTP tunneling)
You may have already faced situation when you need to have messaging capabilities in your application while your client application runs in an environment which you have no control over its network configuration and restrictions. Such situation lead to the fact that you can not use JMS communication over designated ports like 7676 and so.
You may simply put JMS away and follow another protocol or even plain HTTP communication to address your architecture and design requirement, but we can not easily put pure JMS API capabilities away as we may need durable subscription over a proven and already well tested and established design and architecture. Different JMS implementation providers provide different type capabilities to address such a requirement. ActiveMQ provide HTTP and HTTPS transport for JMS API and described it here.
OpenMQ provide different transport protocol and access channels to access OpenMQ functionalities from different prgramming . One of the access channles which involve HTTP is named Universal Message Service (UMS) which provide a simple REST interaction template to place messages and comsume them from any programming language and device which can interact with a network server. UMS has some limitations which is simply understandable based on the RESTful nature of UMS. For current version of OpenMQ, it only supports Message Queues as destinations so there is no publish-subscribe functionality available.
Another capability which involve HTTP is JMS over HTTP or simply JMS HTTP tunneling. OpenMQ JMS implementation supports HTTP/s as transport protocol if we configure the message broker properly. Well I said the JMS implementation support HTTP/S as a transport protocol which means we as user of the JMS API see almost no difference in the way that we use the JMS API. We can use publish-subscribe, point to point, durable subscription, transaction and whatever provided in the JMS API.
First, lets overview the OpenMQ installation and configuration then we will take a look at an example to see what changes between using JMS API and JMS API over HTTP transport. Installation process is as follow:
- Download OpenMQ from it should be a zip which is different for each platform.
- Install the MQ by unzipping the above file and running ./installer or installer.bat or so.
- After the installation completed, go to install_folder/var/mq/instances/imqbroker/props and open the config.properties in a text editor like notepad or emeditor or gedit.
- Add the following line to the end of the above file:
OpenMQ project provides a Java EE web application which interact with OpenMQ broker from one side and Sun JMS implementation on the other side. Interaction of this application with the client and MQ broker is highly customizable in different aspects like Broker port number, client poll inrval, Broker address and so on.
imq.service.activelist=jms,admin,httpjms </code>
Now let's see how we can publish some messages, this sample code assume that we have configured the message broker and assumes that we have the following two JAR files in the classpath. These JAR files are available in install_folder/mq/lib/
- imq.jar
- jms.jar
Now the Publisher code:
public class Publisher { public void publish(String messageContent) { try {"); javax.jms.Session session = con.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); top = session.createTopic("DIRECT_TOPIC"); MessageProducer prod = session.createProducer(top); Message textMessage = session.createTextMessage(messageContent); prod.send(textMessage); prod.close(); session.close(); con.close(); } catch (JMSException ex) { ex.printStackTrace(); } } public static void main(String args[]) { Publisher p = new Publisher(); for (int i = 1; i < 10; i++) { p.publish("Sample Text Message Content: " + i); } } } </code>
As you can see the only difference is the connection URL which uses http instead of mq and point to a Servlet container address instead of pointing to the Broker listening address.
The subscriber sample code follow a similar pattern. Here I write a sample durable subscriber so you can see that we can use durable subscribtion over HTTP. But you should note that HTTP transport uses polling and continuesly open communication channel which can introduce some overload on the server.
class SimpleListener implements MessageListener { public void onMessage(Message msg) { System.out.println("On Message Called"); if (msg instanceof TextMessage) { try { System.out.print(((TextMessage) msg).getText()); } catch (JMSException ex) { ex.printStackTrace(); } } } } public class Subscriber { /** * @param args the command line arguments */ public void subscribe(String clientID, String susbscritpionID) { try { // TODO code application logic here"); con.setClientID(clientID); javax.jms.Session session = con.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); top = session.createTopic("DIRECT_TOPIC"); TopicSubscriber topicSubscriber = session.createDurableSubscriber(top, susbscritpionID); topicSubscriber.setMessageListener(new SimpleListener()); con.start(); } catch (JMSException ex) { ex.printStackTrace(); } } public static void main(String args[]) { Subscriber sub = new Subscriber(); sub.subscribe("C19", "C1_011"); } } </code>
Now how you can test the entire example and monitor the MQ? it is very simple by utilizing the provided tools.
Do the following steps to test the overall durable subscription system:
- Run a subscriber
- Run another subscriber with a different client ID
- Run a publisher once or twice
- Kill the second subscriber
- Run a publisher once
- Run the subscriber and you can see that the subscriber will fetch all messages which arrived after it shut down-ed.
Note that we can not have two separate client with same client ID running because the broker will not be able to distinguish which client it should send the messages.
- You can monitor the queue and the broker using: ./imqadmin which can be found in install_folder/mq/bin this software shows how many durable subscribers are around and how many messages are pending for each subscriber and so on.
- You can monitor the Queue in real-time mode using the following command which can be executed in install_folder/mq/bin
./imqcmd -b 127.0.0.1:7979 metrics dst -t t -n DIRECT_TOPIC The command will ask for username and password, give admin/admin for it
The sample code for this entry can be found Here. The sample code is a NetBeans project with the publisher and the subscriber source code.
A complete documentation of OpenMQ is available at its documentation centre. You can see how you can change different port numbers or configure different properties of the Broker and HTTP tunneling web application communication.
- Login or register to post comments
- Printer-friendly version
- kalali's blog
- 4866 reads
Using the JMS over HTTP with the EMBEDDED broker
by jthoennes - 2009-09-15 06:04Hi, I wonder whether this works out-of-the-box with the EMBEDDED MQ broker of the Glassfish. In that case, the explicit step to start the broker is not needed. Any special configuration needed for this? Thanks, Jörg
HTTP for BLOBs
by roridge - 2009-08-28 01:54Hi, Good post, could have done with that a year ago :) I have been using JMS over HTTP with OpenMQ for about a year now, and for a TextMessage it is pretty good. However, a StreamMessage with a BLOB is a noticeable difference, it is at least 3 times slower than TCP to send the message, end to end for about 50MB is taking upwards of 4 minutes. I can only assume this is because each message is now performing a triple hop as it has to go through the servlet? I would be interested to know what speed you can send ~50MB at from end-to-end. Also, I have been trying to work out how the servlet sends the message on to the broker, when it has no obvious knowledge of the broker other than a port. I had originally assumed that the servlet would merely push the message onwards to the broker via TCP, however, I now wonder if it is the broker who connects to the servlet and pulls? Many thanks Ror
by dgavenda - 2009-07-23 06:13I have it working now. Thanks for the help and the post.
by kalali - 2009-07-22 14:46@dgavenda, There are two possibilities that you can not see the instance folder: first: You should start the broker at leas one time to have that instance folder created. You may had not started the server before you have looked for the file. second which I can hardly imagine about your case is a configuration element named IMQ_DEFAULT_VARHOME. this element specifies the default var home of you openMQ installation. You can check its value by looking at install_folder/etc/imqenv.conf file. hope it helps
by dgavenda - 2009-07-22 11:35It seems this refers to OpenMQ 4.1. I was able to find that file in 4.1. Where is the similar config file in 4.3? Or would you suggest to use 4.1?
by dgavenda - 2009-07-22 10:52"After the installation completed, go to install_folder/var/mq/instances/imqbroker/props and open the config.properties in a text editor like notepad or emeditor or gedit. " I am using the binary version of openMQ 4.3 for Linux. After I unzip the zip file and run ./installer, I do not have anything in the install_folder/var/mq/instances directory. Also, there doesn't seem to be a config.properties file in the MessageQueue directory. I checked recursively too. What am I missing?
by aberrant - 2009-06-22 07:32Fantastic, thank you.
by kalali - 2009-06-19 14:32An untrusted applet can communicate back to a server which it is initiated from (server which hosted the applet and delivered the .class and jar files). So your applet can either use mq protocol or it can use JMS over HTTP protocol which is shown in the sample.
by aberrant - 2009-06-19 14:16Is this technique compatible with the applet security rules? Can I have an unsigned applet that connects back to the server it was loaded from using JMS over HTTP? That would be really cool. | http://weblogs.java.net/blog/kalali/archive/2009/06/jms_over_http_u.html | crawl-003 | refinedweb | 1,639 | 55.44 |
Linked by Thom Holwerda on Mon 13th Dec 2010 19:27 UTC, submitted by lemur2
Thread beginning with comment 453556
To view parent comment, click here.
To read all comments associated with this story, please click here.
To view parent comment, click here.
To read all comments associated with this story, please click here.
RE[3]: Computer programming isn't 'Safe'
by TheGZeus on Tue 14th Dec 2010 21:38 in reply to "RE[2]: Computer programming isn't 'Safe'"
Member since:
2005-07-22
Writing anything solely for money isn't a safe activity, indeed.
You either end up starving, frustrated, and lonely, wondering why no one will compensate you for what you want to do, or you end up writing trite crap novels with titles like "A is for Alibi", if one's writing prose.
I suggest writing for the sake of writing, and then finding a way to make money, be it from said writing or other means.
That said, your bitter rant has little to do with the subject at hand.
'Bitter rant' - huh? I am not bitter and find programming in C# rather fun.
Comparing the risk of being sued for writing Free Software using the 'wrong C# namespaces' is so infinitesimally small compared with the other everyday risks of being a computer programmer is not a 'rant'. I am not bitter because I am happily employed. I like C# and have written language bindings for the Qt and KDE apis (Qyoto and Kimono) without anyone paying me and have certainly not been bothered about this imaginary risk stuff. | http://www.osnews.com/thread?453556 | CC-MAIN-2016-50 | refinedweb | 264 | 68.6 |
#include <wx/dcclient.h>
A wxPaintDC must be constructed if an application wishes to paint on the client area of a window from within an EVT_PAINT() event handler.
This should normally be constructed as a temporary stack object; don't store a wxPaintDC object. If you have an EVT_PAINT() handler, you must create a wxPaintDC object within it even if you don't actually use it.
Using wxPaintDC within your EVT_PAINT() handler is important because it automatically sets the clipping area to the damaged area of the window. Attempts to draw outside this area do not appear.
To draw on a window from outside your EVT_PAINT() handler, construct a wxClientDC object.
To draw on the whole window including decorations, construct a wxWindowDC object (Windows only).
A wxPaintDC object is initialized to use the same font and colours as the window it is associated with.
Constructor.
Pass a pointer to the window on which you wish to paint. | http://docs.wxwidgets.org/trunk/classwx_paint_d_c.html | CC-MAIN-2014-15 | refinedweb | 157 | 54.22 |
a newbie in Python and pyOpenGL.)
Environment:
WinXP SP2
Python ver. 2.5
WingIDE
easy_install is installed
PIL, pyNum is installed
Download PyOpenGL-3.0.0a5-py2.5.egg
run: easy_install PyOpenGL-3.0.0a5-py2.5.egg
pyOpenGL is installed in
D:\Python25\Lib\site-packages\PyOpenGL-3.0.0a5-py2.5.egg\
I tried to run a example ".\OpenGL\Demo\da\dots.py", but it fails in
the line:
from OpenGL.GL import *
with errors:
AttributeError: 'WinFunctionType' object has no attribute
'returnValues'
Traceback (innermost last):
File "OpenGL\Demo\da\dots.py", line 1, in <module>
#!/usr/bin/python
File "OpenGL\Demo\da\dots.py", line 24, in <module>
from OpenGL.GL import *
File "OpenGL\GL\__init__.py", line 3, in <module>
from OpenGL.raw.GL.annotations import *
File "OpenGL\raw\GL\annotations.py", line 19, in <module>
'textures',
File "OpenGL\arrays\arrayhelpers.py", line 68, in setInputArraySizeType
if not hasattr( function, 'returnValues' ):
File "OpenGL\wrapper.py", line 64, in __getattr__
return getattr( self.wrappedOperation, key )
It seems that pyOpenGL reimplements the module "ctypes" internally, but
not finished.... I cannot find "self.wrappedOperation" with any
attribute with the name of 'returnValues'. How to go through this
problem? Did I make some simple mistakes at the beginning of the
installation of pyOpenGL?
Thank you!
ShenLei
I was happy to see the new binaries for PyOpenGL for Python 2.5
and was hoping that you would produce a windows installer for
OpenGL Context and Python 2.5
Hello, Dear All
I have about 40 python seperate files and want to
compile it into a executable. My source code works
very well. And the exe also works, but one of function
cannot work correctly, The error like following. But
the Tuple is defined in
/usr/lib/python2.4/site-packages/OpenGL-
3.0.0a4-py2.4.egg/OpenGL/Tk/__init__.py, in line 322.
But not my input value. I use pyopengl3.00a4.py2.4.
Anybody can explain it.
Error: 1
TypeError Exception in Tk callback
Function: <bound method NewGl.tkExpose of
<gldisp.NewGl instance at 0xb6e68cec>> (type: <type
'instancemethod'>)
Args: (<Tkinter.Event instance at 0xb6e7570c>,)
Event type: ConfigureNotify
Traceback (innermost last):
File "Pmw.py", line 1383, in __call__
None
File "/usr/lib/python2.4/site-packages/OpenGL-
3.0.0a4-py2.4.egg/OpenGL/Tk/__init__.py", line 548, in
tkExpose
self.basic_lighting()
File
"/usr/lib/python2.4/site-packages/OpenGL-3.0.0a4-py2.4.egg/OpenGL/Tk/__init__.py",
line 323, in basic_lighting
glLightfv(GL_LIGHT0, GL_POSITION, light_position)
File
"/usr/lib/python2.4/site-packages/OpenGL-3.0.0a4-py2.4.egg/OpenGL/wrapper.py",
line 1621, in __call__
return self.finalise()( *args, **named )
File
"/usr/lib/python2.4/site-packages/OpenGL-3.0.0a4-py2.4.egg/OpenGL/wrapper.py",
line 664, in wrapperCall
pyArgs.append( converter(arg, self, args) )
File "/usr/lib/python2.4/site-packages/OpenGL-
3.0.0a4-py2.4.egg/OpenGL/converters.py", line 113, in
__call__
return self.function( incoming )
File
"/usr/lib/python2.4/site-packages/OpenGL-3.0.0a4-py2.4.egg/OpenGL/arrays/arraydatatype.py",
line 52, in asArray
return cls.getHandler(value).asArray( value,
typeCode or cls.typeConstant )
File
"/usr/lib/python2.4/site-packages/OpenGL-3.0.0a4-py2.4.egg/OpenGL/arrays/arraydatatype.py",
line 31, in getHandler
raise TypeError(
TypeError: No array-type handler for type <type
'tuple'> (value: (1, 1, 1, 0) ) registered
Thanks,
John
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
Greg Ewing wrote:
> altern wrote:
>
>> I tried to replace all the 0 value in all vertexes by 0.5 but it
>> doesnt work either.
>
> You might need size[0]-0.5 and size[1]-0.5 as well.
same problem as before. I tried different combinations and it doesnt
seem to be one way to get it right in all machines and platforms.
altern wrote:
> I tried to replace all the 0 value in all vertexes by 0.5 but it doesnt
> work either.
You might need size[0]-0.5 and size[1]-0.5 as well.
--
Greg
hi greg
Greg Ewing wrote:
>.
This is the way i set the projection and draw the lines, being
size=(800,600) in my example
# the projection
glOrtho(0, size[0], size[1], 0, 1, 0)
# red marquee with diagonal lines cross
glBegin(GL_LINE_LOOP)
glColor3f(1,0,0) #
glVertex2i(0,0)
glVertex2i(size[0], size[1])
glVertex2i(0, size[1])
glVertex2i(size[0], 0)
glVertex2i(0,0) # marquee
glVertex2i(size[0], 0)
glVertex2i(size[0], size[1])
glVertex2i(0, size[1])
glEnd() # end line loop
I tried to replace all the 0 value in all vertexes by 0.5 but it doesnt
work either. I also tried to change the glOrtho to
glOrtho(0.5, size[0], size[1], 0.5, 1, 0)
and also combining both with no luck.
However if I set glOrtho like this
glOrtho(-1, size[0], size[1]+1, 0, 1, 0)
then it works fine on my Debian desktop and on my debian laptop but not
on my laptop with XP. So I decided to do tests in all systems on my
machines. This is the result:
glOrtho(-1, size[0], size[1]+1, 0, 1, 0)
works on Debian desktop with a matrox card
works on Debian laptop with ATI
glOrtho(-1, size[0], size[1]+1, -1, 1, 0)
works on XP laptop with ATI
glOrtho(-1, size[0]+1, size[1], 1, 0)
works on XP Desktop with matrox card
I also tested on and old mac ibook with ATI card running 10.4.8 and on
that it works if i do
glOrtho(0, size[0], size[1]+1, -1, 1, 0)
Not very consistent. It seems to me that it might be more to do with the
OS rather than with the cards themselves. The XP versions I am running
are different but the Debian are pretty much the same.
I attach my example in case anyone wants to test it out his/her machine.
The glOrtho is on line 19 and i pasted different combinations of
setup the glOrtho
thanks!
enrike.
--
Greg
hi
i am using glOrtho to create a 2D projection where I map the opengl
units to pixels. The problem comes when running the same example in
different systems and machines I get one pixel difference between
systems. The example draws a one pixel wide box in the borders of the
window. In none of the sytems I tried so far the box was totally
visible. There is always one or two sides missing just by one pixel.
I guess this has to do with the way graphics cards decide to render the
opengl units into pixels in the screen. I tested on same Debian in two
different machines and i get different results.
Also I guess there is no much i can do about this. But maybe I am
missing something. I setup glOrtho like this
glOrtho(0, 800, 600, 0, 1, 0)
I am using pygame to open the window.
thanks
enrike
Mike C. Fletcher wrote:
...
> Urgh. Well, I guess that explains the weird code and the "init"
> functions for the extensions. Going to have to fix that at the PyOpenGL
> level. Grr. If it's really context-dependent we're going to have to
> run an extra function for every extension function (since you can have
> multiple contexts) :( . Wow, that's a sub-optimal design. Someone
> should yell at the MS programmers. Oh well, Windows, what are you going
> to do.
>
> Ah, if I'm implying correctly from the wglGetProcAddress "man page",
> it's actually just that the function might not be available on *this*
> context, so we just have to delay resolution until the first call (or
> more realistically, do a check for NULL function pointer and if NULL do
> a wglGetProcAddress to see if we can get a non-null pointer before
> raising the "function is null" error). Will require that the "null
> function pointer" objects be capable of replacing themselves (somehow)
> with the extension function... but then the normal import mechanism
> pulls them from the module directly... bah. Don't want the overhead of
> an extra Python function call just to allow for late loading on windows,
> we want the raw ctypes function pointers whereever possible (for
> speed). This is going to be a PITA one way or another. Oh well.
>
> Thanks for the report, I'll try to look into it this weekend.
>
PyOpenGL 3.x CVS now has what appears to be a fix for this. Basically
if there is a NULL pointer for an extension then every time you try to
call it, before raising the error it checks to see if the function is
available in the current context, if so, it loads the function and then
substitutes the __call__ method for the function's call with a
staticmethod wrapper (C-coded, so should be moderately fast).
There is still a performance penalty, but it should make most operations
fairly intuitive. The biggest problem it introduces is that any wrapper
code that checks for the boolean truth of an extension function to "see
if it is available" is going to think it's not available. That's pretty
sub-optimal IMO. Just don't have an elegant solution to it yet.
Have fun,
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder | https://sourceforge.net/p/pyopengl/mailman/pyopengl-users/?style=flat&viewmonth=200612 | CC-MAIN-2017-39 | refinedweb | 1,568 | 67.86 |
I have to create a program that requires the user to enter the zip code. The zip code must be 5 digits. I know how to do that using if statement and string.length(). What I don't know how to do is how to make sure the program only inputs and accepts zip codes that start with 606 and 605.
Here's my code so far
#include <iostream> #include <string> using namespace std; int main() { cout << "Please enter zip code: "; string = zipCode; getline(cin,zipCode); if (zipCode.length() == 5 && ) { } else cout << "Please enter a 5 digit Zip Code ";
I have to use a string function | https://www.daniweb.com/programming/software-development/threads/330348/how-to-search-and-match-strings | CC-MAIN-2020-40 | refinedweb | 106 | 79.9 |
im_dilate, im_dilate_raw, im_erode, im_erode_raw - perform morphological operations on a white object against a black background
#include <vips/vips.h> int im_dilate(in, out, m) IMAGE *in, *out; INTMASK *m; int im_erode(in, out, m) IMAGE *in, *out; INTMASK *m; int im_dilate_raw(in, out, m) IMAGE *in, *out; INTMASK *m; int im_erode_raw(in, out, m) IMAGE *in, *out; INTMASK *m;
The above functions are applications of morphological operations on one channel binary images ie. images with pixels that are either 0 (black) or 255 (white). All functions assume that input images contain white objects against a black background. Mask coefficients can be either 0 (for object) or 255 (for background) or 128 (for do not care). The mask should have odd length sides and the origin of the mask is at location (m->xsize/2,m->ysize/2) integer division. All algorithms have been based on the book "Fundamentals of Digital Image Processing" by A. Jain, pp 384-388, Prentice-Hall, 1989. Essentially, im_dilate(3) sets pixels in the output if *any* part of the mask matches, whereas im_erode(3) sets pixels only if *all* of the mask matches. im_dilate(3) dilates the image pointed by in, according to the mask pointed by m and writes the result in the location pointed by the IMAGE descriptor out. The output image is the same size as the input, in the manner of im_conv(3). im_dilate_raw(3) works as im_dilate(3), but does not expand the input. im_erode(3) erodes the image pointed by in, according to the mask pointed by m and writes the result in the location pointed by the IMAGE descriptor out. Again, the output image is forced to have the same size as the input. im_erode_raw(3) works as im_erode(3), but does not expand the input. See the boolean operations im_andimage(3), im_orimage(3) and im_eorimage(3) for analogues of the usual set difference and set union operations.
All functions returns 0 on success and -1 on error.
im_read_imask(3), im_conv(3), im_andimage(3), im_rotate_imask(3).
1991-1995, Birkbeck College and the National Gallery 14 May 1991 | http://huge-man-linux.net/man3/im_dilate.html | CC-MAIN-2017-13 | refinedweb | 349 | 62.88 |
Digital Image or Video Editing
Those who do much serious image
editing value more than all else; sheer- raw - power. A good video
card is nice but definitely secondary to the brute force required to
complete the algorithms needed to manipulate large image files and the
special effects many require
Almost as important is the ability to
have large amounts of hard drive storage space with a large monitor with a high
resolution. (but not too high) Be careful not to think the higher the
resolution the better your images will look. Your images themselves will not
get the extra pixels, only your desktop does. Your images will actually
get smaller to see. Go for a high res. screen if your images are more
pixels in size than your LCD. Especially if you need to see the whole
image as close as possible to its full size. If your images are in the
hundreds of pixels and not thousand, then stay away from UXGA style
screens. Go with a SXGA version.
Another valuable feature is being able to read flash memory cards. CD-RW's and DVD-RW's make large
hard drive a little less necessary since you can archive photos for later
use without tying up large volumes of disk space.
The suggested laptops below will fill your needs very nicely in most of
these categories.
Few laptops can excel at every one of these areas, so you generally
choose the features mentioned that are the most important to your needs.
The two systems that can accomplish all these tasks are the 8588X
and the 870P. The
8588X has the power, along with a variety of input ports. A strong 2nd is
the 5690X because it shares the same powerful motherboard speed. If
your images are primarily in landscape orientation then consider the D470W
17" WideView laptop. Nearly as powerful as the 8588X but with a LCD that
can lend itself to unique images applications.
FYI: The Card Reader is a handy device that can read
multiple formats of the popular flash memory cards used in digital cameras
and digital video cameras as well as MP3 players. Having one allows direct
import of the files into your laptop for manipulation.
Al the above unit have all Hyper threading CPU's or
equivalent, 800FSB, 400 MHz RAM
Cheap Laptops Home Page | http://www.mtechcomputer.com/imageeditlaptops.html | crawl-001 | refinedweb | 392 | 70.53 |
rod.recipe.appengine 2.0.0
ZC Buildout recipe for setting up a Google App Engine development environment.
The rod.recipe.appengine is a zc.buildout recipe to build, test and deploy projects for the Google App Engine. It makes it easy to use eggs and resolve their dependencies automatically.
To be honest, this is a recipe for scrambled eggs. It produces a zip file containing all configured external packages in a traditional folder hierarchy.
This software is released under the GNU Lesser General Public License, Version 3.
Credits
Thanks to Attila Olah who provided a patch which fixes two issues where the recipe wasn't able to find the original pkg_resources.py file. He also enabled the recipe to be used together with distribute as a replacement for setuptools.
Attila Olah also provided a patch for supporting regular expressions when using the exclude option.
Thanks to Tom Lynn for submitting a patch which fixes an issue with symlink on platforms other than UNIX.
Lots of thanks to Gael Pasgrimaud for submitting a patch that allows for zc.recipe.egg options such as extra-paths and entry-points.
A brief documentation
This recipe takes a number of options:
- appengine-lib
- Path to an already installed appengine library
- eggs
- List of required eggs
- entry-points
- A list of entry-point identifiers. See zc.recipe.egg for a more detailed documentation.
- exclude
- A list of basenames and regular expressions to be excluded when setting up the application files, e.g. the whole 'tests' directory.
- extra-paths
- Extra paths to include in a generated script.
- initialization
- Specify some Python initialization code. This is very limited. In particular, be aware that leading whitespace is stripped from the code given.
- packages
- A list of packages to be included into the zip archive, which will be uploaded to the appspot.
- patch
- Specifies a patch file for patching the SDK source-tree. This option is not allowed if appengine-lib is specified.
- patch-options
- List of patch options separated by blanks. (Default=-p1)
- server-script
- The name of the script to run the development server.
- src
- The directory which contains the project source files.
- url
- The url for fetching the google appengine distribution
- use_setuptools_pkg_resources
- Flag whether the recipe shall copy setuptool's pkg_resources.py into the app directory rather than writing a dummy version. (Default=False)
- zip-name
- The name of the zip archive containing all external packages ready to deploy.
- zip-packages
- Flag whether external packages shall be zipped into a single zip file. (Default=True)
Tests
We will define a buildout template used by the recipe:
>>> buildout_template = """ ... [buildout] ... develop = %(dev)s ... parts = sample ... ... [sample] ... recipe = rod.recipe.appengine ... eggs = foo.bar ... packages = ... bazpkg ... tinypkg ... server-script = dev_appserver ... zip-packages = False ... exclude = .*foo/bar/test.*$ ...})
Running the buildout gives us:
>>> print system(buildout) Develop: '.../tests/foo.bar' Develop: '.../tests/bazpkg' Develop: '.../tests/tinypkg' Installing sample. rod.recipe.appengine: downloading Google App Engine distribution... Generated script '/sample-buildout/bin/dev_appserver'. Generated script '/sample-buildout/bin/appcfg'.
This will generate some scripts:
>>> ls('bin') - appcfg - buildout - dev_appserver
And now we try to run the appserver script:
>>> print system(os.path.join('bin', 'dev_appserver'), '-h') Runs a development application server for an application. ...
There should be a configuration script in bin as well:
>>> print system(os.path.join('bin', 'appcfg')) Usage: appcfg [options] <action> ...
Let's see if the 'tests' directory has been excluded:
>>> l = os.listdir(os.sep.join(['parts', 'sample', 'foo', 'bar'])) >>> assert 'tests' not in l
There should be a baz package within our application directory:
>>> assert 'baz' in os.listdir(os.sep.join(['parts', 'sample']))
Let's define another buildout template used by the recipe:
>>> buildout_template = """ ... [buildout] ... develop = %(dev)s ... parts = second_sample ... ... [second_sample] ... recipe = rod.recipe.appengine ... eggs = foo.bar ... use_setuptools_pkg_resources = True ... packages = ... bazpkg ... tinypkg ... patch = %(patch)s ... patch-options = -p1 ... zip-packages = False ... exclude = tests ...') >>> patch = os.path.join(os.path.split(tests.__file__)[0], 'patch.diff') >>> write('buildout.cfg', buildout_template % ... {'dev': egg_src+' '+baz_pkg+' '+tiny_pkg, 'patch': patch})
Running the buildout gives us:
>>> output = system(buildout) >>> if output.endswith( ... "patching file lib/patched/patched.txt\n"): True ... else: print output True
And now we try to run the appserver script:
>>> print system(os.path.join('bin', 'second_sample'), '-h') Runs a development application server for an application. ...
Let's have a look if all dependent packages are copied into our application directory:
>>> os.path.isfile(os.path.join('parts', 'second_sample', 'tinymodule.py')) True >>> os.path.isdir(os.path.join('parts', 'second_sample', 'baz')) True
Setuptool's original pkg_resources.py file should be copied into our app directory:
>>> pkg_resources = os.path.join( ... 'parts', 'second_sample', 'pkg_resources.py') >>> os.path.isfile(pkg_resources) True >>> pkg_resources_file = open(pkg_resources, "r") >>> pkg_resources_file.read().startswith('def _dummy_func') False >>> pkg_resources_file.close()
We've configured the recipe to patch the SDK's source tree:
>>> gae_sdk_root = os.path.join('parts', 'google_appengine') >>> patched_dir = os.listdir(os.path.join(gae_sdk_root, 'lib')) >>> patched_file = open( ... os.path.join(gae_sdk_root, 'google', 'appengine', 'tools', ... 'dev_appserver.py')).read()[:1300] >>> 'patched' in patched_dir True >>> '# This file is patched by the patch command.' in patched_file True
You can also add some extra script:
>>> buildout_template = """ ... [buildout] ... develop = %(dev)s ... parts = script_sample ... ... [script_sample] ... recipe = rod.recipe.appengine ... eggs = foo.bar ... use_setuptools_pkg_resources = True ... packages = ... bazpkg ... tinypkg ... zip-packages = False ... exclude = tests ... url = ... entry-points = manage=django.core:execute_manager ... initialization = import settings ... arguments = settings ... # your script may need some extra-paths ... extra-paths = ... /some/extra/path ... ${buildout:parts-directory}/google_appengine/lib/simplejson ... """})>>> print 'Start...', system(buildout) Start... Generated script '/sample-buildout/bin/manage'...
Then you get a script:
>>> cat('bin', 'manage') #!...python... import sys sys.path[0:0] = [ '/some/extra/path', '/sample-buildout/parts/google_appengine/lib/simplejson', '/sample-buildout/parts/google_appengine', ] <BLANKLINE> <BLANKLINE> import settings <BLANKLINE> import django.core <BLANKLINE> if __name__ == '__main__': django.core.execute_manager(settings)
Changes
2.0.0 2011-07-01
- Adds support for zc.recipe.eggs options such as entry-points and extra-paths.
1.7.0 2011-05-16
- Adds support for regular expression excludes.
- Minor refactoring and clean-up.
1.6.2 2010-04-18
- Fixes an issue where symlink fails on platforms other than UNIX.
1.6.1 2010-04-03
- Fixes an issue where the patch option can't be used without patch-options.
1.6.0 2010-04-03
- New option to specify a patch file for modifying the Google App Engine SDK source tree.
1.5.1 2010-03-27
- Fixes an issue where setuptools wasn't found.
- Distribute can be used as a replacement for setuptools.
- Added credits for Attila Olah.
1.5.0 2010-03-27
- Adds option to copy setuptool's original pkg_resources.py file into app directory rather than writing a dummy stub.
1.4.1 2010-01-18
- Fixes an issue where egg contents which are just single modules aren't copied into the project.
1.4.0 2009-08-26
- Added server-script option.
- Tests added.
1.3.1 2009-07-15
- Fixed issue when copying egg contents.
1.3.0 2009-07-04
- Added options zip-packages and exclude.
1.2.1 2009-07-03
- Uses a much better method for excluding optional c extensions and compiled modules.
- A step forward in platform independence.
1.2.0 2009-06-24
- Creates appcfg script.
1.1.1 2009-06-07
- Makes symbolic links for application files.
- Downloads stay untouched.
1.1.0 2009-04-08
- Mostly rewritten.
- Installs google appengine as part.
- Adding dummy pkg_resources module to handle namespace package relicts.
- Tests added.
- Ready for Google App Engine SDK 1.2.0
1.0.0b5 2009-01-20
- Requires Google App Engine SDK 1.1.8
1.0.0b4 2008-09-04
- Create and use PROJECT_HOME/var to place temporary project files like data base files.
1.0.0b3 2008-09-02
- Copy package contents to temporary library directory.
1.0.0b2 2008-09-02
- Installs the whole distribution in the parts directory now. So it is ready to test and deploy.
1.0.0b1 2008-09-01
- First beta release.
- Author: Tobias Rodaebel
- Keywords: appengine gae zc.buildout recipe zope
- License: LGPL 3
- Categories
- Package Index Owner: safari
- DOAP record: rod.recipe.appengine-2.0.0.xml | http://pypi.python.org/pypi/rod.recipe.appengine/2.0.0 | crawl-003 | refinedweb | 1,353 | 52.56 |
Created on 2012-04-09 20:01 by Michel.Leunen, last changed 2012-04-19 11:55 by Michel.Leunen. This issue is now closed.
HTMLParser fails to parse this structure of tags:
'<a></a><script></script><meta><meta / ><body></body>'
Parsing stops after the first meta tag ignoring the remainers
from HTMLParser import HTMLParser
parser = process_html()
parser.feed('<a></a><script></script><meta><meta / ><body></body>')
Python 2.7.2+ Ubuntu 11.10
What do you think it should do?
My thought is that meta tags may or may not be void, but certainly should not be nested. As XML, I would parse that as
<a></a>
<script></script>
<meta>
<meta / >
<body></body>
*missing closing tag
But for html, there is more cleanup. The catch is that this module probably can't keep up with BeautifulSoup or HTML5lib ... is this particular tag situation common enough to be even have a defined handling, let alone one that is worth adding to a "simple" module?
With Python 2.7.3rc2 and 3.3.0a0 (strict=False) I get:
Start tag: a
End tag : a
Start tag: script
End tag : script
Start tag: meta
Data : <meta / >
Start tag: body
End tag : body
This is better, but still not 100% correct, the "<meta / >" shouldn't be seen as data.
ISTM that "<meta / >" is neither valid HTML nor valid XHTML.
Here's a patch.
-1 on that particular patch.
<tagname / >
(with only whitespace between "/" and ">") strikes me as obviously intending to close the tag, and a reasonably common error.
I can't think of any reason to support nested meta tags while not supporting sloppy self-closing tags.
This issue is also marked for (bugfix-only) 2.7 and 3.2.
Unless there is a specification somewhere (or at least an editor's draft), I can't really see any particular parse as a bugfix. Was the goal just to make the parse finish, as opposed to stopping part way through the text?
To be consistent, this patch should remove the references to and as irrelevant.
Yes, after considerable discussion those of working on this stuff decided that the goal should be that the parser be able to complete parsing, without error, anything the typical browsers can parse (which means, pretty much anything, though that says nothing about whether the result of the parse is useful in any way). In other words, we've been treating it as a bug when the parser throws an error, since one generally uses the library to parse web pages from the internet and having the parse fail leaves you SOL for doing anything useful with the bad pages one gets therefrom. (Note that if the parser was doing strict adherence to the older RFCs our decision would have been different...but it is not. It has always accepted *some* badly formed documents, and rejected others.)
Also note that BeautifulSoup in Python2 used the sgml parser, which didn't throw errors, but that is gone in Python3. In Python3 BeautifulSoup uses the html parser...which is what started us down this road to begin with.
I apologize for misplaced sarcasm. After more careful reading of the source code, I found out that the patch really meets the specifications and the behavior of all tested me browsers. Despite its awkward appearance, the patch fixes a flaw of the original code for this corner case. But it allows the passage of an invalid code in strict mode. I think, this problem can be solved by a more direct way, perhaps even simplifying the original code.
Attached a new patch with a few more tests and a simplification of the attrfind regex.
> But it allows the passage of an invalid code in strict mode.
HTMLParser is following the HTML5 specs, and doesn't do validation, so there's no strict mode (and the strict mode of Python 3 will be removed/deprecated soon).
> I think, this problem can be solved by a more direct way,
> perhaps even simplifying the original code.
This might be true, but I'm quite happy with this patch for now. Maybe one day I'll rewrite it.
> Unless there is a specification somewhere (or at least an editor's
> draft), I can't really see any particular parse as a bugfix.
If HTMLParser doesn't parse as the HTML5 specs say, then it's considered a bug.
On Thu, Apr 12, 2012 at 7:26 PM, Ezio Melotti wrote:
> If HTMLParser doesn't parse as the HTML5 specs say,
> then it's considered a bug.
I had thought that was the goal of the html5lib, and that HTMLParser
was explicitly aiming at a much reduced model in order to remain
simple. (And also because the HTML5 spec is still changing fairly
often, particularly compared to the lifecycle of a feature release of
python.)
HTMLParser is still simpler than html5lib, but if/when possible we are following the HTML5 standard rather than taking arbitrary decisions (like we used to do before HTML5). HTMLParser doesn't claim to be a fully compliant HTML5 parser (and probably never will) -- its goal is rather being able to parse real world HTML in the same way browsers do. There are also a couple of corner cases that are not implemented in HTMLParser because it would make the code too complicated for a little gain.
It sounds like this is a case where the docs should mention an external library; perhaps something like changing the intro of from:
"""
19.2. html.parser — Simple HTML and XHTML parser
Source code: Lib/html/parser.py
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
"""
to:
"""
19.2. html.parser — Simple HTML and XHTML parser
Source code: Lib/html/parser.py
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Note that mainstream web browsers also attempt to repair invalid markup; the algorithms for this can be quite complex, and are evolving too quickly for the Python release cycle. Applications handling arbitrary web pages should consider using 3rd-party modules. The python version of html5lib ( ) is being developed in parallel with the HTML standard itself, and serves as a reference implementation.
"""
Sure, the docs should explain better that html.parser tries its best to parse stuff, is not a validating parser, and is actively developed, contrary to the popular belief that standard library modules never get improved. I’m less sure about links, there is more than one popular library (html5lib, lxml, BeautifulSoup). Another bug needs to be opened, we’re off-topic for this one — but thanks for the remark and proposed patch.
New changeset 36c901fcfcda by Ezio Melotti in branch '2.7':
#14538: HTMLParser can now parse correctly start tags that contain a bare /.
New changeset ba4baaddac8d by Ezio Melotti in branch '3.2':
#14538: HTMLParser can now parse correctly start tags that contain a bare /.
New changeset 0f837071fd97 by Ezio Melotti in branch 'default':
#14538: merge with 3.2.
This is now fixed, thanks for the report!
Regarding the documentation feel free to open another issue, but at some point I'll probably update it anyway and/or write down somewhere what the future plans for HTMLParser and its goals.
Thanks guys for your comments and for solving this issue. Great work! | http://bugs.python.org/issue14538 | CC-MAIN-2016-26 | refinedweb | 1,240 | 71.85 |
I am new to C++. I have CodeWarrior, if that makes a difference. I can get this project to compile and receive input. But when it is suppose to output the weekday at the end of "entered is:", I only get "." What am I doing wrong? I have done the formulas manually, they all seem to work. Any help will be greatly appreciated.
//Project 4 - receives the number of a month, the day
//of a month, and a year, and returns the name of the
//day of the week on which that date fell or will fall
#include <iostream> // cin, cout
#include <iomanip> // math library
#include <string> // string library
using namespace std; // introduces namespace std
string DayoftheWeek(string, int, int, int, int, int, int, int, int, int, int, int, int);
//prototype
int main(void)
{
int mon, day, year;
char YorN;
string WeekDay;
do
{
cout << "Enter the number of the month:";
cin >> mon; //month of year
cout << "Enter day of the month:";
cin >> day; //day of month
cout << "Enter the year:";
cin >> year; //year number
cout << "The day of the week for the date you have entered is: ";
string DayoftheWeek(WeekDay); //function call
cout << WeekDay;
cout << ".\n";
cout << "\n\n\nEnter Y to try another, N to stop.\n\t\t";
cin >> YorN;
}
while(YorN=='Y'||YorN=='y');
return 0;
}
string DayoftheWeek(string WeekDay, int mon, int a, int b, int c, int d, int w, int x, int y, int z, int r, int day, int year)
//definition of function to find day of week
{
a = mon;
b = day;
c = year % 100;
d = year / 100;
if(a <= 2)
{
a += 10;
}
else
{
a -= 2;
}
{
w = (13 * a - 1) / a;
x = c / 4;
y = d / 4;
z = w + x + y + b + c - 2 * d;
r = z % 7;
}
switch(r)//for remainder
{
case 0: WeekDay = "Sunday";
case 1: WeekDay = "Monday";
case 2: WeekDay = "Tuesday";
case 3: WeekDay = "Wednesday";
case 4: WeekDay = "Thursday";
case 5: WeekDay = "Friday";
default: WeekDay = "Saturday";
}return WeekDay;
} | https://cboard.cprogramming.com/cplusplus-programming/6356-what-am-i-doing-wrong.html | CC-MAIN-2017-47 | refinedweb | 328 | 65.19 |
Unanswered: Dynamic Themes For GXT 3
Unanswered: Dynamic Themes For GXT 3
Hi everyone,
I need help for controlling theme in GXT 3. When I still use GXT 2, I can write one application, and then deploy the application with different theme, Let say the first application using default theme (blue), and the other deployed using custom theme (ie. red), all thanks to the css theme. Now in GXT 3, I read that the theme must be done in compile time, and what I understand from that point is I have to compile and build twice for creating a different war package with different theme. Is there any way that I can still achive this dynamic theme in GXT?
Oh and also, I look at the GXT 3 explorer demo, it has no theme combobox at top right of the view, something that is missing when I take a look at GXT 2 explorer demo.
Please kindly advice me.
Thanks & Regards,
the.wizard
Hello.. no one can help me? At least can someone show me where to start digging this dynamic themes things?
Please kindly help me.
Thanks.
- Join Date
- Feb 2009
- Location
- Minnesota
- 2,734
- Vote Rating
- 90
- Answers
- 109
The combo box in GXT 2 reloads the app, and uses a new css file when it comes back up - in the same way, both and are the same except for those themeing details. We didn't add a combo box to switch between them, but could for a future version of the explorer.
To make the gray explorer module, this is all we did:
Code:
<module rename- <inherits name='com.sencha.gxt.explorer.Explorer'/> <inherits name='com.sencha.gxt.theme.gray.Gray'/> <replace-with <when-type-is </replace-with> </module>
Thanks for answering my question.. Now from your explanation, what I understand is, I still have to change the gwt.xml file everytime I need to change the theme, am I right? What I want is, I compile the application once (ie. I set it to gray theme), and then compile it to a .war file to deploy to web server (ie. tomcat). Then I just need to modify the gray css file in my web server to change the theme to any custom theme I want. In GXT 2 this is a simple task to do, but in GXT 3 I don't sure about it. So please help me, how to achieve this goal? Thanks.
I have the same questions but no answers, sorry to say.
I have the same questions but no answers, sorry to say.
I need to be able to dynamically change the background color of a widget to yellow, for an alert, and switch it back to normal after n seconds. I also need to allow the user to select different colors (aka themes) but I do not know ahead of time what colors would be selected. I expected to be able to offer perhaps 4-6 background colors for each window in a desktop application. And user wants to have nighttime vs daytime settings. I could easily see how to do this earlier, via css. I have no idea how to do it now without a tremendous amount of coding. How is this an improvement over gxt 2?
Need quick advice please
- Join Date
- Feb 2009
- Location
- Minnesota
- 2,734
- Vote Rating
- 90
- Answers
- 109
kym - you can still do all of this via CSS - have you tried it? Create a css file, either with or without CssResource, and change the css class name on the widget each time the color needs to change. This is how you had to do it in GXT 2, this is how you do it with GXT 3.
Or, just change the backgroundColor property of the style object.
How did you do this in 2? Can you show how you tried to do the same thing in 3?
The theming point is totally different - to change a theme in 2.x, you would load another css file into the page, which would cause it to re-render each dom element, but would not necessarily re-layout the app, which could cause issues. GXT 2 didn't really 'support' changing the theme on the fly, it just happened to work. The GXT 2 process to change themes was expensive for the browser to change, the 3 process takes more compile time but is easier for the browser.
In general, this is a big theme of GXT 3 - to better follow the general GWT directive of using the compiler to produce code that is built for the browser. It does require an extra file to declare 'this app, but with that theme', and it does require an extra compile, but once this is done, you have finished, optimized apps that only run the code that is needed to get the app going with that theme.
With bug fixes present in GWT 2.5 an 2.5.1, there is another option available - if you set the configuration property "CssResource.style" to "stable-shorttype" or "stable", you will get consistent (and unoptimized!) css class names, so that you can build your own external css files using those classes, and load them on the fly as you see fit. As with GXT 2, as long as those only change colors after the app is loaded, you should be fine, but if sizing or paddings are changed, layouts may need to be performed, which you'll need to kick off manually.
Dynamic changing of color and/or font
Dynamic changing of color and/or font
I have a .css that specifies color and font for a text area. One setting is Green, the other is White. When I get new data, I tried doing ta.setStyleName("newData") with the newData in my css file looking like:
.newData{
background-color: Green;
font-size: 16px;
}
Is this what you meant?
This did not have any effect. The .css is being used and referenced in the program's html. I have also
tried to set the window backgrounds to different colors. This has an impact only when using the gray
theme.
Secondly, I had put the theme in my program's gwt.xml file to the blue theme and then replaced it
with gray. This is in the xml file that is in src above the directory containing my code. I found that I
got only the title bars in my new windows to automatically be created with the color specified in
that .css. When I use "<inherits name='com.sencha.gxt.theme.gray.Gray'/>" in this file, the textarea
settings do nothing, still, but my window's title bar obtains the color in the .css. I tried using the
theme.base.Base and theme.blue.Blue, but they do nothing different from each other. They have the
blue look and nocolors on title bar that I get when using Gray theme.
I don't think it is safe to count on the gray theme because it is likely a bug in the sencha theme code
that has my colors work for the title bar. Also, it does not fully do what I want, anyway.
So how can I just simply set the color and font?
I have only been able to have it work in google toolkit. I had not done it in gxt 2, but I interpreted the
docs on gxt 3 to imply that this was my problem with setting colors - the change to use themes. But if
you think this is something easy to do, I would much appreciate some further information about
which files need to be changed, or perhaps the order of them being loaded by the browser makes a
difference (how does one change that?). I will go back to a simpler example and see what happens
when I do that.
Help would be appreciated as we are planning to purchase license but are holding off until I get these
requirements handled.
Best,
Kym
- Join Date
- Feb 2009
- Location
- Minnesota
- 2,734
- Vote Rating
- 90
- Answers
- 109
I can't say that I would expect this to work in 3.x, mostly because I can't even get it to work in 2.x. Here is what I tried:
Add your style to a css file:
Code:
/*style.css*/ .newData{ background-color: Green; font-size: 16px; }
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <html> <head> <title>Test App</title> <link rel="stylesheet" type="text/css" href="gxt/resources/css/gxt-all.css" /> <link rel="stylesheet" type="text/css" href="style.css" /> <script language='javascript' src='test/test.nocache.js'></script> </head> <body> </body> </html>
Code:
public class Test implements EntryPoint { public void onModuleLoad() { TextArea textarea = new TextArea(); textarea.addStyleName("newData"); RootPanel.get().add(textarea); } }
As near as I can tell, you aren't struggling with GXT 3 styling, you are struggling with CSS itself. The css rule doesn't really make sense, no matter which GXT version it is applied to, or how themes are achieved in it. The rule, as written, is trying to style the element the class is set on, while it *should* be styling the textarea element itself. Here is one way this could be achieved (works in both GXT 2 and 3):
Code:
.newData textarea{ background-color: Green; font-size: 16px; }
This isn't a question of GXT 3 not 'improving' over GXT 2. The improvement comes in the form of a) making it easier to maintain complex changes to the appearance of a widget, and b) the compiled output of your application, including those styles which your app requires. While (as described in my last post) it is not required to follow this appearance pattern, it *is* unfortunately necessary to understand CSS in order to write it. I don't say this to be rude, but to point out that there is more going on here than your simplified problem seems to tell.
Your issue with Window is almost certainly related, though without seeing the CSS, I can't say for sure. In order to build the Window so that it has rounded corners and the edge effects used in our default themes but still make it work cross-browser, many elements need to be added to the dom, each with particular styles. In this case (I haven't tested, this post is giant already), I believe you need to style the element accessible via the getBody() method to get the central region of the window. Your situation may be different, I'd need to see what you've tried and how your widgets (i.e. your html structure) is set up to be more specific.
I hope this helps in explaining that this isn't complexity for the sake of complexity, but the fact that CSS isn't quite so straightforward, and that supporting such a variety of browsers requires some knowledge of those browsers when you delve deeper than just assembling widgets.
Dynamic changing of color
Dynamic changing of color
Thanks so much for clarification about .css. I also have mine working with the change you suggested. My apologies for that, I do not know css that well, so the definition of the element is not clear to me.
Now, regarding the window title bars getting colors as per the .css, that is interesting because I am only
specifying the style name in the css (as I was doing for the textarea).
So I have:
.window1{
background-color: Green;
}
.window2{
background-color: Yellow;
}
...
...
With setting of style done this way:
appWindow = new Window();
...
...
appWindow.setStyleName("window1");
or
appWindow.setStyleName("window2");
etc.
This "worked" only under the gray theme and was ignored with anything else. And, even if I changed
the css to conform to the change done for textarea, nothing changed the title bar color outside of the above setting. In the css I tried both:
.appWindow window1 {
background-color: Green;
}
or
.window window1 {
....
....
Only the first made the change. Don't know why.
But thaniks for your help,
Kym
Setting dynamic styles
Setting dynamic styles
I am still pondering the issue of the classname in .css and why I needed to include the textarea into it. I thought you could define any name you want (that is valid) as the classname and just do a setStyleName() to it. Where are the rules defined for this?
-Kym | http://www.sencha.com/forum/showthread.php?258562-Dynamic-Themes-For-GXT-3&p=950113&viewfull=1 | CC-MAIN-2014-52 | refinedweb | 2,072 | 72.05 |
im trying to make a program that sends a text message to my phone whenever i get an im on through my Aol screen name..
currently aol doesnt support "virgin mobile" phone numbers... which is what i have...
but i figure i can still send it through SMTP, i can get it to work if i send the text messages through yahoo ..I.E.
0001112222@vmobl.com
that works,
so im trying to use python to send the emails when i get an im ( i have all of the aim stuff figured out already)
the problem comes when i try to use pythons smtplib module
i dont have much knowledge in this area.. but this is what happens
apparently my sbc dsl modem blocks port 25, which i use to send out the emails in STMP, so i set it up so that it uses the sbc mail server 'mail.pacbell.net'
my test script is this..
import smtplib
toaddrs = "myphone@vmobl.com"
fromaddr = "someaddress@wherever.com"
msg="This is the message"
server = smtplib.SMTP('mail.pacbell.net')
failed = server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print "done"
and it prints...
Traceback (most recent call last):
File "E:/Programs/Python 2.3.4/cellphone.py", line 8, in -toplevel-
failed = server.sendmail(fromaddr, toaddrs, msg)
File "E:\Programs\Python 2.3.4\lib\smtplib.py", line 676, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (550, '5.0.0 Access denied', 'someaddress@wherever.com')
i dont know why its saying "acces denied"
ive tried several of my emails, and none of them seem to work
can anyone tell me how to work aroudn this?
thanks for any help, and sorry for the lengthy post | http://forums.devshed.com/python-programming-11/smtp-access-denied-issue-174985.html | CC-MAIN-2014-35 | refinedweb | 284 | 75.81 |
How can I create a nested hashmap given a list of values?
List(1,2,3,4).toMap => Map(1 -> Map(2 -> Map(3 -> 4)))
List(1,2,3,4).toMap => Map(1 -> Map(2 -> Map(3 -> 4)))
List(1,2,3,5).toMap => Map(1 -> Map(2 -> Map(3 -> 5)))
Map(1 -> Map(2 -> Map(3 -> List(4,5)))
List(List(1,2,3,8), List(2,3,7,9)).groupBy(x => x(0)).
groupBy(x => x(1)).
groupBy(x=>x(2))
...
...
.groupBy(x=>x(n))
We can achieve something close to your 1st request without too much difficulty.
scala> List(1,2,3,4).foldRight(Map[Int,Map[Int,_]]()){case (a,b) => Map(a->b)} res0: scala.collection.immutable.Map[Int,scala.collection.immutable.Map[Int, _]] = Map(1 -> Map(2 -> Map(3 -> Map(4 -> Map()))))
But I don't think there's enough information to fully comprehend your 2nd request. For example: How would the following lists be merged?
List(1,2,3,8) List(2,3,7,9)
UPDATE
From your comments it sounds like maybe the best approach might be to merge the lists before the nesting. This could be done a number of different ways, depending on your requirements.
For example: If order is important (and it looks like it is) can the list be easily sorted? If your using
Int then that's trivial.
def nest[A](input: List[A]): Map[A, Map[A,_]] = input.foldRight(Map[A,Map[A,_]]()){case (a,b) => Map(a->b)} val lst1 = List(1,2,3,8) val lst2 = List(2,3,7,9) nest( (lst1 ++ lst2).distinct.sorted ) //result: Map(1 -> Map(2 -> Map(3 -> Map(7 -> Map(8 -> Map(9 -> Map()))))))
But I suspect that these simple minded examples might be drifting away from your real-world use cases. | https://codedump.io/share/jjPDQg13bvh/1/in-scala-create-a-nested-hashmap-of-length-n-given-a-list-of-length-n | CC-MAIN-2017-26 | refinedweb | 307 | 67.25 |
orayi Spencer Guzha6,044 Points
The class Player with __init__ , my Task 1 is no longer passing for almost 72 hours and also the Task for closing a file
What could be wrong I have tried several times and Task 1 is said to be no longer passing why?
import re string = '''Love, Kenneth: 20 Chalkley, Andrew: 25 McFarland, Dave: 10 Kesten, Joy: 22 Stewart Pinchback, Pinckney Benton: 18''' players = re.match(r''' (?P<last_name>[\w ]*) ,\s (?P<first_name>[\w ]*) :\s (?P<score>[\d]*)''' , string, re.X|re.M) class Player: def __init__(self, last_name, first_name, score): self.last_name = last_name self.first_name = first_name self.score = score
1 Answer
Chris FreemanTreehouse Moderator 67,986 Points
Sorry, I could not find anything wrong with your code. It passes the challenge as is. Sometimes "Task 1 is no longer passing" is the result of a syntax error introduce, or mixing of a TAB instead of spaces while indenting.
Post back if you need more help. Good luck!!
Shorayi Spencer Guzha6,044 Points
Shorayi Spencer Guzha6,044 Points
Ok thanks | https://teamtreehouse.com/community/the-class-player-with-init-my-task-1-is-no-longer-passing-for-almost-72-hours-and-also-the-task-for-closing-a-file | CC-MAIN-2022-27 | refinedweb | 176 | 73.88 |
When Yarn was first released, it was a huge step forward for the JavaScript and NPM community. At the time, NPM did not support deterministic sub-dependency resolution. And Yarn was considerably faster, primarily due to the introduction of an offline cache.
These days, however, the gap between Yarn and NPM is much closer. NPM 5 introduced a package-lock, which allows for deterministic dependency installation. Additionally, recent versions of NPM now cache installed dependencies, which speeds up installation but still lags behind Yarn (in my non-scientific testing).
Yet, even with improvements to NPM, Yarn still provides compelling reasons to choose it. Here are three Yarn features I’ve found extremely useful over the past few years.
1. Pinned Version Resolutions
Have you ever used a library, discovered an issue with it, and determined that the problem was with one of their dependencies? One of the most frustrating things to happen in that situation is discovering that the sub-dependency had released a fix in newer versions. Even more frustrating than that, though, is if your dependency is no longer maintained or not frequently updated.
Enter Yarn dependency resolution. In your package.json, add a property “resolutions.” Yarn will resolve the versions listed in this field. This looks like:
{ .... "resolutions": { "mini-css-extract-plugin": "^0.9.0", "less-loader": "^5.0.0" } }
In your Yarn .lock, this would look like:
less-loader@4.1.0, less-loader@^5.0.0: version "5.0.0" resolved "" integrity sha512-bquCU89mO/yWLaUq0Clk7qCsKhsF/TZpJUzETRvJa9KSVEL9SO3ovCvdEHISBhrC81OwC8QSVX7E0bzElZj9cg== dependencies: clone "^2.1.1" loader-utils "^1.1.0" pify "^4.0.1"
Notice how less-loader@4.1.0 and less-loader@^5.0.0 resolve to 5.0.0. Typically, Yarn will resolve major versions separately. However, with the version resolution set to ^5.0.0, it resolves all versions of less-loader to that.
This is a good way to ensure that all dependencies are using the same version of a specific package. However, this could lead to unintended behaviors, so use this sparingly.
2. Autoclean
Autoclean lets you automatically remove any dependencies in the
.yarnclean file after installing or adding dependencies. In the Yarn docs, they recommend it for pruning unnecessary files that take up extra space, such as docs, tests, examples, assets, etc. These files aren’t necessary to run the modules, and it can help reduce the node_modules size.
One of the benefits that I’ve found with autoclean is that dependencies can be removed completely. This certainly isn’t a common case, but there have been a few times where I’ve found that the cleanest solution is to remove dependencies altogether.
For example, in the past, I’ve used libraries that have dependencies on both React and React Native. This leads to some incorrect imports, namespace collision, and occasional bugs. The easiest thing to do in that case is to add rules in the
.yarnclean file to simply remove the bad dependencies. If I’m working on a web application, I don’t want React Native modules in my application dependencies, especially not my compiled code.
3. Yarn 2 – aka “Berry”
Yarn 2 has been announced and is under active development. This is a major overhaul, and it will provide many new features in addition to various bug fixes. In the Yarn roadmap, it was stated that the intention is to shift Yarn from a Node-specific CLI package manager to a platform and API for multiple languages. Yarn 2 is available now for usage in Node projects.
I’m personally very excited about the workspaces for full-stack projects and the portable shell for cross-platform Windows/Mac developers.
Yarn v2 provides the most compelling reason to continue using Yarn in 2020. Yarn reshaped the Node ecosystem in 2016, and I believe they can do it again in 2020. | https://spin.atomicobject.com/2020/03/15/why-yarn-2020/ | CC-MAIN-2020-34 | refinedweb | 640 | 59.7 |
On Wed, Jul 14, 2010 at 12:04 AM,On 14 July 2010 14:43, Ian Bicking <<a href="mailto:ianb@colorstudy.com">ianb@colorstudy.com</a>> wrote:<br> > So... there's been some discussion of WSGI on Python 3 lately. I'm not<br> > feeling as pessimistic as some people, I feel like we were close but just<br> > didn't *quite* get there.<br> <br> </div>What I took from the discussion wasn't that one couldn't specify a<br> WSGI interface, and as you say we more or less have one now, the issue<br> is more about how practical that is from a usability perspective for<br> those who have to code stuff on top.<br></blockquote><div><br>My intuition is that won't be that bad. At least compared to any library that is dealing with str/unicode porting issues; which aren't easy, but so it goes.<br> <br></div><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;"><div class="im"><br> > * I'm terrible at naming, but let's say these new values are RAW_SCRIPT_NAME<br> > and RAW_PATH_INFO.<br> <br> </div>My prior suggestion on that since upper case keys for now effectively<br> derive from CGI, was to make them wsgi.script_name and wsgi.path_info.<br> Ie., push them into the wsgi namespace.<br></blockquote><div><br>That's fine with me too.<br> </div><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;"> <div class="im"> > Does this solve everything? There's broken stuff in the stdlib, but we<br> > shouldn't bother ourselves with that -- if we need working code we should<br> > just write it and ignore the stdlib or submit our stuff as patches to the<br> > stdlib.<br> <br> </div>The quick summary of what I suggest before is at:<br> <br> <a href="" target="_blank"></a><br> <br> I believe the only difference I see is the raw SCRIPT_NAME and<br> PATH_INFO, which got discussed to death previously with no consensus.<br></blockquote><div><br>Thanks, I was looking for that. I remember the primary objection to a SCRIPT_NAME/PATH_INFO change was from you. Do you still feel that way?<br> <br>I generally agree with your interpretation, except I would want to strictly disallow unicode (Python 3 str) from response bodies. Latin1/ISO-8859-1 is an okay encoding for headers and status and raw SCRIPT_NAME/PATH_INFO, but for bodies it doesn't have any particular validity.<br> <br>I forgot to mention the response, which you cover; I guess I'm okay with being lenient on types there (allowing both bytes and str in Python 3)... though I'm not really that happy with it. I'd rather just keep it symmetric with the request, requiring native strings everywhere.<br> </div></div><br>-- <br>Ian Bicking | <a href=""></a><br> | https://mail.python.org/pipermail/web-sig/attachments/20100714/5b88d1e8/attachment-0001.html | CC-MAIN-2018-05 | refinedweb | 503 | 55.95 |
App::Framework::Core - Base application object
use App::Framework::Core ; our @ISA = qw(App::Framework::Core) ;
The details of this module are only of interest to personality/extension/feature developers.
Base class for applications. Expected to be derived from by an implementable class (like App::Framework::Core::Script).') * feature_config = HASH ref containing setup information for any installed features. Each feature must have it's own HASH of values, keyed by the feature name * App::Framework::Core.
The %args are specified as they would be in the set method, for example:
'mmap_handler' => $mmap_handler
The full list of possible arguments are :
'fields' => Either ARRAY list of valid field names, or HASH of field names with default values
Initialises the App::Framework::Core object class variables.
Class instance object is not allowed
Attempt to load the module into the specified package $pkg (or load it into a temporary space).
Then checks that the load was ok by checking the module's version number.
Returns 1 on success; 0 on failure.
Load the module into the caller's namespace then set it's @ISA ready for that module to call it's parent's new() method
Initialises the object class variables.
Looks for the named module in the @INC path. If found, checks the package name inside the file to ensure that it really matches the capitalisation.
(Mainly for Microsoft Windows use!)
Looks for any perl modules contained under the module path. Looks at all possible locations in the @INC path, returning the first found.
Returns a HASH contains the module name as key and the full filename path as the value.
Starting at package, return a HASH ref in the form of a tree of it's parents. They keys are the parent module names, and the values are HASH refs of their parents and so on. Value is undef when last parent is reached.
Get the full path to this application (follows links where required)
Function that gets called on errors. $error is as defined in App::Framework::Base::Object::ErrorHandle
Add the listed features to the application. List is an ARRAY ref list of feature names.
Note: names need correct capitalisation (e.g. Sql not sql) - or just use first char capitalised(?)
Method/feature name will be all lowercase
Optionally, can specify $feature_args HASH ref. Each feature name in $feature_list should be a key in the HASH, the value of which is an arguments string (which is a list of feature arguments separated by space and/or commas)
Return named feature object if the feature is installed; otherwise returns undef.
Return named feature object. Alternative interface to just calling the feature's 'get/set' method.
For example, 'sql' feature can be accessed either as:
my $sql = $app->feature("sql") ;
or:
my $sql = $app->sql() ;
API for feature objects. Used so that they can register their methods to be called at the start and end of the registered functions.
Function list is a list of strings where the string is in the format:
<method name>_entry <method_name>_exit
To register a call at the start of the method and/or at the end of the method.
This is usually called when the feature is being created (which is usually because this Core object is installing the feature). To ensure the core's lists are up to date, this function sets the feature object and priority. * (Application registered 'app_start' function)
Execute the application.
Calls the following methods in turn:
* (Application registered 'app' function)
Tidy up after the application.
Calls the following methods in turn:
* (Application registered 'app_end' function)
Exit the application.
Show usage
Utility method
Parses the filename and returns the full path, basename, and extension.
Effectively does:
$fname = File::Spec->rel2abs($fname) ; ($path, $base, $ext) = fileparse($fname, '\.[^\.]+') ; return ($path, $base, $ext) ;
Print out the items in the $items_aref ARRAY ref iff the application's debug level is >0. If $min_debug is specified, will only print out items if the application's debug level is >= $min_debug.
Setting the debug flag to level 1 prints out (to STDOUT) some debug messages, setting it to level 2 prints out more verbose messages.
Steve Price
<sdprice at cpan.org>
None that I know of! | http://search.cpan.org/dist/App-Framework/lib/App/Framework/Core.pm | CC-MAIN-2018-22 | refinedweb | 698 | 64.51 |
Forums MaxMSP
Hi all,
Maybe a bit of a newbie question.
Im trying to build a network monitor in max that triggers notes when packets are sent and received and also depending on the amount of packets control tempo. What would be the best way to do this? Can I do it with the mxj send/recieve?
Thanks in advance for any help
OSC is a nice way to go for control of things remotely ’cause you can
create namespaces for the messages and route them accordingly without
having to devise your own parsing scheme. There are some max objects
for doing this: udpreceive, udpsend.
wes
Thanks!
Will this allow me to intercept the packets without affecting other programs?
Ideally id like the patch to work in the background while I access websites and transfer data.
Oh, are you trying to sniff packets?? that’s a different story. Maybe
you could download Carnivore and do an mxj with that code.
I think the program you’re describing is called a “packet sniffer”, but I
don’t know whether the OSC objects support this. Anyone?
I believe most packet sniffers generate plain text log files, so maybe you
could use Max to access and parse the data in thse files to do what you
want.
Best of luck!
- *V*I*R*G*O*
You need to run your ethernet card in promiscuous mode to capture all
data. This requires using packet capture libraries like libpcap on
unix and windows.
might I suggest using ‘carnivore’ by the RSG – which is ready made to
give you that data :)
v a d e //
abstrakt.vade.info
I
Wow, thanks for all these replies!
I think capturing all the data to file is going to be my best bet, since writing things in java isnt exactly my forte.
Which platform are you workling on? I have a (not well tested) carnivore
external for windows that sniffs all the network traffic and gives it to
you through an outlet….
Olaf
Its for windows :) Ive got carnivore working through a very basic patch, any help is most appreciated
Is it possible to use Carnivore as a MAX lib rather than in Processing?
You must be logged in to reply to this topic.
C74 RSS Feed | © Copyright Cycling '74 | http://cycling74.com/forums/topic/network-monitor/ | CC-MAIN-2014-15 | refinedweb | 381 | 72.66 |
github.com/quarnster/SublimeGDB
this is reaaaal good. Thank you!
a few hopefully queick questions and observations: a. when i start the debugger (f5), right click on the variable -> "add to watches" the sublime hangs ofr a few seconds. I have 3 core AMD and it goes for 4% utilization ( nothing else is running ). b. sorry about this naive question. what is the right sequence for debugging session? Right now i'm doing this: 1. save file. 2. set breakpoint 3. right click on the var to add it to the watch. 3. F5 to start the debugger and F5 to advance to the breakpoint.
but i don't see any indication of the degugger running, nor i see where the current line is ....Obviously i'm doing something wrong.Please advise.
Which OS are you using? The plugin is pretty much untested on Windows and has issues on Linux, making it impossible to add breakpoints or watches while the target is running. Feel free to contribute code fixing it.
As for running status, you'll want to check the callstack view and the threads view. To fix anything that's broken, you'll likely want to keep an eye in the GDB Session view which will print all the commands sent to gdb and all the data that is received from it in raw format.
i'm on RH6 64. The link does not point to the issue i experienced - in my case the sublime is getting frozen for a few seconds while no execution/debugging is happening. It's rather minor @ this point for me.
right - but do i do this right - set breakpoint, hit F5 and hit F5 again to get the program to advance to the breakpoint? becasue i see no changes anywhere. And it's a simple code really:
package main
import ( // "example/newmath" "fmt" "os")
type F_error struct { f_name string}
var ( F_name1 string = "/tmp/abc.txt" F_name2 string)
func main() {
// Open a file.
// Read from the file and print on to the screen
file_1, err := os.Open(F_name1)
if err != nil {
fmt.Println(err)
}
fmt.Println("File name is %v ", &file_1)
// Read from another file and append original
// and replace the original file
fmt.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2))
// os.Open(new_file)
}
Never done anything go releated. Check the GDB session view for info on what it's doing.
ok. it seems it's waiting for "file" ... hmmm another question: one closed (with mouse) all the "little" windows - stack etc. But the area where there were is still open. How can i close it if restart doesn't help ?
If it's waiting for "file" you probably haven't set sublimegdb_commandline properly in the configuration so it doesn't know what executable you are trying to debug.
The layout is restored when the gdb session exits (select stop debugging in the right click menu). If stopping debugging doesn't work, you can also use the layout shortcuts or menu item. Menu item View->Layout->Single for example.
correct you are . I haven't touched anything. now i opened the sublimegdb.sublime-settings and it has this :
// All options in here can also be specified in your project settings
// with a prepended "sublimegdb_". You probably want to
// have something like this in your project settings:
//
// "settings":
// {
// "sublimegdb_sourcedir": "/path/to/your/project/source",
// "sublimegdb_workingdir": "/path/to/your/project",
// // NOTE: You MUST provide --interpreter=mi for the plugin to work
// "sublimegdb_commandline": "gdb --interpreter=mi ./your_executable_name"
* // ]
// }
//
"workingdir": "/tmp",
// NOTE: You MUST provide --interpreter=mi for the plugin to work
"commandline": "gdb --interpreter=mi ./executable",
can i have the executable_name as a dynamic value? for example if i need to review the package it will have a different name from the main exec file.i added "*" in one of the lines above. I believe there should be a "}" not a "]".
how do i find out where the gdb gets executed? it seemed to unable to locate my file... -- aha! i must have the sublimegdb_workingdi set.
perfect - that worked like a charm. thank you !
now , once i added the sction above to the project file the gdb seemed to pick up on the file. At least i see some meaningful information.here is what i noticed tho in gdb session window:
/usr/local/go/src/pkg/runtime/runtime-gdb.py (referenced in .debug_gdb_scripts): No such file or directory\n"
(gdb)
(gdb)
33^error,msg="Undefined show command: \"interpreter\". Try \"help show\"."
(gdb)
i can't locate the .debug_gdb_scripts file. where is it and is it important? --- this is something GO specific. I'm looking into this. please ignore.update: there is a
do i need to care about the "interpreter" error ?
i replaced the code above with the simple loop:
for i := 0; i < 10; i++ {
println(i)
}
put the breakpoint @ println linenow in gdb console i see the println (i'm assuming) printing the sequence of 0123... but how can i see the actual value in variable?the gdb variables window is empty.the gdb breakpoints has this :
-1 - watch: F_name1
-1 - watch: file_1
-1 - watch: i
1 - /home/azz/work/workspace/src/az/main.go:35
and in the gdb Session ( once i add the i thru the gdb drop down manu "Add watch":
225-break-watch i
225^error,msg="No symbol \"i\" in current context."
(gdb)
[quote="dbabo"]....now , once i added the section above to the project file the gdb seemed to pick up on the file. At least i see some meaningful information.here is what i noticed tho in gdb session window:
[/quote]
I think the error "no symbol" is specific to GO. According to this manual GO vars are "package.var" (golang.org/doc/gdb).This guy seemed to got GDB to play nicer %) with his IDE (code.google.com/p/liteide/) at least i can see all variables in the "variable" window during debugging.
I really wish i'm missing something obvious since over 2 days i've been playing with your extension and Sublime i found myself enjoying it much better then other implementations.
I.
Awesome! Let me try right now...
BTW. I saw in your comments that you were not able to figure out how to set a new breakpoint while debugging. The author of LiteIde got it to work - i just tested it. So you may want to contact him.
good news indeed!i could see "i" now.now i made a change to the code - in the loop i print the const ( F_name1). But i can't see it in the variables window.
Also - how can i remove the var from the watch window?
func main() {
file_1, err := os.Open(F_name1)
if err != nil {
fmt.Println(err)
}
for i := 0; i < 10; i++ {
println(i)
println(F_name1)
}
}
Remove by pressing F9 with the cursor on the line in the breakpoint/watch window.
cool. how about the F_name1 problem?
Like I said earlier:
If it's not listed, it wasn't possible to create a gdb variable for it. Feel free to submit a pull request when you figure out what needs to be changed.
i don't know why but i can't fish the value of constant from gdb.quamster - thank you for the earlier fix. Life is good now | https://forum.sublimetext.com/t/debuging/6075 | CC-MAIN-2017-22 | refinedweb | 1,219 | 76.42 |
Java, J2EE & SOA Certification Training
- 35k Enrolled Learners
- Weekend
- Live Class
In Java, we come across situations where we need to use objects instead of primitive data types. To accomplish this, Java provides wrapper class Character for primitive data type char. In this article on Char in Java, let us understand the same in detail.
The following topics will be covered in this article:
Let’s begin!
The Character class generally wraps the value of all the primitive type char into an object. Any object of the type character may contain a single field whose type is char. The Character class offers a number of useful classes (i.e., static) methods for working with characters.
To create a character object with the character constructor −
Character ch = new Character('a');
The above statement creates a character object which contains ‘a’ of type char. There is only one constructor in character class which expects an argument of the char data type.
Next in this article on Char in Java, let us see few escape sequences used with the characters in Java.
A character preceded by a backslash () is generally called an escape sequence. There is a table mentioned below that will help you in understanding this concept.
Since you have understood the escape sequences, let us move ahead and understand the methods that character class offers in Java.
The following table discusses a few important methods of the character class.
Next, in this article on Char in Java, let us see the practical implementation of the above-discussed methods.
import java.util.Scanner; public class JavaCharacterExample1 { public static void main(String[] args) { // Ask the user for the first input. System.out.print("First input:"); // Use the Scanner class to get the user input. Scanner scanner = new Scanner(System.in); // Gets the user input. char[] value1 = scanner.nextLine().toCharArray(); int result1 = 0; // Count the characters for a specific character. for (char ch1 : value1) { result1 = Character.charCount(ch1); } // Print the result. System.out.print("Value: "+result1+"n"); System.out.print("Second input:"); char[] value2 = scanner.nextLine().toCharArray(); for (char ch2 : value2) { int result2 = Character.hashCode(ch2); System.out.print("The hash code for the character '"+ch2+"' is given as:"+result2+"n"); } System.out.print("Third input:"); char[] value3 = scanner.nextLine().toCharArray(); for (char ch3 : value3) { boolean result3 = Character.isDigit(ch3); if(result3){ System.out.println("The character '" + ch3 + "' is a digit. "); } else{ System.out.println("The character '" + ch3 + "' is not a digit."); } System.out.print("Fourth input:"); char[] value4 = scanner.nextLine().toCharArray(); for (char ch4 : value4) { boolean result4 = Character.isISOControl(ch4); System.out.println("The fourth character '"+ch4+"' is an ISO Control:"+result4); } } } }
First input:89 Value: 1 Second input:J The hash code for the character 'J' is given as:74 Third input:5 The character '5' is a digit. Fourth input:h The fourth character 'h' is an ISO Control:false
With this, we come to an end to this article on Char in Java. I hope you understood the fundamentals of Java. If you found this article on “Char in Java”, “Char in Java” and we will get back to you as soon as possible. | https://www.edureka.co/blog/character-class-java | CC-MAIN-2020-05 | refinedweb | 524 | 51.04 |
<ac:macro ac:<ac:plain-text-body><![CDATA[
<ac:macro ac:<ac:plain-text-body><![CDATA[
The encoder is a simple and full configurable filter to encode characters to its entities.
Zend Framework: Zend_Filter_CharacterEntityEncode & Zend_Filter_CharacterEntityDecode Component Proposal
Table of Contents
1. Overview
The decoder is the opposite filter to decode entities to its characters.
2. References
<ac:macro ac:<ac:plain-text-body><![CDATA[
The encoder is a simple and full configurable filter to encode characters to its entities.
The encoder is a simple and full configurable filter to encode characters to its entities.
3. Component Requirements, Constraints, and Acceptance Criteria
- This component will provide a complete and good configurable interface to encode and decode texts with entities.
- This component will not replace Zend_Filter_HtmlEntities.
- This component will use iconv to convert character-sets
- This component will not handle special CDATA content (like the content of <script></script>)
4. Dependencies on Other Framework Components
- Zend_Filter
- Zend_Exception
5. Theory of Operation
The encoder converts the complete text from intput character set to UTF-8 and replaces only characters which aren't available by given output character set with a named entity given by user or by numeric or hex entity. After this the text will reconverted to output character set.
The decoder converts all entities (named by user entity reference, numeric and hex) to its equipollent by given character sets. If an entity can't convert to the charset the configured action will be used (exception, translit, ignore, entity, substitute). Furthermore it is configurable if the special chars (&,<,>,",') must keep._Filter_CharacterEntityEncode
- Zend_Filter_CharacterEntityDecode
or
- Zend_Filter_EntityEncode
- Zend_Filter_EntityDecode
8. Use Cases
You get a html formated text from a rich text editor in ISO-8859-1 and need to convert it to UTF-8.
-> This example converts the text to UTF-8 and converts all entities to UTF-8 but special chars ",',<,>,&.
-> You will get a valid html formated string with a minimum of entities.
35 Commentscomments.show.hide
Mar 07, 2010
Christopher Thomas
<p>Looks nice. Great replacement to htmlspecialchars() and htmlentities(). Hope it gets into ZF soon.</p>
Mar 07, 2010
Marc Bennewitz (private)
<p>Thanks for your interest.</p>
<p>It's not a replacement of the html entities filter, it's an addition.<br />
-> htmlentities and friends is more performance than this but this adds some functionalities.</p>
Jun 03, 2010
Stewart Lord
<p>Regarding class naming, how about HtmlEntityDecode instead of CharacterEntityDecode? This would have better parity with the existing Zend_Filter_HtmlEntities.</p>
<p>Are you planning to replace the existing HtmlEntities class? That would be a significant break in backwards compatibility. The alternative of having two html encoding filters seems like it would be too confusing. </p>
<p>Should we drop the encoding class from the proposal?</p>
Jun 03, 2010
Marc Bennewitz (private)
<blockquote>
<p>Regarding class naming, how about HtmlEntityDecode instead of CharacterEntityDecode? This would have better parity with the existing Zend_Filter_HtmlEntities.</p></blockquote>
<p>HTML would be wrong because this is designed to handle xml and html entities. My current implementation is simply EntityEncode & EntityDecode <br class="atl-forced-newline" /></p>
<blockquote>
<p>Are you planning to replace the existing HtmlEntities class? That would be a significant break in backwards compatibility. The alternative of having two html encoding filters seems like it would be too confusing.</p></blockquote>
<p>No, because it's using simply the build in function which is much faster and in most cases you don't need extra functionalities.</p>
Jun 03, 2010
Stewart Lord
<p>I see your point about HtmlEntityDecode being 'wrong' given the support for XML entities. However, since XHTML supports XML entities, I'm not sure the name is entirely incorrect.</p>
<p>It seems to me that having two filters that handle (X)HTML entities is preferable to having three. E.g.</p>
<p> HtmlEntities<br />
HtmlEntityDecode</p>
<p>vs.</p>
<p> HtmlEntities<br />
EntityEncode<br />
EntityDecode</p>
Jun 04, 2010
Marc Bennewitz (private)
<ul>
<li>Filters using only a build-in function should be named as the functions.</li>
<li>EntityEncode will add some functionalities - why you would skip it ?</li>
<li>HtmlEntityDecode could make sense to have a fast decoder simply using html_entity_decode<br />
Than we have 4 filters:
<ul>
<li>HtmlEntities</li>
<li>HtmlEntityDecode</li>
<li>EntityEncode</li>
<li>EntityDecode</li>
</ul>
</li>
</ul>
Jun 05, 2010
Stewart Lord
<p>You wouldn't have to skip the EntityEncode functionality, you could add it to the existing HtmlEntities as additional options. Having four filters works too, just confusing for people, IMO.</p>
Jun 03, 2010
Stewart Lord
<p>I have a few questions regarding some of the inner-workings of the entity decoder:</p>
<p>1. The proposal mentions conversion of numeric and hex entities. Will this be limited to the 252-253 standard entities, or will it support the full range of unicode codepoints?</p>
<p>2. When converting named entities, could we add support for being case-insensitive for entities where the case does not matter (such as &NBSP
?</p>
<p>3. Can you use the html_translation_table() function instead of enumerating the html 4 entities? Or is it insufficient?</p>
<p>4. I think your class constants violate the coding standards (words should be underscore separated). How about INVALID_CHAR_EXCEPTION instead of ONILLEGALCHAR_EXCEPTION?</p>
<p>Cheers,<br />
Stew</p>
Jun 04, 2010
Marc Bennewitz (private)
<p>1. There isn't a limit -> the full range of unicode.<br />
2. Named entities are case sensitive ä <> Ä and something like &AUML; doesn't exist but you can define you own entity!<br />
3. I defined the most needed entity references html4 / xml / special as an static array and you can overwrite these tables.<br />
4. You are right - I couldn't found a good name for it - INVALID_CHAR_* looks a bit nicer <ac:emoticon ac:<br />
(or we define only EXCEPTION, TRANSLIT etc.)</p>
Jun 05, 2010
Stewart Lord
<p>That's great!</p>
<p>We should have an option to make entities case-insensitive when the case doesn't matter. Yes, entities are case-sensitive, but often they are used incorrectly. Webkit and Gecko support this behavior.</p>
<p>If an entity varies by case (e.g. aring vs Aring), then we are case-sensitive for that entity. If the entity does not vary by case (e.g. amp) then we should accept both upper and lower case variations (e.g. AMP).</p>
Jun 30, 2010
Stewart Lord
<p>Hi Marc, any objection to adding this loose-case matching feature to the proposal? It's an important feature for my use case.</p>
Jul 01, 2010
Marc Bennewitz (private)
<blockquote><p>If an entity varies by case (e.g. aring vs Aring), then we are case-sensitive for that entity. If the entity does not vary by case (e.g. amp) then we should accept both upper and lower case variations (e.g. AMP).</p></blockquote>
<p>Because you can define your own entities it's not possible to know that & could be case insensitive.</p>
<p>My idea would be to allow calling a callback for unknown entities like the following:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$decoder->setUnknownEntityCallback(function ($entity) {
// your code to handle unknown entities
});
$decoder->filter('&&InvalidEntity;');
]]></ac:plain-text-body></ac:macro>
<p>-> The callback is called for every unknown entity<br />
-> The return value is the replace of the unknown entity</p>
<p>Than you can define your own actions.</p>
Jul 01, 2010
Stewart Lord
<blockquote><p>Because you can define your own entities it's not possible to know that & could be case insensitive.</p></blockquote>
<p>The way that I have implemented it, the table of entities is examined to determine which entities appear only once and which entities appear more than once with case variations. This approach should be compatible with user-defined entities.</p>
<p>If the user defines a new entity 'foobar' and loose case matching is enabled, we will replace foobar or FOOBAR. If two variations of foobar appear, or if loose case matching is disabled, we will only replace foobar.</p>
<blockquote><p>My idea would be to allow calling a callback for unknown entities like the following<>
<p>I would argue that it should be on by default, but either way I feel strongly that it should be built-in.</p>
Jul 02, 2010
Marc Bennewitz (private)
<blockquote><p>The way that I have implemented it, the table of entities is examined to determine which entities appear only once and which entities appear more than once with case variations. This approach should be compatible with user-defined entities.</p></blockquote>
<p>This sounds slow!<></blockquote>
<p>Sure, but browsers are not libraries <ac:emoticon ac: If we implement such a feature (to detect unknown entities) the user should define his right action he wont.</p>
<p>With such a callback you can implement a case-insensitive behavior very simple:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$map = $decoder->getEntityReference();
$decoder->setUnknownEntityCallback(function ($entity) use ($map) {
$lower = strtolower($entity);
if (isset($map[$lower]))
else
});
]]></ac:plain-text-body></ac:macro>
<blockquote><p>I would argue that it should be on by default, ...</p></blockquote>
<p>NO! It's only an addition.</p>
Jul 02, 2010
Stewart Lord
<blockquote><p>This sounds slow!</p></blockquote>
<p>It really shouldn't be. Especially relative to the expense of performing text translation. Recall, I am talking about examining the table of named entities which only contains around 250 entries. In any case, performance speculation is not a good reason to dismiss this feature.</p>
<blockquote><p>Sure, but browsers are not libraries If we implement such a feature (to detect unknown entities) the user should define his right action he wont.</p></blockquote>
<p>I see your point. The two features are in some conflict which raises the question of what the right thing to do is. If loose-case matching is enabled, we would be effectively saying that the entity is known and therefore we shouldn't call the unknown entity callback for that entity.</p>
<blockquote><p>With such a callback you can implement a case-insensitive behavior very simple:</p></blockquote>
<p>The callback feature is very cool, but this function doesn't quite capture the behavior I am talking about. It is a bit more complicated than this. Recall that we only want to be case-insensitive for entities where the case does not matter. For example, we don't won't tolerate case mismatch for 'aring', but we will for amp, nbsp, etc.</p>
<blockquote><p>NO! It's only an addition.</p></blockquote>
<p>Ok, but you agree that I can add it?</p>
Jul 02, 2010
Marc Bennewitz (private)
<p>do you have some sample code?</p>
Jul 03, 2010
Stewart Lord
<p>Sure, here is how I am doing named entity decoding. You can see that we walk over the entity table and support both upper and lower case variations of entities that appear only once in the table.</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$mapping = array();
$entities = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
$entityCounts = array_count_values(array_map('strtolower', $entities));
foreach ($entities as $character => $entity) {
// translated character should be in requested charset
// using iconv for it's better charset support.
$character = html_entity_decode($entity, ENT_QUOTES, self::UTF8);
$character = iconv(self::UTF8, $this->_charset, $character);
$mapping[$entity] = $character;
// some entities vary by case (e.g. å, Å), if this entity
// has only one entry, support both upper and lower-case variations.
if ($entityCounts[strtolower($entity)] == 1)
}
// do decoding of named entities.
$value = str_replace(array_keys($mapping), array_values($mapping), $value);
]]></ac:plain-text-body></ac:macro>
Jul 04, 2010
Marc Bennewitz (private)
<p>Now I tested the behavior with FF 3.6.6 and IE 8 and I saw that these browsers doesn't implement a fault back! -> Unknown entities are displayed as as the entities.</p>
<p>Therefore I don't no why it should be implemented.<br />
1. not a standard<br />
2. not a quasi standard (behavior of most browsers)</p>
<p>And your behavior it a quite special, too. For example invalid entities like "&NbSp;" will not be detected.</p>
<p>My next point is: You can implement your own behavior using the callback functionality.</p>
<p><ac:link><ri:page ri:</ac:link>: FF 2.6.6 -> FF 3.6.6</p>
Jul 04, 2010
Stewart Lord
<p>We're seeing two different things. I just tested again under FF 3.5.10, Safari 5.0, Chrome 5.0 and IE 8. I used the following markup:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
<html>
<body>
& & &Amp;
</body>
</html>
]]></ac:plain-text-body></ac:macro>
<p>All four browsers demonstrate the same behavior. The first two entities are honored, and the third entity is ignored (displayed as-is). This matches the decoding behavior of my example code. The 'special' behavior you are referring to is actually quite intentional.</p>
<p>This is most definitely a quasi-standard, and we should provide support for it.</p>
Jul 04, 2010
Marc Bennewitz (private)
<p>hehe please use the following test:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
<html>
<body>
&<br />
&<br />
&Amp;<br />
<br />
<br />
&NBSP;<br />
&NbSp;<br />
<br />
¶<br />
&PARA;<br />
&PaRa;<br />
<br />
å<br />
Å<br />
&ARING;<br />
</body>
</html>
]]></ac:plain-text-body></ac:macro>
<p>You will note that only the amp will be detected. This is because often users doesn't escape or escape this entity wrong and this will break links <ac:emoticon ac:</p>
Jul 05, 2010
Stewart Lord
<p>Interesting. Looks like the case-insensitivity only applies to a limited set of entities: copy, reg, quot, lt, gt, and amp. Not sure what the rationale behind that is, but clearly my implementation is incorrect. It would be nice to match this behavior, but I also discovered that browsers will decode entities that have no trailing semi-colon and I don't think it will be practical to match all of these kinds of peculiarities.</p>
Jul 06, 2010
Marc Bennewitz (private)
<p>It sounds like a html auto repair like tidy.</p>
<p>This should be done on an other filter and there is already work on it:
<a class="external-link" href=""></a></p>
<p>This doesn't mean that the behavior of unknown entities should be configurable but an entity auto repair shouldn't part of this filter.</p>
Jun 04, 2010
Thomas Weidner
<p>One thing to note:</p>
<p>There is already a Zend_Filter_Encode and a Zend_Filter_Decode I am working on.<br />
There are several adapters/extensions for them like Base64, Json, Punycode and Url.</p>
<p>Additionally I am actually working on a Zend_Filter_TwoWay (as requested) which enables two-way-filtering.</p>
<p>As your proposal enables encoding as also decoding the following would perfect fit in my eyes:<br />
Zend_Filter_Encode_HtmlEntity (implies Zend_Filter_Decode_HtmlEntity)<br />
Zend_Filter_Encode_Entity (implies Zend_Filter_Decode_Entity)</p>
Jun 04, 2010
Marc Bennewitz (private)
<p>Thanks for the info!</p>
<p>yea, an own namespace for encode/decode filters makes sense.<br />
-> I looked at your code on incubator (hope it's the right place) but there are some parts I don't understand. Do you have proposal for it to discuss about?</p>
Aug 03, 2010
Pádraic Brady
<ac:macro ac:<ac:rich-text-body><p><strong>Community Review Team Recommendation</strong></p>
<p>The ZF CR-Team has postponed a decision on this proposal and requests that the proposer amend their proposal to answer the following questions:</p>
<ul>
<li>What is the purpose and objective of these components?</li>
<li>Why are these components needed for the Zend Framework?</li>
<li>Why is the implementation performed character by character?</li>
<li>What are the security implications (if any) of the current implementation?</li>
</ul>
<p>If the proposer wishes, they may contact the CR-Team on #zftalk.dev to discuss these questions.</p></ac:rich-text-body></ac:macro>
Aug 05, 2010
Marc Bennewitz (private)
<blockquote>
<ul>
<li>What is the purpose and objective of these components?</li>
<li>Why are these components needed for the Zend Framework?</li>
</ul>
</blockquote>
<ul>
<li>HTML is often used to format texts.<br />
Some webservices links to html formated text files (without head). There are often entities used to encode specific characters not supported by the used character set.<br />
-> If you use such a file you have to convert it in your needed char-set and to minify it you can convert entities if it's supported by your char-set or if you don't allow entities you can remove all unsupported entities.</li>
</ul>
<ul>
<li>usage of characters not supported within used character set:<br />
Some companies don't use UTF-8 (history cause) and often use entities to write unsupported characters. (related to first note)</li>
</ul>
<ul>
<li>editable div's<br />
Rich text editors are using an editable div element which send content as html formated text, too. If you need to convert it you have to handle all contained entities.</li>
</ul>
<ul>
<li>htmlentities and friends only works with a fixed entity reference/table:<br />
Sometimes you need to encode/decode non standard entities which isn't possible with the build-in php functions and without usage of DOM. <br />
Additionally you can't configure htmlentities and friend to use hex-,decimal or named entities.</li>
</ul>
<blockquote>
<ul>
<li>Why is the implementation performed character by character?</li>
</ul>
</blockquote>
<p>On decoding only entities will be performed (entity to character)<br />
On encoding only UTF-8 characters will be performed (character gt 127 -> entity )<br />
Named entities described in reference will be converted once (strtr)<br />
I have to do it character by character because I have to check if this entity is valid for the given character set or not.<br />
e.g. encode "öäü€" to ISO-8859-1 only the "€" must be converted.</p>
<blockquote>
<ul>
<li>What are the security implications (if any) of the current implementation?</li>
</ul>
</blockquote>
<p>This component only decodes entities to characters by converting the uni-code of the entity to UTF-8 and than to the configured character set. If this failed one of the configurable actions will be performed.<br />
encodes characters to entities<br />
or rather encodes characters to UTF-8 and than if not supported by given char-set to the uni-code as hex or decimal entity.<br />
-> There is no handling of html specific tags where security should be done like the script-tag.</p>
Aug 12, 2010
Matthew Weier O'Phinney
<p>Marc – To be honest, this seems like a highly specific and specialized component, and I'm wondering if there's broad enough appeal to warrant its inclusion. Can you provide some more detailed use cases, and indicate the spectrum of use cases for which it would enable? Also, it seems to me like a component such as HTMLPurifier or Padraic's Wibble might offer a more secure approach here – could you comment on that, please?</p>
Aug 12, 2010
Pádraic Brady
<p>Hi Marc,</p>
<p>The first part of your response touches quite firmly on why the proposal was questioned. HTML from any external source (even if it appears trusted) must be considered insecure until it has been validated (or verified as being received from a trusted source - public web services are generally not trusted due to their potential for spawning a mass XSS attack). Since there is no actual validation for HTML possible (validation alone is completely useless), there exist HTML sanitisers like HTMLPurifier. Simply tidying up entities is not sufficient to prevent the potential for XSS and Phishing vulnerabilities. So this particular use case is not entirely suitable for your proposal, at least not without specifying the precise restrictions under which it applies.</p>
<p>The second part addresses the valid use of entities to represent Unicode multibyte characters. These entities remain valid even for Unicode encoded HTML (so it is not a validation issue but a tidy output issue). Once you see it's related to output, again we fall into the scope of a HTML Sanitiser. The same case with the third (user editing via a RTE).</p>
<p>On the fourth case, we're running into a few side issues. The native entity functions are not always ideal, but neither are they so completely useless as to necessitate a move to iconv in its entirety. This is where your proposal is missing details explaining why we need to be worried about different entity types which are all, presumably, valid in the context of HTML. For example, what is a "non-standard entity"? It's not defined anywhere. If these are illegal entities for standards compliant HTML, what is the scope of the problem they cause? We need to understand what the problem is before we can judge whether the solutions fits.</p>
<p>To put all of this into perspective, and being fully aware that it is not accepted in the ZF at this time, Wibble (Zend/Html/Filter) should perform all of what you appear to be proposing with the added benefit that it would be a full featured HTML sanitiser.</p>
<p>There was a reason for the security questions beyond the obvious. HTML vulnerabilities exist surrounding entity interpretation. For example, entities may be interpreted as their literal representations in specific contexts (notably attribute values, and CSS values). An attacker is more than capable of applying entities one or more times under the assumption that a single decoding run, will leave doubly encoded entities (e.g. ><ac:emoticon ac: behind as a single entity (i.e. a decoding bypass). Since you don't treat the HTML via DOM or other HTML aware means, it seems from the proposal that this filter may not be capable of accounting for multiple levels of entities.</p>
<p>While I can see the value of what the proposal is out to achieve, so far it seems to suffer from its narrow scope. In that respect, it's a little like Zend_Filter_StripTags. Does it strip tags? Yes. Does it strip tags under all circumstances? No. Does it actually add anything to security? Not really. It works, but in a limited fashion that needs to carefully considered. This filter has the same issue. It will perform exactly what it says it will and no more. It's one slice out of the bigger puzzle of filtering HTML. I'm not saying that makes it useless, just that it's only useful for very specific tightly controlled inputs. If it were to be added to the framework, I would insist that its documentation contain a section just to make the points above as clear as possible (assuming these are not based on a misunderstanding of the component's operation).</p>
<p>Outside of security, the proposal still struggles to explain its purpose. Both the overview and operation sections are extremely brief and don't really make a case for including the component in the ZF. These sections need to try and make it clear to readers why we need/want these new filters. We get they encode/decode entities, but what makes that useful compared to every other option I presume people are already using (I just stick stuff like this through HTMLPurifier - but I'm sure people use other strategies).</p>
Aug 16, 2010
Stefan Staudenmeyer
<p>Dude came in the support channel and asked me to translate this section for him. Sounds like plain english to me, else "/trout hadean" in #zftalk.dev @ freenode...</p>
<p>START NUB ENGLISH :::</p>
<p>This entity-filter attends to convert sections of text with entities, no matter if they come as HTML </p>
<p>or XML (Wibble/Zend_HTML_FIlter though require the HTML format). A section can come with multiple </p>
<p>character sets, like unicode for the entities and a normal one for text. The Filter helps converting </p>
<p>these sections into a different character set with or without the entities. </p>
<p>Why?<br />
1. Not every program or service works with clean unicode but grown historically. When you are forced </p>
<p>to work with these programs you have to convert them (I had to work with such services on many </p>
<p>projects).</p>
<p>2. Many users continue to use HTML-entities, even though the site already runs with native Unicode. </p>
<p>With a little Help of this Filter, you can delete the entities overhead by converting the nonrelevant </p>
<p>ones into UTF-8 that are not needed for escaping.</p>
<p>3. When you whant to convert HTML into plain text, stripping out the tags (strip_tags()) wont do it. </p>
<p>You have to as well delete the entities, wich only partially can be achieved with htmlentities and </p>
<p>stuff, as they are using a predefined entity-table as well as limited character sets or functions to </p>
<p>handle incompatible characters (like the euro-sign in a ISO-8859-1 section). </p>
<p>Security:<br />
As the filter does not work on HTML/XML-layer, its security measures are unnessesary. It is a fact that Unicode has to follow several rules, but through using iconv (or entities) not well formed Unicode-characters should be recognized and run the "invalidCharAction" (should be added to unit tests).</p>
<p>Definitions: </p>
<ul class="alternate">
<li>invalid character: a character, wich can not be converted or not part of the output character set.</li>
<li>invalid entity: an entity wich is undefined.</li>
</ul>
<p>::: STOP NUB ENGLISH</p>
Aug 17, 2010
Pádraic Brady
<p>Entities operate in XML/HTML - i.e. definitely in the HTML layer. Some Unicode valid characters are a security risk (e.g. half-width characters among others <a href="">IE6 and halfwidth/fullwidth Unicode characters</a>). No mention whether the component will handle nested/double encodings in any way (a known reconstructive risk to bypass HTML/XML filters for decoding).</p>
Aug 17, 2010
Marc Bennewitz (private)
<ul>
<li>Entities operate in XML/HTML:<br />
Yes, but often used outside of it</li>
</ul>
<ul>
<li>Some Unicode valid characters are a security risk:<br />
This is not a security issue of entities. You can write it as Entities AND as native characters on a unicode charset.<br />
-> On your example page isn't any entity!<br />
-> If you set a unicode charset as output you have to handle/filter this characters if where are entities or not.<br />
-> If you don't set a unicode charset as output this filter calls the invalidCharAction because these entity-characters can't convert to your output charset.</li>
</ul>
<ul>
<li>nested/double encodings:<br />
I'm not sure if I understand you right.<br />
Double encoded entities can't be automatically double decoded. You can't know if the text is a valid and native text after only one decode.<br />
E.g.: If you paste an example html snipped on a comment to describe something your html snipped must be double encoded on display your comment. All reading this displayed html only should decode it once to get the native text.<br />
What's wrong with it?</li>
</ul>
Aug 18, 2010
Pádraic Brady
<p>Marc, we're obviously not on the same page so let me try and put it into perspective.</p>
<p>Consider a point to point use case from receiving input (containing entities) to echoing output to a browser. I'm guessing your first instinct is to pass everything (after entity filtering) through htmlspecialchars(). This is perfectly fine. Now, consider use case #1 from the proposal and you find a problem - you can't run htmlspecialchars() across HTML intended for direct output (i.e. from a rich text editor using HTML tags and styling). That would negate the HTML and remove the formatting/styling intended by the rich text editor. Using your filter adds nothing in this regard. You STILL can't run it through htmlspecialchars() - it's HTML, not plain text. So what's left to ensure secure output? Use a HTML Sanitiser (a secure one). This will not have any issues with your filter, but it also makes your filter redundant - a good sanitiser will decompose entities into their literal characters correctly. This basically makes use case #1 redundant from the perspective that a HTML sanitiser is still required and should not need any additional entity decoding beyond that.</p>
<p>Use case #2 has similar issues. It's clearly both in the HTML domain and utilises HTML sanitisation via strip_tags() which is not considered a sanitisation option since it's not character encoding aware (also it strips tags but doesn't clean or validate anything that is added as a safe element, as would be necessary in different cases). strip_tags() is basically evil - even the manual doesn't note all of its limitations which is a shame.</p>
<p>This is the point I'm making by emphasising security as a concern. You keep insisting that security is not an issue and that the component does not operate in the HTML domain, and thus fail to recognise that many uses for the component directly depend on bypassing output filtering in favour of HTML sanitisation. The component doesn't exist in isolation. This means that, whether you see it that way or not, your component is effectively aimed at replacing one element of HTML sanitisation. The only other alternative is that it is intended for use without a HTML sanitiser or with a far more limited sanitiser, neither of which is recommended security practice in PHP. In this respect the Decoder (I see nothing insecure about an Encoder) is redundant unless within a very narrow scope where all possible HTML elements are neutralised prior to output. This is not addressed or mentioned anywhere, and the context of the use cases suggests nothing to limit its scope.</p>
<p>More relevantly (just to add to the confusion of using this alongside a sanitiser), there is the risk that someone would use the Decoder after HTML Sanitisation. Since the decoder filter is capable of reversing previously added entities (e.g. & to replace the & in any entities original to the input - usually done with attributes as a precaution against XSS/Phishing), it is possible to undo some sanitisation modifications. This might be wrong - there's no decoder implementation to refer to yet so I'm assuming it's possible going by the proposal text.</p>
Sep 01, 2010
Marc Bennewitz (private)
<p>hi paddy</p>
<p>This filter don't run it through htmlspecialchars() - it's using own functions for encoding and decoding and this process is configurable to keep existing special chars as is -> than <>'"& are not encoded but all other.</p>
<p>The main job of this filter is to handle entities (and only entities) more adjustable than the build-in htmlentities and friend does. I mean it should help converting such documents from one charset to another by minimizing the entity overhead.</p>
>This basically makes use case #1 redundant from the perspective that a HTML sanitiser is still required and should not need any additional entity decoding beyond that.</p></blockquote>
<p>Do you mean that this should be part of HTML Senitiser? Than should this usable out of DOM.</p>
Sep 02, 2010
Pádraic Brady
<blockquote>
<p>This filter don't run it through htmlspecialchars() - it's using own functions for encoding and decoding and this process is configurable to keep existing special chars as is -> than <>'"& are not encoded but all other.</p></blockquote>
<p>Is the default to decode entities such as > or to keep them undecoded?</p>
<blockquote>
<p>The main job of this filter is to handle entities (and only entities) more adjustable than the build-in htmlentities and friend does. I mean it should help converting such documents from one charset to another by minimizing the entity overhead.</p></blockquote>
<p>I'm not so worried about encoding/decoding as I am the context in which they are used. Many of the use cases show it being used prior to output (thus it's operation in that context should encourage secure behaviour). It has to be assumed that a secure HTML sanitiser is being used - you acknowledge this by uses of strip_tags(), for example. </p>
<blockquote>
>That's what I've been saying. </p>
<blockquote>
<p>Do you mean that this should be part of HTML Senitiser? Than should this usable out of DOM.<>
Sep 04, 2010
Marc Bennewitz (private)
<blockquote><p>Is the default to decode entities such as > or to keep them undecoded?</p></blockquote>
<p>For default all characters will be encoded / decoded.<></blockquote>
<p>I took some look within wibble and HTMLPurifier but I can't find enough information how to:</p>
<ul class="alternate">
<li>remove entities used for characters out of document charset (translit, substitute, ignore, ...)</li>
<li>convert a document from one charset to another</li>
<li>handling unknown (self defined) entities</li>
<li>encoding to named entities vs. numeric vs. hex</li>
</ul> | http://framework.zend.com/wiki/pages/viewpage.action?pageId=18219044&focusedCommentId=26378247 | CC-MAIN-2014-41 | refinedweb | 5,562 | 54.63 |
Hello everyone,
For the following code from Bjarne's book, it is stated that template parameter T for function g will be instantised as int other than double. My question is why there are not two instantiations for both int and double version of template function g?
Here is the related statement from Bjarne,Here is the related statement from Bjarne,Code:// section C.13.8.3 Point of Instantiatant Binding template <class T> void f (T a) { g(a); } void g(int); void h() { extern g (double); f (2); }
--------------------
Each use of a template for a given set of template arguments defines a point of instantiation.
That point is the nearest global or namespace scope enclosing its use,
just before the declaration that contains that use.
--------------------
Does it before g (double) is not global function or namespace scope enclosing its use? If yes, I do not know why g (double) is not a global function, since it is declared as extern and some other compile unit should expose it?
thanks in advance,
George | http://cboard.cprogramming.com/cplusplus-programming/99989-template-function-instantiation.html | CC-MAIN-2015-06 | refinedweb | 174 | 58.82 |
Python and other scripting languages are sometimes dismissed because of their inefficiency compared to compiled languages like C. For example here are implementations of the fibonacci sequence in C and Python:
And here are the execution times:
$ time ./fib 3.099s $ time python fib.py 16.655s
As expected C has a much faster execution time - 5x faster in this case.
In the context of web scraping, executing instructions is less important because the bottleneck is I/O - downloading the webpages. But I use Python in other contexts too so let’s see if we can do better.
First install psyco. On Linux this is just:
sudo apt-get install python-psyco
Then modify the Python script to call psyco:
import psyco psyco.full() def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) fib(40)
And here is the updated execution time:
$ time python fib.py 3.190s
Just 3 seconds - with psyco the execution time is now equivalent to the C example! Psyco achieves this by compiling code on the fly to avoid interpreting each line.
I now add the below snippet to most of my Python scripts to take advantage of psyco when installed:
try: import psyco psyco.full() except ImportError: pass # psyco not installed so continue as usual | https://webscraping.com/blog/How-to-make-python-faster/ | CC-MAIN-2017-43 | refinedweb | 218 | 64.1 |
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:
Last value of limted pattern length
Hi everyone,
what I'm trying to do is getting the last value of pattern recognition as a line. The data that is used in the pattern should be limitted.
My current approach ending in an index error
self.pattern_len =min(len(self.datas[0].open)-1, 10) self.PATTERN_CDLHARAMICROSS = bt.talib.CDLHARAMICROSS(self.datas[0].open.get(size= self.pattern_len), self.datas[0].high.get(size= self.pattern_len), self.datas[0].low.get(size= self.pattern_len), self.datas[0].close.get(size= self.pattern_len))[-1] IndexError: array index out of range
I know it could probably be easier by just using the whole length for the pattern and just read the last value from the line.
(Would that mean in every bar/step there would be an complete array of the pattern recognition?)
Is the error, that it tries to establish the value before it has enough values? Why does my approach with min does not work?
To answer my own question:
def __init__(self): self.PATTERN_CDLHARAMICROSS = bt.talib.CDLHARAMICROSS(self.datas[0].open, self.datas[0].high, self.datas[0].low, self.datas[0].close) def next(self): self.log(self.PATTERN_CDLHARAMICROSS[0])
gives exactly what i wanted. No doubled arrays and limiting the time line makes no sense here if it is applied to the whole line.
Sorry for the stupid question. | https://community.backtrader.com/topic/3803/last-value-of-limted-pattern-length/2 | CC-MAIN-2022-40 | refinedweb | 251 | 57.67 |
#include <Variables.hpp>
List of all members.
By default the Event methods return the full object/array. Often only a few variables are used out of a given branch.
This helper class can be used to restrict access to only a subset of the variables in a branch. It should be initialized (either via the constructor or the add() methods) with a list of variable names in the branch. Then the Variables should be passed as a parameter to the Event::getNNN() method. All other variables in the branch are undefined:
Variables vars("_evtno"); const TMBGlobal *global = event.getGlobal(vars); int event_number = global->evtno(); int run_number = global->runno(); // UNDEFINED !!
Definition at line 35 of file Variables.hpp.
Constructor & Destructor Documentation | http://www-d0.fnal.gov/Run2Physics/working_group/data_format/caf/classcafe_1_1Variables.html | crawl-003 | refinedweb | 120 | 60.21 |
IRC log of svg on 2010-05-31
Timestamps are in UTC.
08:05:07 [RRSAgent]
RRSAgent has joined #svg
08:05:07 [RRSAgent]
logging to
08:05:09 [trackbot]
RRSAgent, make logs public
08:05:11 [trackbot]
Zakim, this will be GA_SVGWG
08:05:11 [Zakim]
I do not see a conference matching that name scheduled within the next hour, trackbot
08:05:12 [trackbot]
Meeting: SVG Working Group Teleconference
08:05:12 [trackbot]
Date: 31 May 2010
08:05:32 [pdengler]
pdengler has joined #svg
08:05:38 [ed]
ed has joined #svg
08:05:53 [ed]
trackbot, start telcon
08:05:55 [trackbot]
RRSAgent, make logs public
08:05:57 [trackbot]
Zakim, this will be GA_SVGWG
08:05:57 [Zakim]
I do not see a conference matching that name scheduled within the next hour, trackbot
08:05:58 [trackbot]
Meeting: SVG Working Group Teleconference
08:05:58 [trackbot]
Date: 31 May 2010
08:06:39 [ed]
Zakim, remind me in 8 hours about whatever
08:06:39 [Zakim]
ok, ed
08:13:08 [jwatt]
jwatt has joined #svg
08:15:05 [ChrisL]
ChrisL has joined #svg
08:15:28 [ChrisL]
08:15:50 [pdengler]
scribenick: pdengler
08:16:15 [pdengler]
topic: CSS 2.1 Issue 114
08:17:49 [pdengler]
ChrisL: To run the test linked above, you need a certain font; according to CSS, you should skip that first font because it is invalid
08:18:16 [pdengler]
ChrisL: And that you should in fact skip over the entire list, which means the default font should be used
08:18:24 [ChrisL]
firefox 3.6 shows all numbers
08:18:42 [ChrisL]
opera 10.10 does too but opera 10.53 shows no numbers
08:18:46 [pdengler]
pdengler: IE Platform preview shows none
08:19:32 [pdengler]
pdengler: Chrome does the same as IE and FireFox
08:19:56 [ed]
opera 10.53 shows no text at all (even the "revision" string), wondering if it really finds the proper font there
08:20:29 [pdengler]
ChrisL: Proposal is that a CSS font should be an ident. But this is potentially to strict
08:20:48 [pdengler]
ChrisL: The issue is that certain characters would have to be quoted
08:21:59 [pdengler]
pdengler: This means that fonts that start with (1-9) would have to be quoted
08:23:41 [pdengler]
ChrisL: The issue is that CSS wants to close this issue, but that this effects SVG. But it looks like most of them are rejecting fonrt family names, and remain compliant
08:24:05 [pdengler]
pdengler: Correction IE shows the numbers just as Chrome and Firefox
08:24:24 [ChrisL]
batik (svn) shows the numbers (and a bunch of error messages)
08:24:41 [pdengler]
ChrisL: Suggest we go with Mozilla proposal.
08:25:43 [ChrisL]
so font family would be a list of CSS2.1 IDENT
08:26:42 [ed]
08:28:21 [ChrisL]
so SVG WG aligns with proposal 1,
08:29:19 [ChrisL]
action chris to convey this result to CSS WG
08:29:20 [trackbot]
Created ACTION-2788 - Convey this result to CSS WG [on Chris Lilley - due 2010-06-07].
08:29:57 [ChrisL]
action-2788?
08:29:57 [trackbot]
ACTION-2788 -- Chris Lilley to convey this result to CSS WG -- due 2010-06-07 -- OPEN
08:29:57 [trackbot]
08:31:45 [ChrisL]
action chris to move the font-family parsing tests to the svg 1.1se test suite
08:31:45 [trackbot]
Created ACTION-2789 - Move the font-family parsing tests to the svg 1.1se test suite [on Chris Lilley - due 2010-06-07].
08:40:13 [pdengler]
nomis: The basic idea behind diffusion curves is that you define shapes, and then colors on the sides of a curve
08:40:43 [pdengler]
Topic : Diffusion Curves by Simon from GIMP
08:40:54 [ChrisL]
08:42:03 [shepazu]
08:42:04 [nomis]
nomis has joined #svg
08:42:46 [shepazu]
shepazu has joined #svg
08:42:51 [pdengler]
nomis: Simon has prototyped this on RGB (not yet on curves) but on pixels that diffuse colors
08:43:20 [nomis]
I'd like to emphasize that all of the algorithm implementation is done by jasper.
08:46:44 [ChrisL]
original paper
09:02:03 [ed]
ed has joined #svg
09:05:33 [pdengler]
The use case for diffusion curves is rooted in drawing much smoother, richer graphics with being able to establish vectors/curves with a 'color' on each side, then having the algorithm fill in the difference
09:06:13 [pdengler]
AlexD: Other use cases include removing/smoothing through averaging an image (such as 'air brushing a photo')
09:06:38 [ed_]
ed_ has joined #svg
09:07:10 [pdengler]
anthony: The issue with the original alogithm is that it was an iterative method. This was an issue with animation causing computational intensive rendering
09:07:23 [pdengler]
ChrisL: Since then, there have been some papers on making that issue more tractable
09:07:28 [pdengler]
pdengler: So what about the IP around this?
09:15:44 [shepazu]
shepazu has joined #svg
09:21:45 [pdengler]
pdengler has joined #svg
09:22:11 [pdengler]
anthony: If you look at these images, they all have smooth edges. But if you have a pattern, this begins to break down
09:22:28 [pdengler]
ChrisL: That's why having it in SVG is more powerful in an SVG Authoring Tool
09:22:50 [pdengler]
anthony: Hi frequency color changes do not work as well (from the author and from Anthony)
09:24:56 [pdengler]
ChrisL: How would this be integrated into SVG?
09:27:21 [pdengler]
nomis: Why define diffusion curves independent of the image
09:28:19 [pdengler]
shepazu: We are discussoin whether to make it a paint server, or whether you apply via an effect
09:28:42 [pdengler]
anthony: Could you do it through filters where you apply it to shape?
09:28:47 [pdengler]
ed: Doesn't come naturally that way
09:29:10 [pdengler]
ChrisL: We are going to need some sort of syntax that allows to define 'left-side'/'right-side' colors
09:29:29 [pdengler]
ChrisL: You can imagine it being referenced as a fill/paint as you can any other paint
09:30:17 [pdengler]
shepazu: I was thinking of a new property, e.g.
09:32:24 [AlexD]
I think you are putting the cart before the horse. It's a nice graphical demo, however it would be good to first see mainstream authoring tools support it; and more importantly fully evaluate the run-time efficiency of the techniques. If the diffusion curve algorithms are n^2 then forget it. Is there any IP also?
09:33:06 [AlexD]
BTW, left/right side fill is the Flash model.
09:33:20 [pdengler]
anthony: Consider using the new path syntax
09:33:49 [ChrisL]
yes but its a solid fill i believe
09:34:59 [pdengler]
shepazu: e.g. new path syntax <path><quadratic ../><lineto../><horiztonal ../></path>
09:35:15 [ed]
AlexD: yeah, the complexity does worry me as well
09:35:28 [pdengler]
shepazu: consider too verbose. But if you use compressed it, it turns out the the compressed format is much better
09:35:55 [pdengler]
pdengler: I still think it's too verbose given the potential use cases
09:37:25 [AlexD]
Personally I think we need to address things like variable stroke-width that's been asked for years ago and If I remember correctly high on the cartographers wish-lists.
09:39:07 [pdengler]
ed: I've been working on OpenGL; would it be interesting to redefine a path syntax to include a color?
09:40:00 [pdengler]
shepazu: If we are talking about having the constraints functions (calc, etc) we are already talking about changing the path syntax, to break down into path/calc/ and color
09:40:06 [pdengler]
pdengler: No way
09:42:30 [pdengler]
ChrisL: Suppose you are only allowed to use cubic beziers. The start/end positions would be known. So you can have a separate attribute for coloring (lcolls/rcols)
09:43:07 [pdengler]
nomis: I'm not sure why you would want to restrict this to bezier curves?
09:43:09 [pdengler]
ChrisL: Simplicty
09:43:21 [pdengler]
nomis: But any path can have these
09:49:03 [pdengler]
shepazu: Back to the agenda, we want to talk about group workflow
09:50:23 [pdengler]
shepazu: typically what we do with a feature, we will have a discussion in the group, mailing lists, face-to-faces are used for attempting to finalize decisions
09:50:36 [pdengler]
shepazu: Now we are just brainstorming
09:50:51 [pdengler]
ChrisL: We have had a couple of runs at diffusion curves; we are excited about it; we see the potential now
09:51:07 [pdengler]
anthony: In that case, we should gather the ideas together and write them down
09:54:05 [AlexD]
We should collate all the work done on 1/2 Full of which there is a lot - compositing, vector effects, flow graphics, etc. etc. and add the interesting nice things - and hopefully address the shortcomings that the geo community have been asking for for years. Amongst everything else of course.
09:54:20 [AlexD]
s?1/2?1.2?
09:54:56 [pdengler]
shepazu: So does GIMP import SVG?
09:55:01 [pdengler]
nomis: Yes.
09:55:11 [pdengler]
ChrisL: Can you interpret clipping paths on raster images?
09:55:45 [pdengler]
nomis: We output them from raster images; you can defining a clipping path for exporting to TIF for example
09:57:09 [pdengler]
ed: What I would like to see personally is this plan that we have written up over the previous days to put it on the Wiki for collaboration
09:57:52 [pdengler]
action : pdengler to post plan for the plan for SVG 2.0 on the Wiki
09:57:52 [trackbot]
Created ACTION-2790 - Post plan for the plan for SVG 2.0 on the Wiki [on Patrick Dengler - due 2010-06-07].
10:01:30 [pdengler]
nomis: One more item on diffusion curves: if you have paths with multiple color definitions along the way, you might want to define the way colors are interpoloated along the path
10:02:31 [pdengler]
Topic : Fonts
10:03:07 [pdengler]
Action : chrisl to investigate diffusion curves and potentials for SVG 2.0
10:03:07 [trackbot]
Created ACTION-2791 - Investigate diffusion curves and potentials for SVG 2.0 [on Chris Lilley - due 2010-06-07].
10:03:27 [nomis]
if anybody wants to play with the prototype diffusion code:
10:04:21 [pdengler]
ChrisL: Will investigate syntax, authoring tools, use cases
10:04:48 [pdengler]
anthony: I will investigate rendering methods
10:05:13 [pdengler]
action : anthony Investigate rendering methods for diffusion curves
10:05:13 [trackbot]
Created ACTION-2792 - Investigate rendering methods for diffusion curves [on Anthony Grasso - due 2010-06-07].
10:06:23 [shepazu]
10:08:30 [fat_tony]
Topic: Text and Fonts
10:10:10 [fat_tony]
CL: I have a proposal for SVG 2.0 as what we should do for fonts
10:10:52 [fat_tony]
... the web has meanwhile moved to downloading fonts of web
10:10:59 [fat_tony]
... in 1.0 you were required to SVG fonts
10:11:18 [fat_tony]
... I propose for SVG 2.0 we mandate you use WOFF
10:11:27 [fat_tony]
... and have SVG Fonts as an optional features
10:11:53 [fat_tony]
DS: I have a counter proposal, right now we have SVG Tiny 1.2 fonts in Opera and Webkit
10:11:58 [fat_tony]
... and there are patches for FireFox
10:12:02 [fat_tony]
DC: Yes
10:12:50 [fat_tony]
JW: We don't currently SVG Fonts are the well designed and should be the solution going forward
10:13:05 [fat_tony]
... if we have demand from users to put them then we will consider it
10:13:26 [fat_tony]
... at the moment we'll see how WOFF goes
10:13:41 [fat_tony]
... and if that meets the majority of uses cases we can gather the uses cases it doesn't meet
10:13:51 [fat_tony]
... and reconsider
10:14:17 [fat_tony]
DS: My counter proposal is we add SVG Tiny 1.2 fonts to SVG 2.0
10:14:24 [fat_tony]
... we consider adding it
10:14:30 [fat_tony]
... then we have separate font specification
10:14:37 [fat_tony]
CL: Had considered that
10:14:41 [AlexD]
What's the status of WOFF standards-wise? Is this W3C working group or loosely coupled vendor alliance like WhatWG?
10:14:51 [fat_tony]
... but there are few reasons why I didn't say this
10:16:07 [fat_tony]
... Tiny subset does the single colour path, but don't get any features about animated fonts, video fonts etc. E.g. anything that can be drawn is a glyph
10:16:16 [fat_tony]
... that's the bit that should be held onto SVG Fonts
10:16:32 [fat_tony]
PD: What couldn't you take those benefits that SVG Fonts have, and take those to WOFF
10:16:51 [fat_tony]
CL: Because WOFF is a packaging format for OpenType
10:17:59 [fat_tony]
PD: I agree we should put fonts in as an optional module
10:18:15 [fat_tony]
... SVG Fonts as an optional module
10:18:27 [fat_tony]
... If customers demand it, I'll build it
10:18:35 [fat_tony]
ED: I agree with what Doug proposed
10:18:41 [fat_tony]
... breaking it out is fine
10:18:46 [AlexD]
SVG Tiny 1.2 fonts is trivial to implement, and by being defined as a font allows an implementation to
10:18:52 [fat_tony]
... but that subset should be required
10:18:58 [AlexD]
optionally cache glyphs.
10:19:05 [fat_tony]
... because that is already implemented
10:19:48 [ChrisL]
@alex: woff is being standardized at W3C
10:20:10 [AlexD]
SVG fonts are the only (current) way to deliver a single piece of SVG content to a device and have the text rendered as intended. Similar to XPS where obfuscated OpenType is mandated. I'd like to see the obfuscated OpenType considered alongside WOFF too.
10:20:14 [fat_tony]
DS: To me as a developer, there are couple of different things about SVG Tiny 1.2 fonts
10:20:17 [fat_tony]
... you can have overlaps
10:20:20 [ChrisL]
10:20:23 [fat_tony]
... which you can't do in traditional fonts
10:20:29 [fat_tony]
... and you can do scripting
10:20:33 [fat_tony]
... which is why I would want them
10:20:38 [fat_tony]
... I'll be flexible on this
10:21:48 [fat_tony]
DC: [gives diagram over overlapping diagram]
10:22:25 [fat_tony]
s/overlapping diagram/overlapping font/
10:24:15 [fat_tony]
DS: Wouldn't want overlapping fonts unless you get to headers
10:24:40 [AlexD]
Also, as for overlaps - you can define strokes as individual graphics items and glyphs using <use> which gives you the ability to generate Asian fonts using a set of calligraphic strokes that are composite glyphs. That sort of encapsulation isn't available in other fonts and can reduce size greatly for large glyph sets like Kanji...
10:26:05 [fat_tony]
PD: In terms of beyond headers is it reasonable to use SVG Fonts for a document?
10:26:17 [fat_tony]
ED: Primary use case is headers
10:26:40 [fat_tony]
s/headers/headings/
10:26:43 [shepazu]
s/headers/headings/
10:27:11 [fat_tony]
DC: My experience of SVG graphics is they can be quite slow
10:27:28 [fat_tony]
PD: I know you have more use cases
10:27:37 [fat_tony]
ED: I'm not saying the whole module should be required
10:27:56 [fat_tony]
... I'm saying a small subset that's already implemented should be carried on to the new spec
10:27:57 [shepazu]
s/can be quite slow/can be quite slow, so it's not typical to render large blocks of text/
10:28:10 [fat_tony]
DS: There are two or three proposals on the table
10:29:13 [fat_tony]
BL: I think it use already
10:29:18 [fat_tony]
... the SVG Fonts
10:29:25 [fat_tony]
... if you make it optional now
10:29:38 [fat_tony]
... it might not work anymore
10:29:42 [fat_tony]
CL: That's the issue now
10:29:53 [fat_tony]
BL: Can do a lot of great things with SVG Fonts
10:30:13 [fat_tony]
PD: It will be only performant it will on be use cases for headings
10:30:25 [fat_tony]
BL: Is there a technology right now that can replace SVG Fonts
10:30:31 [fat_tony]
PD: We don't need fonts
10:30:35 [fat_tony]
... you can use paths
10:30:47 [fat_tony]
... we have this huge API on this thing called fonts
10:30:55 [fat_tony]
CL: You're suggesting don't put text there
10:30:59 [fat_tony]
... put graphics there
10:31:14 [fat_tony]
... not good for accessibility
10:31:24 [fat_tony]
PD: It just seems heavy handed
10:31:45 [AlexD]
If SVG fonts are used the user agent automatically knows that the bitmap can be cached for re-use and efficiency. Basic laser printer techniques from the 80s apply here. And accesibility and cut/paste from the graphic, and searching,etc...
10:31:49 [fat_tony]
CL: You've converted the curve and stuck an element to say it's font
10:32:28 [fat_tony]
DS: There is altGlyph
10:33:07 [fat_tony]
... This is the reverse to the way I would've done it
10:33:12 [fat_tony]
... syntax would be like:
10:33:32 [shepazu]
<text ...><altGlyph xlink:My Logo</altGlyph> </text>
10:35:07 [fat_tony]
CL: It points to a glyph
10:35:15 [fat_tony]
... it has to say what the base line is
10:35:26 [ChrisL]
and the coordinate system
10:35:40 [fat_tony]
DS: We could alter altGlyph
10:35:47 [fat_tony]
... as if it where a use
10:35:58 [fat_tony]
CL: Where is your point you're anchoring at?
10:37:30 [fat_tony]
DS: If you're pointing at something that is not a glyph it acts more like a <use>
10:37:36 [fat_tony]
... but it does it inline
10:37:51 [fat_tony]
... we'd have to define in the spec what things in the spec what the baseline is
10:39:23 [fat_tony]
JW: I'm not resistant to working on SVG Fonts
10:39:32 [fat_tony]
... I'm just saying it should not be required by 2.0
10:39:41 [fat_tony]
... I'm quite happy to work and participate on the fonts part
10:40:04 [fat_tony]
... there's a difference to us having fonts in our charter compared to requiring it
10:40:19 [fat_tony]
CL: Do you think Mozilla would implement it if it was optional?
10:40:28 [fat_tony]
JW: Depends on demand
10:41:05 [AlexD]
if the time-frame for 2.0 reflects 1.2 Tiny in any way, i.e. 7 years from 1.1 to Tiny 1.2 then you will have 7 years of 1.1 browsers that support SVG fonts. Deprecating them for 2.0 seems a bit short-sighted. And the implementation effort is trivial compared with other aspects of the spec...
10:42:54 [pdengler]
Not all browsers support them now
10:43:22 [AlexD]
True - but there are _many_ mobile and IPTV user agents that do.
10:44:28 [AlexD]
Oh and both Adobe Illustrator and Corel Draw emit SVG Fonts as part of their content, and they are leaders in the graphic arts authoring community...
10:44:43 [ChrisL]
alex, these are all good points
10:44:49 [ChrisL]
so does inkscape
10:45:22 [ChrisL]
inkscape can author svg fonts as well. as can fontforge
10:45:50 [ChrisL]
deprecation is not on the table
10:46:16 [fat_tony]
DS: I'm ok with potentially removing them from the core, as along as there is away to do SVG text as a graphic
10:46:52 [fat_tony]
... I'm proposing some sort of altGlyph like solution
10:47:19 [fat_tony]
... so we don't have content out that is not a-semantic
10:47:30 [fat_tony]
... want text extraction and text search to work
10:48:32 [fat_tony]
PD: It gets tricky with fonts on a path
10:50:53 [AlexD]
What's tricky about fonts on a path?
11:56:34 [ChrisL]
debug off, optimize on, deprecation on
12:00:55 [ed]
dave crossland: one usecase I see for svgfonts is photo-fonts
12:01:09 [ed]
...there are such proprietary font formats
12:01:35 [ed]
CL: we should collect those on a wiki or something
12:02:02 [ed]
DS: fontlab (photolab)
12:02:13 [ed]
s/photolab/photofont.com/
12:02:54 [ed]
DC: you're not going to typeset a book with a photofont, but it does get used for some things
12:03:21 [ed]
DS: the scrapbooking community might be interested in this
12:04:48 [ed]
DS: (shows a glyphshape used as a clippath, cutting out a letter G of a photo)
12:08:34 [ed]
(examples of photofonts shown)
12:09:55 [ed]
DC: sometimes you want glyphs randomly selected, having several shapes, like for handwriting fonts
12:10:12 [ed]
CL: you could do most of that using an svgfont
12:10:20 [ed]
...using ligatures etc
12:11:08 [ed]
DC: full svgfonts would give the power to do more interesting (such as photofonts)
12:11:42 [ed]
... so saying it would be nice if full svgfonts were supported in svg 2.0
12:12:00 [ed]
DS: we don't see it on the web much today
12:12:55 [ed]
... designers might want to be able to use these features, things that can't be done with traditional fonts
12:13:07 [ed]
...and I'm fine with having svgfonts as an optional module
12:15:30 [ed]
topic: xlink:href and html integration
12:15:40 [ed]
scribenick: ed
12:16:24 [shepazu]
12:16:39 [pdengler]
pdengler has joined #svg
12:17:58 [shepazu]
12:24:44 [fat_tony]
sribenick: fat_tony
12:25:05 [fat_tony]
ED: If you had xlink:href and href on an element which one would you throw away?
12:25:49 [ed]
s/which one would you throw away?/you are saying that one of them is thrown away during parsing?/
12:26:28 [abattis]
abattis has joined #svg
12:26:31 [abattis]
O
12:26:35 [abattis]
Yo
12:26:48 [abattis]
scribenick
12:27:31 [abattis]
scribenick: abattis
12:27:45 [ChrisL]
scribe: Dave_Crossland
12:27:52 [abattis]
scribe: Dave Crossland
12:28:34 [abattis]
shepazu: here's now IRC works
12:29:00 [abattis]
... and thats it.
12:30:24 [abattis]
... If only xlink:href is present it will be put into the DOM property href and when serialised href is not namespaced
12:30:49 [abattis]
... theres one remaining usse
12:30:58 [abattis]
... xlink is used in content for title=""
12:31:14 [abattis]
... the xlink title is meant to describe the nature of the lnked resource, not the graphic in the SVG
12:31:30 [abattis]
... so do we get rid of xlink and added title as well to fulfil that function
12:31:36 [abattis]
... so its title as used in html
12:31:54 [abattis]
ChrisL: we only added it because XLINK had it
12:32:12 [abattis]
... having human readbale text in attributes where you can't i18n it
12:32:22 [abattis]
... but xlink made that mistake and we can inherit it (?)
12:32:35 [abattis]
shepazu: title as in attribute descirbes whats being linked to
12:32:43 [abattis]
... title as a child describes the link itseld
12:32:52 [abattis]
... itself
12:33:03 [abattis]
ChrisL: HTML can do both, eg lang
12:33:19 [abattis]
shepazu: svg tin 1.2 today does it with attribute only
12:33:32 [abattis]
... i prpose we say yes
12:33:52 [abattis]
pdengler: what do i put in for script?
12:34:08 [ChrisL]
href
12:34:09 [abattis]
shepazu: first, i want to minute a resolution to go with this plan
12:34:24 [abattis]
pdengler: if you put href on an image
12:34:39 [ChrisL]
s/lang/lang and hreflang/
12:34:58 [abattis]
... then _IF_ we have a goal of syntactic and programmatic (img.src)
12:35:08 [abattis]
shepazu: epareate the issues of src and href
12:35:31 [abattis]
... our goal can be to treat href one way and agree ,and then look at src
12:35:39 [abattis]
pdengler: you think we can get agreemnt on src fast?
12:36:07 [abattis]
ChrisL: you end up with a guessing game for href and src, if they are dfferent, people dont remember
12:36:12 [abattis]
pdengler: src is more important
12:36:26 [abattis]
shepazu: we have to resolve how href is processed
12:36:34 [abattis]
... its definied in <use>
12:36:43 [abattis]
... they are really separate issues
12:36:54 [abattis]
... are you saying not to allow image href at all?
12:37:01 [abattis]
pdengler: you want IE to do this
12:37:03 [abattis]
shepazu: yes
12:37:12 [abattis]
pdengler: if we ship IE with image href
12:37:21 [abattis]
shepazu: that doesnt preclude img src, we can do both
12:37:24 [abattis]
pdengler: whats the API look like?
12:37:27 [abattis]
shepazu: crappy
12:37:38 [abattis]
shepazu: we have to say what happens with href, period
12:37:51 [abattis]
... we have to say what happens when we have href there, so thats why its separate issue
12:38:09 [abattis]
.. everywhere
12:38:12 [abattis]
... everywhere
12:38:19 [abattis]
... even HTML when SVG is inside HTML
12:38:24 [abattis]
pdengler: so out of doc?
12:38:27 [abattis]
shepazu: everywhere!
12:38:46 [abattis]
pdengler: theres an issue with the API... i hate to proliferate and attribute
12:38:55 [abattis]
shepazu: maybe its okay, lemme think
12:39:08 [abattis]
shepazu: i think its separete because if we start doing <script src=""> then
12:39:16 [abattis]
... theres a better case there than <img>
12:39:30 [abattis]
... its a tag spelled differently, behaves differently
12:39:40 [abattis]
pdengler: we can make a case t oHTML WG they have inconsisntecyn
12:46:11 [abattis]
abattis: whats up with html 6?
12:46:29 [abattis]
shepazu: there are things talked about not going in to html5, so probably there will be one
12:46:41 [abattis]
... okay, so, href itself is readonly
12:46:58 [abattis]
ed_work: theres a link thats read-write
12:47:02 [abattis]
ed_work: the spec is confused
12:47:17 [abattis]
ed_work: its RW because you can write to what it points to
12:47:43 [ed]
ed has joined #svg
12:47:56 [abattis]
shepazu: so can we get an AMEN to xlink:href
12:47:59 [abattis]
pdengler: amen
12:48:11 [abattis]
jwatt: ummm let me think
12:48:27 [abattis]
fat_tony: amen
12:48:33 [abattis]
shepazu: patches welcome
12:48:36 [ChrisL]
yea verily
12:49:06 [abattis]
ed_work: if we agree things are thrown away when parsing to generate the DOM, both xlink:href and href, what i hear here is that the xlink:href will be thrown away
12:49:11 [abattis]
jwatt: srsly?
12:49:30 [abattis]
ChrisL: more time?
12:49:46 [abattis]
jwatt: i dont think we should throw it away, we should put both into DOM and give one precedence
12:49:55 [abattis]
ChrisL: and if one is chagned later, what happens?
12:50:01 [abattis]
jwatt: a script can set attributes for both
12:50:08 [abattis]
... or does it throw?
12:50:13 [abattis]
... there are still issues to be worked out
12:50:28 [abattis]
... on that point i prefer precedence than messing with the parser
12:50:57 [AlexD]
I agree with JWatt, allow both and add precedence, like we did for xml:id and id in Tiny.
12:50:59 [abattis]
shepazu: i want to see a more formal prposal, thats a cxomplex design descisoin for a minor use case
12:51:09 [abattis]
... and i think browser vendors would agree
12:51:18 [abattis]
... mozilla people have said this idea isnt a good solution to me
12:51:20 [abattis]
jwatt: not to me
12:51:41 [abattis]
shepazu: AlexD, that was a disaster
12:51:50 [abattis]
(lol)
12:51:58 [AlexD]
Agreed, I don't like xml:id at all.
12:52:04 [abattis]
shepazu: you have 2 dom attirbutes, why?
12:52:16 [abattis]
... what happens when you hcange the href property?
12:52:43 [abattis]
jwatt: yuou set thte attributes, and whichever is active, has precedendce. so if you have href set, use that, if you have xlnk:href set use that
12:52:49 [abattis]
... if you set both, you get both bcak
12:53:14 [AlexD]
This is where I think HTML5+svg an pure XML based SVG need to diverge. If it's XML, then xlink:href, when we integrate into HTML5, href only. But needs more discussion.
12:53:23 [abattis]
ed_work: if yo uhave both set, and serialise it back, jwatt is saying you get both, whereas before we said only 1 would comeback
12:54:26 [AlexD]
JWatt is correct here. If you have both, the DOM should represent both. But in the HTML5 case I'd argue integration should throw away xlink.
12:55:04 [abattis]
shepazu: lets not fork SVG, i dont want different behavour in SVG standalone and SVG+HTML
12:55:24 [abattis]
ed_work: AlexD makes an interesting point
12:55:29 [AlexD]
So we're screwed:-)
12:55:30 [abattis]
shepazu: i dont want differnet behaviour
12:55:48 [abattis]
ChrisL: either do it in the parsing model of each, or its the same in both
12:56:04 [abattis]
shepazu: i really want it tobe simple and unambiguous for authors and simpler for implementors
12:56:24 [abattis]
jwatt: its no problem to see if we have href, if so use it, else if xlink, use that
12:56:25 [ChrisL]
s/in both/in both, and thus we can't discard attributes/
12:56:37 [abattis]
shepazu: its not as simple as that, its what i wrot ethe page for
12:56:42 [abattis]
jwatt: link pls
12:56:46 [shepazu]
12:56:53 [AlexD]
Simplest for implementation is to just ignore the namespace prefix, so href is all that's looked at.
12:59:00 [AlexD]
BTW, there is content out there being shipped commercially that claims to be SVG and uses href with no prefix and the implementor of the UA is a Swedish cmpany...
12:59:05 [abattis]
jwatt: ed, were you obejcting to my idea?
12:59:07 [abattis]
ed_work: no
12:59:18 [abattis]
jwatt: this doesnt to me mess with what the makrup does
12:59:28 [abattis]
shepazu: it seems like deprecating href in a way
12:59:48 [abattis]
jwatt: i dont see why it encourages its use more than dougs solution
12:59:50 [abattis]
shepazu: ok
12:59:59 [abattis]
... maybe a simpler syntax is a win
13:00:07 [ed]
s/ed_work: no/ed: just restating the discussion we had a bit back, not objecting/
13:00:15 [abattis]
... but what if you have both, and you setone, and its href it takes precedence/
13:00:54 [abattis]
jwatt: if you set an attribute, thats what you want
13:01:16 [abattis]
... someone setting on attr and animating the other? a real edge case we dont need to consider highly
13:02:16 [AlexD]
We can't break DOM2/DOM3. If you setAttribute it's in the null namespace, if it's setAttributeNS then the namespace is honoured. You can't expect an SVG UA to override with extra behaviour. It pushes it into the wrong level of the DOM model.
13:02:28 [abattis]
... to restate: it seems easy to allow setting both, and see if either exists and use that, and precedence is ...
13:02:34 [abattis]
shepazu: how do you serialise that?
13:02:46 [abattis]
jwatt: serialise them both
13:02:53 [abattis]
... if they put it in for backward compatibiltly
13:03:05 [AlexD]
JWatt: Nooooooo..... Yuk!
13:03:21 [abattis]
ChrisL: before <a> name="" to id="", people duplicated the values in both attrs
13:03:27 [AlexD]
We have a document model or we don't.
13:03:53 [abattis]
jwatt: shepazu, if you think inserting is a bad thing, tell me
13:04:07 [abattis]
ChrisL: AlexD says ^^^
13:04:19 [abattis]
... i can live with jwatts prposal, i want to see it written pu
13:04:52 [abattis]
ed_work: so, for animating, say ou animate the URLs, different HREFs, with the DOM you take one out
13:04:58 [abattis]
... it makes it harder to deal with dependenceies
13:05:02 [abattis]
jwatt: not got it
13:05:06 [abattis]
... you animate an attr
13:05:14 [abattis]
ed_work: now you can animate attrs
13:05:26 [abattis]
jwatt: eh? i can put 2 animator tags in and do it separately
13:05:41 [abattis]
pdengler: now we're tlaking abotu 2.0 without types or other thing
13:05:49 [abattis]
pdengler: do we know if href should be an animated string?
13:05:58 [abattis]
... the first time we looked at href we choked
13:06:14 [abattis]
... i know what youre trying to get done, get href, i dont worry about animating this thing
13:06:29 [abattis]
... my argument against jwats proposal is that they will pile up
13:06:48 [abattis]
... if you dont set a stake in the ground about higher level constricts uts hard to nke desicsions abut the details
13:07:06 [abattis]
jwatt: simple cases like rollovers, slideshows,
13:07:12 [abattis]
pdengler: xhtml never had these?
13:07:19 [abattis]
ChrisL: yo uhad to do it with script
13:07:39 [abattis]
pdengler: is SVG for the 500 people using it to date? or the millions of web devs who know a programming pattern
13:07:48 [abattis]
pdengler: plan that stuff first
13:08:10 [abattis]
pdengler: if theres a middle ground about what jwatt needs, modifing th eprposal, im not concenred about animated types but ed_work is
13:08:24 [abattis]
... it looks like a problem, but until i see an nimated href
13:08:31 [abattis]
ChrisL: they ar ein SMIL
13:08:47 [abattis]
shepazu: are you using aniimating in a different way? a mouseover, a cilick, can be an animation
13:08:53 [abattis]
pdengler: i havent seen much SMIL content
13:09:00 [abattis]
... nor much SVG content
13:09:10 [abattis]
shepazu: its 3pm
13:09:18 [abattis]
... jwatt, what do you say?
13:09:25 [abattis]
jwatt: we have precedence
13:09:32 [abattis]
jwatt: dont drop or not set attrs
13:10:02 [ChrisL]
Resolution: accept modified href proposal with no dropped attributes, just precedence
13:10:04 [abattis]
shepazu: okay, ill modify the prposal live
13:10:17 [AlexD]
Phew
13:10:28 [abattis]
:)
13:11:31 [abattis]
shepazu: writing it right now!
13:13:24 [FelipeSanches]
FelipeSanches has joined #svg
13:13:27 [ChrisL]
13:13:29 [abattis]
... * read out what i wrote
13:14:11 [abattis]
shepazu: when serialised what hpanes?
13:14:18 [abattis]
ChrisL: you get back what you put in
13:14:49 [FelipeSanches]
I am concerned about the d attribute in the path tag. Whenever somebody wants to modify it dinamically through javascript we have to parse the d data, then generate a new d attribute, then the browser has to re-parse it again.
13:15:15 [FelipeSanches]
can we have an in-memory representation of path data that javascript could more easily manipulate?
13:15:38 [ChrisL]
@Felipe yes we plan to have a more verbose xml syntactic alternative to cover that use case
13:15:48 [FelipeSanches]
thanks
13:17:27 [abattis]
pdengler: err we discussed, not planned. memory footprints have unknown tradeoffs
13:17:28 [ChrisL]
s/plan/are considering/
13:17:32 [pdengler]
I don't agree; we have discussed potential alternatives, but haven't weighed the pros and cons
13:18:39 [abattis]
ChrisL: DOM is an API not a memory modeule
13:19:06 [abattis]
... you can give him a mini parser to do that?
13:20:28 [abattis]
BREAK TIME
13:36:15 [abattis]
pdengler: theres enough benefi tto doing the href
13:36:30 [abattis]
... to have something Just Work
13:36:47 [abattis]
... i would push hard to get this in MSIE to move from HTML development to HTML+SVG development
13:37:21 [abattis]
... they are goig to get caught on script in some cases if it uses HREF, if its inside the SVG tag, but mostly people will put the script where they are used to, in the HTML <head>
13:37:41 [abattis]
... so in the end if you dont solve this the world is a difficult place for a while bu tleads to the right model later on
13:38:04 [abattis]
... if we do it now its easier now and for later on puts a challenge on us, its the same as class and id, but for an attr thats not used as widely
13:38:11 [abattis]
... so i dont think were ready to dicuss SRC
13:38:30 [abattis]
shepazu: with the new membership of NASA in W3C, we are now literally architecture astronauts
13:38:37 [abattis]
jwatt: when did that happen?
13:38:41 [abattis]
pdengler: a few days ago
13:39:04 [abattis]
ChrisL: diffusion constraintsin vector graphics paper:
13:39:08 [ChrisL]
13:39:36 [abattis]
ChrisL: note thats are in english ;)
13:39:52 [abattis]
ChrisL: which suggests they want this Out There :)
13:41:12 [abattis]
email from Luke Kenneth Casson Leighton: "do remind them of the existence of GWTCanvas and its python port, which works even under pyjamas-desktop using DCOM to connect directly with MSHTML.DLL"
13:44:50 [abattis]
topic: svg 1.1
13:45:03 [abattis]
ed_work: whats left to be done on the spec itself?
13:45:11 [abattis]
ChrisL: im working it into shape
13:45:28 [abattis]
... there are rules for produce a tech report on the w3 website
13:45:48 [abattis]
... thats the document you saw and im getting it ready so when we are ready for publshing it can go straight
13:46:19 [abattis]
... there are other docs to do, and an internal meeting, and you effectvely go through the candidate recommentation again
13:46:31 [abattis]
s/recommentation again/recommentation process again/
13:47:00 [abattis]
ed_work: do we need a minuted resultion? anyone objecting?
13:47:23 [abattis]
ed_work: okay, we resolve to request publication of SVG 1.1 PER
13:47:40 [abattis]
Resolution: We will request publication of SVG 1.1 PER
13:47:45 [pdengler]
pdengler has joined #svg
13:47:54 [ed]
ed has joined #svg
13:47:57 [ed]
RRSAgent, pointer?
13:47:57 [RRSAgent]
See
13:49:51 [FelipeSanches]
FelipeSanches has left #svg
13:50:35 [ChrisL]
13:50:55 [ChrisL]
13:51:52 [ChrisL]
13:55:22 [abattis]
shepazu: MS passes 100% of svg tests they submitted
13:55:46 [abattis]
pdengler: opera passed 100% of their test subsmission :)
13:56:05 [abattis]
ed_work: no it didnt :)
13:56:20 [abattis]
;)
13:58:19 [shepazu]
s/MS passes 100% of svg tests they submitted/MS passes 100% of svg tests they submitted :)/
13:58:54 [ChrisL]
action: chris to request PER of SVG 1.1SE
13:58:55 [trackbot]
Created ACTION-2793 - Request PER of SVG 1.1SE [on Chris Lilley - due 2010-06-07].
14:04:08 [pdengler]
I will work on the test suite from svgdom-over-01-f.svg reverse alphabetical
14:04:29 [pdengler]
Anthony will resubmit the MSFT tests that didn't have the CVS parameter set correctly
14:09:04 [abattis]
fat_tony: so are we done with 1.1?
14:09:05 [abattis]
ed_work: yeah
14:09:19 [abattis]
ChrisL: tlaking about the week of 7th june? im free friday
14:09:24 [abattis]
shepazu: im traveling all june
14:09:42 [abattis]
ed_work: is a marathon teleconf any good?
14:09:47 [abattis]
pdengler: time overlaps are tricky
14:10:01 [abattis]
ChrisL: block time and people can bookend it
14:10:27 [abattis]
ChrisL: like a scrum, rotate through when they are available so all can participate
14:11:25 [abattis]
ed_work: i can do it whenever
14:11:27 [abattis]
fat_tony: same
14:11:42 [abattis]
ChrisL: shepazu, HTML+SVG?
14:11:56 [abattis]
shepazu: 2 more things, short ones
14:12:35 [abattis]
topic: SVG+HTML
14:12:58 [abattis]
shepazu: MSIE considered novel syntax... HTMl5 is some way from being done and the parsing algo has only 1 implementaitn thats incomplete
14:13:13 [abattis]
shepazu: from W3C process perspective its far from done
14:13:27 [abattis]
jwatt: the strategy to ship first is a problem
14:13:40 [abattis]
ChrisL: its shipped and not finalised at the same time
14:13:41 [abattis]
;)
14:13:48 [abattis]
ed_work: there's 2 impkementations
14:14:00 [ed]
s/ed_work/DS/
14:14:15 [abattis]
shepazu: there maybe 2, but 'we shipped libhtml5' doesn't conut
14:14:26 [abattis]
s/conut/count
14:14:37 [AlexD]
Are there any tests for HTMl5 parsing conformance?
14:15:00 [abattis]
pdengler: MSIE 9 hsa no plans for this, its for later. first we need to rationalise and unionise many things
14:15:35 [abattis]
pdengler: i could throw out some idea on default inlining SVG... putting an XY coordinateon a div in svg, that wont hold unless you ge tthe other stuff sorted
14:16:18 [abattis]
pdengler: we have to nail the union of the 2 specs
14:16:29 [abattis]
shepazu: if its ships its too late (?)
14:16:45 [abattis]
pdengler: it requires cooperation with the HTML group. when do they close the spec?
14:16:53 [abattis]
jwatt: its open for some time
14:17:01 [abattis]
pdengler: right
14:17:11 [abattis]
jwatt: once something ships, if we both ship HTML5 parses...
14:17:43 [abattis]
pdengler: is this a parsing problem? if so, raise them, but i wont thikn what they might be, i look at what people want to do
14:17:57 [AlexD]
Given how long it will take HTML5 to mature (i.e. PREC) then perhaps SVG needs to take some lead in an HTML(4)+SVG integration profile... HTML5 is a bit of vapourware right now really.
14:17:58 [abattis]
shepazu: these are coupled, yes.
14:18:41 [abattis]
shepazu: say you want serverside stuff, and we can imagine a html6 parser being different. parsers determine what syntax is allowed
14:19:07 [abattis]
pdengler: can a div work in a co ordinate space/
14:19:23 [abattis]
pdengler: when do we decide this is a div/
14:19:37 [abattis]
... like a div within SVG
14:20:05 [abattis]
... what does it mean to have HTML not as a foreign object in SVG?
14:20:18 [abattis]
... we are yet to dicover what people expet and how they will use SVVG in HTML
14:20:44 [abattis]
... remove the idea of forign object..?
14:20:52 [abattis]
jwatt: is this in scope of html5?
14:21:15 [abattis]
jwatt: they are only looking at parse
14:21:18 [abattis]
r level
14:23:32 [abattis]
...
14:23:59 [abattis]
shepazu: to draw this to a close, we need to go backto html5 group and say, we got these use cases....
14:24:10 [abattis]
... how productive will itbe at this point?
14:24:51 [AlexD]
There is a difficult line to tread here. Parsers may define what syntax is allowed but HTML and tag-soup has allowed all sorts of non-spec compliant to try to render something. SVG has tried to be more strict. When we join them, what will the author expect and what should we mandate?
14:25:25 [abattis]
jwatt: parsing thing, its more the CSS WG to talk to
14:26:48 [abattis]
jwatt: existing specs its not well done
14:27:13 [abattis]
jwatt: look at draft cSS spec
14:28:43 [abattis]
jwatt: need to look at CSS2.1
14:28:54 [abattis]
ChrisL: intended to bedeon thi yar
14:29:26 [abattis]
shepazu: we should consider what the WGs did
14:35:24 [abattis]
Action: pdengler to talk to MSIE team about HTML5+SVG tests
14:35:24 [trackbot]
Created ACTION-2794 - Talk to MSIE team about HTML5+SVG tests [on Patrick Dengler - due 2010-06-07].
14:37:16 [abattis]
...
14:39:01 [abattis]
shepazu: we can move forward on this in the context of SVG integration
14:39:38 [abattis]
pdengler: integration is an optional module for 2.0. its key going forward.
14:39:50 [abattis]
shepazu: its a standalone module, yes
14:40:14 [abattis]
Topic: Group Workflow
14:40:17 [shepazu]
14:40:51 [pdengler]
scribenick : pdengler
14:41:46 [FelipeSanches]
FelipeSanches has joined #svg
14:42:05 [pdengler]
shepazu: This link was set up in the context of the conversation that Patrick brought up earlier around use cases.
14:42:27 [pdengler]
shepazu: Review and make recommended changes to this
14:43:17 [pdengler]
shepazu: don't move the status of specs from proposed to approved before we have tests for those
14:43:26 [pdengler]
ed: I don't think this will work as we will have changes across the entire spec
14:44:00 [pdengler]
ed: It is a good idea to differentiate between what is proposed, and what is approved, but we don' t necessarily have anything better
14:45:40 [pdengler]
shepazu: to be clear, have all of the tests in place, not just some
14:45:55 [pdengler]
ChrisL: I share the concern that there will be cross dependencies that will be difficult to manage
14:46:14 [pdengler]
shepazu: We could have a status of 'approved pending..'
14:46:39 [pdengler]
ChrisL: We need a stage of 'being worked on, but not just proposed'
14:46:59 [pdengler]
shepazu: As part of our process of submitting specs, that we formally adopt the idea that right away we right tests for it
14:47:32 [ChrisL]
zakim, list attendees
14:47:32 [Zakim]
sorry, ChrisL, I don't know what conference this is
14:49:56 [pdengler]
anthony: For the print spec, we tried to mark up the assertions in the spec and this worked well
14:50:21 [pdengler]
anthony: We did this for the compositing spec as well, and then wrote tests against them, which made it much easier to link to assertions
14:50:23 [ChrisL]
Present: Alex, Anthony, Dave, JWatt, Doug, Patrick, Erik, Chris, Femke, Felipe, Hin-Tak, Simon
14:50:36 [ChrisL]
rrsagent, make minutes
14:50:36 [RRSAgent]
I have made the request to generate
ChrisL
14:50:56 [ChrisL]
rrsagent, make logs public
14:50:59 [ChrisL]
rrsagent, make minutes
14:50:59 [RRSAgent]
I have made the request to generate
ChrisL
14:51:12 [ChrisL]
Chair: Erik
14:51:13 [ChrisL]
rrsagent, make minutes
14:51:13 [RRSAgent]
I have made the request to generate
ChrisL
14:53:03 [shepazu]
14:54:56 [shepazu]
trackbot, stop telcon
14:54:56 [trackbot]
Sorry, shepazu, I don't understand 'trackbot, stop telcon'. Please refer to
for help
15:04:22 [fat_tony]
fat_tony has left #svg
15:25:27 [FelipeSanches]
FelipeSanches has left #svg
15:53:33 [shepazu]
Rue du Parnasse 19, 1050 Ixelles
15:53:55 [shepazu]
Renaissance Brussels Hotel
16:06:40 [Zakim]
ed, you asked to be reminded at this time about whatever
16:23:30 [nomis]
nomis has joined #svg
21:41:18 [karl]
karl has joined #svg
23:52:00 [FelipeSanches]
FelipeSanches has joined #svg
23:52:10 [FelipeSanches]
FelipeSanches has left #svg | http://www.w3.org/2010/05/31-svg-irc | CC-MAIN-2015-18 | refinedweb | 8,102 | 65.25 |
Hi, Sorry, I forgot to reply to this earlier. On Fri, Feb 16, 2018 at 10:10:59AM -0600, Eric Blake wrote: > On 02/16/2018 07:53 AM, Vladimir Sementsov-Ogievskiy wrote: > > Good idea. But it would be tricky thing to maintain backward > > compatibility with published versions of virtuozzo product. And finally > > our implementation would be more complex because of this simplification. > > > Hm. Finally, you suggested several changes (including already merged > > 56c77720 :( ). Suggestions are logical. But if they will be accepted, we > > (Virtuozzo) will have to invent tricky hard-to-maintain code, to > > distinguish by third factors our already published versions. Hrm. I wasn't aware you'd already published those versions; if you had told us, we could've reviewed the spec at that point and either merge it or update it to incorporate whatever changes you think seem like they are necessary. Note that the section "Experimental extensions" contains the following wording: In addition to the normative elements of the specification set out herein, various experimental non-normative extensions have been proposed. These may not be implemented in any known server or client, and are subject to change at any point. A full implementation may require changes to the specifications, or cause the specifications to be withdrawn altogether. [...] Implementors of these extensions are strongly suggested to contact the mailinglist in order to help fine-tune the specifications before committing to a particular implementation. i.e., what's in an "extension-" branch can be described as "we're thinking about it and it will probably happen as written, but we're not entirely sure yet". The idea behind this is that we don't want to limit ourselves to things that haven't been implemented (but that the fact of "implementing something" causes it to get written into stone, sortof). This is different from how most standards bodies work, I'm sure, but it seemed to work so far, and I wish you had let us know that the work you were doing was about to be reaching customers. Anyway. [...] > Also, the Virtuozzo product hasn't been mentioned on the NBD list, and while > you are preparing patches to the public qemu based on the Virtuozzo product, > I'm not sure if there is a public repository for the existing Virtuozzo > product out in the wild. Is your product using NBD_OPT_LIST_META_CONTEXT, > or _just_ NBD_OPT_SET_META_CONTEXT? +1. What's published currently? [...] > Or, we can revert the change in commit 56c77720, and keep > NBD_REPLY_TYPE_BLOCK_STATUS at 5 (it leaves a hole in the NBD_REPLY_TYPE > numbering, where 3 and 4 might be filled in by other future extensions, or > permanently skipped). This works IF there are no OTHER incompatible changes > made to the rest of the block status extension as part of promoting it to > current (where we still haven't finished that debate, given my question on > whether 32-bit lengths and colon-separated namespace:leaf in a single string > is the best representation). > > So, I'd like some feedback from Alex or Wouter on which alternatives seem > nicest at this point. I'm thinking that reverting at least the number change seems like a good idea. If Vladimir can shed some light on what's been published so far, we can see what damage has been done and try to limit further damage. It makes no sense to ignore that the spec has been implemented; the whole point of writing a spec is so that third parties can implement it and be compatible. If we ignore that just because there was a misunderstanding, then I think we're throwing away the kid with the bathwater. Since I don't think a gap in numbers is that much of a problem, I'm happy reverting the renumbering part of 56c77720 and keep it at 5. I'd also like to know what it is exactly that Virtuozzo implemented, so we can update the extension-blockstatus (if necessary) and then merge that to master. However, for future reference, Vladimir, I would prefer it if you could give us a heads-up if you're getting close to releasing something to the public that's still in an experimental branch, so that we can make updates if necessary and merge it to master. Thanks, -- Could you people please use IRC like normal people?!? -- Amaya Rodrigo Sastre, trying to quiet down the buzz in the DebConf 2008 Hacklab | https://lists.debian.org/nbd/2018/02/msg00018.html | CC-MAIN-2021-17 | refinedweb | 733 | 56.39 |
ARM design on the mbed Integrated Development Environment – Part 2: program design and structure
Advertisement
Editor’s Note: In Part 2, excerpted from their book Fast and effective embedded systems design: Applying the ARM mbed , authors Tim Wilmshurstand Rob Toulson introduce a number of C/C++ programming methods for ARM designs using the open source mbed integrated development environment.
There are many different approaches to development in embedded systems. As noted in Part 1, with the mbed there is no software to install, and no extra development hardware needed for program download. All software tools are placed online so that you can compile and download wherever you have access to the Internet.
Notably, there is a C++ compiler and an extensive set of software libraries used to drive the peripherals. Thus, also as noted in Part 1, there is no need to write code to configure peripherals, which in some systems can be very time consuming.
BUT, although this book does not assume that you have any knowledge of C or C++, you have an advantage if you do.
The mbed Compiler and API
The mbed development environment uses the ARM RVDS (RealView Development Suite) compiler, currently Version 4.1. All features of this compiler relevant to the mbed are available through the mbed portal .
One thing that makes the mbed special is that it comes with an application programming interface (API). In brief, this is the set of programming building blocks, appearing as C++ utilities, which allow programs to be devised quickly and reliably. Therefore, we will be writing code in C or C++, but drawing on the features of the API.
Using C/C++
As just mentioned, the mbed development environment uses a C++ compiler.That means that all files will carry the .cpp (Cplusplus) extension. C, however, is a subset of C++, and is simpler to learn and apply. This is because it does not use the more advanced ‘object-oriented’ aspects of C++.
In general, C code will C compile on a C++ compiler, but not the other way round. C is usually the language of choice for any embedded program of low or medium complexity, so will suit us well here. For simplicity, therefore, we aim to use only C in the programs we develop. It should be recognized, however, that the mbed API is written in C++ and uses the features of that language to the full. We will aim to outline any essential features when we come to them.
Program Design and Structure
There are numerous challenges when tackling an embedded system design project. It is usually wise first to consider the software design structure, particularly with large and multi-functional projects. It is not possible to program all functionality into a single control loop, so the approach for breaking up code into understandable features should be well thought out. In particular, it helps to ensure that the following can be achieved:
- that code is readable, structured and documented
- that code can be tested for performance in a modular form
- that development reuses existing code utilities to keep development time short
- that code design supports multiple engineers working on a single project
- that future upgrades to code can be implemented efficiently.
There are various C/C++ programming techniques that enable these design requirements to be considered, as discussed here, including: functions, flow charts, pseudocode and code reuse.
The role of Functions
A function is a portion of code within a larger program. The function performs a specific task and is relatively independent of the main code. Functions can be used to manipulate data; this is particularly useful if several similar data manipulations are required in the program. Data values can be input to the function and the function can return the result to the main program. Functions, therefore, are particularly useful for coding mathematical algorithms, look-up tables and data conversions, as well as control features that may operate on a number of different parallel data streams. It is also possible to use functions with no input or output data, simply to reduce code size and to improve readability of code. Figure 6.1 illustrates a function call.
There are several advantages when using functions. First, a function is written once and compiled into one area of memory, irrespective of the number of times that it is called from the main program, so program memory is reduced. Functions also allow clean and manageable code to be designed, allowing software to be well structured and readable at a number of levels of abstraction. The use of functions also enables the practice of modular coding, where teams of software engineers are often required to develop large and advanced applications. Writing code with functions therefore allows one engineer to develop a particular software feature, while another engineer may take responsibility for something else.
Using functions is not always completely beneficial, however. There is a small execution time overhead in storing program position data and jumping and returning from the function, but this should only be an issue for consideration in the most time-critical systems. Furthermore, it is possible to ‘nest’ functions within functions, which can sometimes make software challenging to follow. A limitation of C functions is that only a single value can be returned from the function, and arrays of data cannot be passed to or from a function (only single-value variables can be used). Working with functions and modular techniques therefore requires a considered software structure to be designed and evaluated before programming is started.
Using Flowcharts to Define Code Structure
It is often useful to use a flowchart to indicate the operation of program flow and the use of functions. Code flow can be designed using a flowchart prior to coding. Figure 6.2 shows some of the flowchart symbols that are used.
For example, take the following software design specification:
Design a program to increment continuously the output of a seven-segment numerical light-emitting diode (LED) display (as shown in Figure 6.3 , and similar to the one used in Part 1) through the numbers 0 to 9, then reset back to 0 to continue counting. This includes:
- Use a function to convert a hexadecimal counter byte A to the relevant seven- segment LED output byte B.
- Output the LED output byte to light the correct segment LEDs.
- If the count value is greater than 9, then reset to zero.
- Delay for 500 ms to ensure that the LED output counts up at a rate that is easily visible.
The output of the seven-segment display has been discussed previously in Part 1 and in particular in Table 3.4. A feasible software design is shown in Figure 6.4 .
Flowcharts allow us to visualize the order of operations of code and to make judgments on which sections of a program may require the most attention or take the most effort to develop. They also help with communicating a potential design with non-engineers, which may hold the key to designing a system that meets a very detailed specification.Pseudocode
Pseudocode consists of short, English phrases usedto explain specific tasks within a program. Ideally, pseudocode shouldnot include keywords in any specific computer language. Pseudocodeshould be written as a list of consecutive phrases; we can even drawarrows to show looping processes. Indentation can be used to show thelogical program flow in pseudocode.
Writing pseudocode saves timelater during the coding and testing stage of a program’s developmentand also helps communication among designers, coders and projectmanagers. Some projects may use pseudocode for design, others may useflowcharts, and some a combination of both.
The software design shown by the flowchart in Figure 6.4 could also be described in pseudocode as shown in Figure 6.5 below
Notethat the functions SegConvert( ) and Delay( ) are defined elsewhere,for example in a separate ‘utilities’ file, authored by a differentengineer. Function SegConvert( ) could implement a simple look-up tableor number of if statements that assigns the suitable value to B.
Working with Functions on the mbed
Implementing a Seven-Segment Display Counter. Program Example 6.1 below shows a program which implements the designs described by theflowchart in Figure 6.4 and the pseudocode shown in Figure 6.5.
Itapplies some of the techniques first used in Program Example 3.5 inPart 1, but goes beyond these. The main design requirement is that aseven-segment display is used to count continuously from 0 to 9 and loopback to 0. Declarations for the BusOut object and the A and Bvariables, as well as the SegConvert( ) function prototype, appear earlyin the program. It can be seen that the main( ) program function isfollowed by the SegConvert( ) function, which is called regularly fromwithin the main code. Notice in the line
B=SegConvert(A); // Call function to return B
that B can immediately take on the return value of the SegConvert( ) function.
Notice the SegConvert( ) function the final line immediately below, which applies the return keyword:
return SegByte;
Thisline causes program execution to return to the point from which thefunction was called, carrying the value SegByte as its return value. Itis an important technique to use once you start writing functions thatprovide return values. Notice that SegByte has been declared as part ofthe function prototype early in the program listing.
Connect aseven-segment display to the mbed and implement Program Example 6.1. Thewiring diagram for a seven-segment LED display was shown previously inFigure 3.10 in Part 1. Verify that the display output continuouslycounts from 0 to 9 and then resets back to 0. Ensure that you understandhow the program works by cross-referencing with the flowchart andpseudocode designs shown previously.
Function Reuse
Nowthat we have a function to convert a decimal value to a seven-segmentdisplay byte, we can build projects using multiple seven-segmentdisplays with little extra effort. For example, we can implement asecond seven-segment display (Figure 6.6 ) by simply defining its mbed BusOut declaration and calling the same SegConvert( ) function as before.
Itis possible to implement a counter program that counts from 00 to 99 bysimply modifying the main program code to that shown in Program Example 6.2 .Note that the SegConvert( ) function previously defined in ProgramExample 6.1 is also required to be copied (reused) in this example. Notealso that a slightly different programming approach is used; here weuse two for loops to count each of the tens and units values.
Usingtwo seven-segment displays, with pin connections shown in Figure 6.6above, implement Program Example 6.2 and verify that the display outputcounts continuously from 00 to 99 and then resets back to 0. Review theprogram design and familiarize yourself with the method used to countthe tens and units digits each from 0 to 9.
A more advancedprogram could also read two numerical values from a host terminalapplication and display these on two seven-segment displays connected tothe mbed. The program can therefore display any integer number between00 and 99, as required by user key presses.
An example programdesign uses four functions to implement the host terminal output onseven-segment displays. The four functions are as follows:
- SegInit( ) e to set up and initialize the seven-segment displays
- HostInit( ) e to set up and initialize the host terminal communication
- GetKeyInput( ) e to get keyboard data from the terminal application
- SegConvert( ) e function to convert a decimal integer to a seven-segment display data byte.
Wewill use the mbed universal serial bus (USB) interface to communicatewith the host PC, and two seven-segment displays, as in the previousexercise.
For the first time now we come across a method forcommunicating keyboard data and display characters, using ASCII codes.The term ASCII refers to the American Standard Code for InformationInterchange method for defining alphanumeric characters as 8-bit values.Each alphabet character (lower and upper case), number (0e9) and aselection of punctuation characters are all described by a uniqueidentification byte, i.e. the ‘ASCII value’. Therefore, for example,when a key is pressed on a computer keyboard, its ASCII byte iscommunicated to the PC. The same applies when communicating withdisplays.
The ASCII byte for numerical characters has the higherfour bits set to value 0x3 and the lower four bits represent the valueof the numerical key which is pressed (0x0 to 0x9). Numbers 0e9 aretherefore represented in ASCII as 0x30 to 0x39.
To convert theASCII byte returned by the keyboard to a regular decimal digit, thehigher four bits need to be removed. We do this by logically ANDing theASCII code with a bitmask, a number with bits set to 1 where we want tokeep a bit in the ASCII, and set to 0 where we want to force the bit to0. In this case, we apply a bitmask of 0x0F. The logical AND applies theoperator ‘&’ and appears in the line:
return (c&0x0F); // apply bit mask to convert to decimal, and return
Example functions and program code are shown in Program Example 6.3 .
Once again, the function SegConvert( ), as shown in Program Example 6.1, should be added to compile the program.
Part 1: The basics of the mbed IDE
Part 3: More complex program functions
Tim Wilmshurst ,head of Electronics at the University of Derby, led the ElectronicsDevelopment Group in the Engineering Department of Cambridge Universityfor a number of years, before moving to Derby. His design career hasspanned much of the history of microcontrollers and embedded systems.
Rob Toulson is Research Fellow at Anglia Ruskin University in Cambridge. Aftercompleting his PhD, Rob spent a number of years in industry, where heworked on digital signal processing and control systems engineeringprojects, predominantly in audio and automotive fields. He then moved toan academic career, where his main focus is now in developingcollaborative research between the technical and creative industries.
This article is excerpted from Fast and effective embedded systems design: Applying the ARM mbed byRob Toulsonand Tim Wilmshurst, used with permission from Newnes, adivision of Elsevier. Copyright 2012. All rights reserved. For moreinformation on this title and other similar books, visit .
Advertisement | https://www.embedded.com/arm-design-on-the-mbed-integrated-development-environment-part-2-program-design-and-structure/ | CC-MAIN-2022-40 | refinedweb | 2,337 | 52.7 |
How do I read the data from the XMLdataBank through groovy and then parse that XML
I have a SOAP request which gives XML response. I created one XMLdatabank and mapped the respective node which has children to a variable in the XMLDatabank. In the extension tool I try reading that data of that variable through groovy but it is returning NULL.
I was able to do it with the Json response but not with XML.
import com.parasoft.api.*;
public void sample(Object value, ExtensionToolContext context){
String garbage= context.getValue("Generated Data Source","Response");
Application.showMessage("The data is: " + garbage);
}
0
The data bank column "Response" either doesn't exist or wasn't populated. The XML Data Bank has to be configured with an extraction with your desired column name. The XPath used for your extraction must be correct (it will be different for XML than JSON). Additionally, the Data Bank needs to run at least once to populate the data bank column with a value before your script is executed.
Yes I ran the test and I was able to see the data in the Databank and once I mapped the node to a variable and clicked on evaluate I was able to see the data too. But in the script I am it is returning Null.
In the Data Xank XPath settings dialog under the Data Source Column section, are you using "Custom column name" or "Variable"? context.getValue("Generated Data Source","Response") is what you use for "Custom column name". If instead you are writing the value to a test variable then you would just use context.getValue("Response") assuming your test variable is named "Response".
I am also curious to know why you want to parse the XML from a Groovy script in the first place. There are often better alternatives than scripting.
Hi Kesary,
You can refer below Jython script which works for me:
from soaptest.api import *
from com.parasoft.api import *
from java.util import *
def sample(input, context):
garbage= str(context.getValue("Generated Data Source", "Response"))
Application.showMessage("The data is: " + garbage)
return garbage
*Key point is to make sure Data source column name must be 'Response' in the Xml Data Bank
I want to clarify that Groovy works fine too, like your original script. Switching to another scripting language shouldn't solve anything. The issue is one of the things I mentioned in my earlier comments. The data bank column "Response" either doesn't exist or wasn't populated or you are really writing to a test variable in which case your script is calling the wrong method.
Hi benken,
I have found what was causing the issue. As I was running the test separately and extension tool separately I was getting Null response as the data in the "response" variable was wiped off.
To make things work I must run the thing that creates the generated datasource and that executes the extension tool as a unit and not individually.
Thank you so much all for the suggestions
| https://forums.parasoft.com/discussion/comment/9260 | CC-MAIN-2018-09 | refinedweb | 508 | 64.2 |
Comments describe what is happening inside a program so that a person looking at the source code does not have difficulty figuring it out.
In this article, you’ll learn:
- How to add comments in your Python code
- The need of the comments
- What are the inline comments, block comments, and multi-line comments
- The use of docstring comments.
Table of contents
What is Comment in Python?
The comments are descriptions that help programmers to understand the functionality of the program. Thus, comments are necessary while writing code in Python.
In Python, we use the hash (
#) symbol to start writing a comment. The comment begins with a hash sign (
#) and whitespace character and continues to the end of the line.
Many programmers commonly use Python for task automation, data analysis, and data visualization. Also, Python has been adopted by many non-programmers such as analysts and scientists.
In a team, many programmers work together on a single application. Therefore, if you are developing new code or modifying the existing application’s code, it is essential to describe the purpose behind your code using comments.
For example, if you have added new functions or classes in the source code, describe them. It helps other colleagues understand the purpose of your code and also helps in code review.
Apart from this, In the future, it helps to find and fix the errors, improve the code later on, and reuse it in many different applications.
Writing comments is considered a good practice and required for code quality.
If a comment is found while executing a script, the Python interpreter completely ignores it and moves to the next line.
Example:
x = 10 y = 20 # adding two numbers z = x + y print('Sum:', z) # Output 30
As you can see in the above program, we have added the comment ‘adding two numbers’.
Single-line Comment
Python has two types of comments single-line and multi-line comments.
In Python, single-line comments are indicated by a hash sign(
#). The interpreter ignores anything written after the # sign, and it is effective till the end of the line.
Primarily these comments are written over Python statements to clarify what they are doing.
Example: Writing single-line Comments
# welcome message print('Welcome to PYnative...')
Output:
Welcome to PYnative...
Note: By considering the readability of a code, limit the comment line to a maximum of 79 characters as per the PEP 8 style guide.
Multi-Line Comments
In Python, there is no separate way to write a multi-line comment. Instead, we need to use a hash sign at the beginning of each comment line to make it a multi-line comment
Example
# This is a # multiline # comment print('Welcome to PYnative...')
Output
Welcome to PYnative...
Add Sensible Comments
A comment must be short and straightforward, and sensible. A comment must add value to your code.
You should add comments to give code overviews and provide additional information that is not readily available in the code itself.
Comments should contain only information that is relevant to reading and understanding the program.
Let’s take the following example.
# Define list of student names names = ['Jess', 'Emma', 'Kelly'] # iterates over name list and prints each name for student in names: print(student, end=' ')
As you can see, the code is self-explanatory, and adding comments for such code is unnecessary. It would be best if you avoided such scenarios.
Now, let’s take the second example where we have demonstrated the correct way to write comments.
# Returns welcome message for a customer by customer name and location # param name - Name of the customer # param region - location # return - Welcome message def greet(name, region): message = get_message(region) return message + " " + name # Returns welcome message by location # param region - location def get_message(region): if (region == 'USA'): return 'Hello' elif (region == 'India'): return 'Namaste' print(greet('Jessa', 'USA'))
Inline Comments
We can add concise comments on the same line as the code they describe but should be shifted enough to separate them from the statements for better readability. It is also called a trailing comment.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a
# and a single space.
Inline comments are useful when you are using any formula or any want to explain the code line in short.
If one or more lines contain the short comment, they should all be indented to the same tab setting.
Example:
def calculate_bonus(salary): salary = salary * 7.5 # yearly bonus percentage 7.5
Block Comments
Block comments are used to provide descriptions of files, classes, and functions. We should add block comments at the beginning of each file and before each method.
Add a black line after the block comment to set it apart from the rest of the code.
Example:
# Returns welcome message for a customer by customer name and location # param name - Name of the customer # param region - location # return - Welcome message def greet(name, region): message = get_message(region) return message + " " + name
Docstring Comments
Docstring comments describe Python classes, functions, constructors, methods. The docstring comment should appear just after the declaration. Although not mandatory, this is highly recommended.
Conventions for writing good documentation strings are mentioned in PEP 257
- The docstring comment should appear just after the declaration.
- A docstring can be a single line or a multi-line comment.
- Docstring should begin with a capital letter and end with a period.
Example: docstring in function
def bonus(salary): """Calculate the bonus 10% of a salary .""" return salary * 10 / 100
Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does.
Commenting Out Code for Testing
If you are getting a runtime error or not getting an expected output and cannot figure out which part of the code is causing the problem, you can comment out the specific block or a line to quickly figure out the problem.
Example:
def greet(name, region): # below code is comment for testing # message = get_message(region) message= 'Hello' return message + " " + name def get_message(region): if (region == 'USA'): return 'Hello' elif (region == 'India'): return 'Namaste' print(greet('Jessa', 'USA'))
Using String Literals for Multi-line Comments
As we discussed, there is no unique way to write multi-line comments. We can use multi-line strings (triple quotes) to write multi-line comments. The quotation character can either be ‘ or “.
Python interpreter ignores the string literals that are not assigned to a variable.
Example
''' I am a multiline comment! ''' print("Welcome to PYnative..")
In the above example, the multi-line string isn’t assigned to any variable, so the interpreter ignores it. Even it is not technically a multi-line comment.
Summary
The comments are descriptions that help programmers to understand the functionality of the program. Thus, comments are necessary while writing code in Python.
- Use the hash (#) symbol to start writing a comment in Python
- Comments should contain only information that is relevant to reading and understanding the program.
- Python dosen’t support multi-line comments. we need to use a hash sign at the beginning of each comment line to make it a multi-line comment
- Keep comments indentation uniform and match for best readability.
- Add Docstring to functions and classes | https://pynative.com/python-comments/ | CC-MAIN-2021-39 | refinedweb | 1,232 | 54.52 |
Given:
// CPP program to minimize number of // unique characters in a string. #include <bits/stdc++.h> using namespace std; // Utility function to find minimum // number of unique characters in string. void minCountUtil(string A, string B, unordered_map<char, int>& ele, int& ans, int ind) { // If entire string is traversed, then // compare current number of distinct // characters in A with overall minimum. if (ind == A.length()) { ans = min(ans, (int)ele.size()); return; } // swap A[i] with B[i], increase count of // corresponding character in map and call // recursively for next index. swap(A[ind], B[ind]); ele[A[ind]]++; minCountUtil(A, B, ele, ans, ind + 1); // Backtrack (Undo the changes done) ele[A[ind]]--; // If count of character is reduced to zero, // then that character is not present in A. // So remove that character from map. if (ele[A[ind]] == 0) ele.erase(A[ind]); // Restore A to original form. // (Backtracking step) swap(A[ind], B[ind]); // Increase count of A[i] in map and // call recursively for next index. ele[A[ind]]++; minCountUtil(A, B, ele, ans, ind + 1); // Restore the changes done // (Backtracking step) ele[A[ind]]--; if (ele[A[ind]] == 0) ele.erase(A[ind]); } // Function to find minimum number of // distinct characters in string. int minCount(string A, string B) { // Variable to store minimum number // of distinct character. // Initialize it with length of A // as maximum possible value is // length of A. int ans = A.length(); // Map to store count of distinct // characters in A. To keep // complexity of insert operation // constant unordered_map is used. unordered_map<char, int> ele; // Call utility function to find // minimum number of unique // characters. minCountUtil(A, B, ele, ans, 0); return ans; } int main() { string A = "abaaa"; string B = "bbabb"; cout << minCount(A, B); return 0; }
2
Time Complexity: O(2n) : SahilMalik1
Recommended Posts:
- Count all possible paths between two vertices
-
- Rat in a Maze with multiple steps or jump allowed
- Fill 8 numbers in grid with given conditions
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. | https://www.geeksforgeeks.org/minimize-number-unique-characters-string/ | CC-MAIN-2018-39 | refinedweb | 344 | 66.13 |
In this tutorial, we will understand the concept of ngrams in NLP and why it is used along with its variations like Unigram, Bigram, Trigram. Then we will see examples of ngrams in NLTK library of Python and also touch upon another useful function everygram. So let us begin.
What is n-gram Model
In natural language processing n-gram is a contiguous sequence of n items generated from a given sample of text where the items can be characters or words and n can be any numbers like 1,2,3, etc.
For example, let us consider a line – “Either my way or no way”, so below is the possible n-gram models that we can generate –
As we can see using the n-gram model we can generate all possible contiguous combinations of length n for the words in the sentence. When n=1, the n-gram model resulted in one word in each tuple. When n=2, it generated 5 combinations of sequences of length 2, and so on.
Similarly for a given word we can generate n-gram model to create sequential combinations of length n for characters in the word. For example from the sequence of characters “Afham”, a 3-gram model will be generated as “Afh”, “fha”, “ham”, and so on.
Due to their frequent uses, n-gram models for n=1,2,3 have specific names as Unigram, Bigram, and Trigram models respectively.
Use of n-grams in NLP
- N-Grams are useful to create features from text corpus for machine learning algorithms like SVM, Naive Bayes, etc.
- N-Grams are useful for creating capabilities like autocorrect, autocompletion of sentences, text summarization, speech recognition, etc.
Generating ngrams in NLTK
We can generate ngrams in NLTK quite easily with the help of ngrams function present in nltk.util module. Let us see different examples of this NLTK ngrams function below.
Unigrams or 1-grams
To generate 1-grams we pass the value of n=1 in ngrams function of NLTK. But first, we split the sentence into tokens and then pass these tokens to ngrams function.
As we can see we have got one word in each tuple for the Unigram model.
from nltk.util import ngrams n = 1 sentence = 'You will face many defeats in life, but never let yourself be defeated.' unigrams = ngrams(sentence.split(), n) for item in unigrams: print(item)
('You',) ('will',) ('face',) ('many',) ('defeats',) ('in',) ('life,',) ('but',) ('never',) ('let',) ('yourself',) ('be',) ('defeated.',)
Bigrams or 2-grams
For generating 2-grams we pass the value of n=2 in ngrams function of NLTK. But first, we split the sentence into tokens and then pass these tokens to ngrams function.
As we can see we have got two adjacent words in each tuple in our Bigrams model.
from nltk.util import ngrams n = 2 sentence = 'The purpose of our life is to happy' unigrams = ngrams(sentence.split(), n) for item in unigrams: print(item)
('The', 'purpose') ('purpose', 'of') ('of', 'our') ('our', 'life') ('life', 'is') ('is', 'to') ('to', 'happy')
Trigrams or 3-grams
In case of 3-grams, we pass the value of n=3 in ngrams function of NLTK. But first, we split the sentence into tokens and then pass these tokens to ngrams function.
As we can see we have got three words in each tuple for the Trigram model.
from nltk.util import ngrams n = 3 sentence = 'Whoever is happy will make others happy too' unigrams = ngrams(sentence.split(), n) for item in unigrams: print(item)
('Whoever', 'is', 'happy') ('is', 'happy', 'will') ('happy', 'will', 'make') ('will', 'make', 'others') ('make', 'others', 'happy') ('others', 'happy', 'too')
Generic Example of ngram in NLTK
In the example below, we have defined a generic function ngram_convertor that takes in a sentence and n as an argument and converts it into ngrams.
from nltk.util import ngrams def ngram_convertor(sentence,n=3): ngram_sentence = ngrams(sentence.split(), n) for item in ngram_sentence: print(item)
sentence = "Life is either a daring adventure or nothing at all" ngram_convertor(sentence,3)
('Life', 'is', 'either') ('is', 'either', 'a') ('either', 'a', 'daring') ('a', 'daring', 'adventure') ('daring', 'adventure', 'or') ('adventure', 'or', 'nothing') ('or', 'nothing', 'at') ('nothing', 'at', 'all')
NLTK Everygrams
NTK provides another function everygrams that converts a sentence into unigram, bigram, trigram, and so on till the ngrams, where n is the length of the sentence. In short, this function generates ngrams for all possible values of n.
Let us understand everygrams with a simple example below. We have not provided the value of n, but it has generated every ngram from 1-grams to 5-grams where 5 is the length of the sentence, hence the name everygram.
from nltk.util import everygrams message = "who let the dogs out" msg_split = message.split() list(everygrams(msg_split))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out'), ('who', 'let', 'the'), ('let', 'the', 'dogs'), ('the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs'), ('let', 'the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs', 'out')]
Converting data frames into Trigrams
In this example, we will show you how you can convert a dataframes of text into Trigrams using the NLTK ngrams function.
import pandas as pd df=pd.read_csv('file.csv') df.head()
from nltk.util import ngrams def ngramconvert(df,n=3): for item in df.columns: df['new'+item]=df[item].apply(lambda sentence: list(ngrams(sentence.split(), n))) return df
new_df = ngramconvert(df,3) new_df.head()
(Bonus) Ngrams in Textblob
Textblob is another NLP library in Python which is quite user-friendly for beginners. Below is an example of how to generate ngrams in Textblob
from textblob import TextBlob data = 'Who let the dog out' num = 3 n_grams = TextBlob(data).ngrams(num) for grams in n_grams: print(grams)
['Who', 'let', 'the'] ['let', 'the', 'dog'] ['the', 'dog', 'out']
- Also Read – Learn Lemmatization in NTLK with Examples
- Also Read – NLTK Tokenize – Complete Tutorial for Beginners
- Also Read – Complete Tutorial for NLTK Stopwords
- Also Read – Beginner’s Guide to Stemming in Python NLTK
Reference – NLTK Documentation | https://machinelearningknowledge.ai/generating-unigram-bigram-trigram-and-ngrams-in-nltk/ | CC-MAIN-2022-33 | refinedweb | 1,001 | 58.32 |
main()
int main()or
int main(int argc, char* argv[]).
system("color E8");
gradeis
94.45?
elsestatement cannot have a expression, it is literally:
scanf, make use of the value it returns, to see that it worked. Always initialise your variables with something, not necessarily zero. I find some invalid value a good idea - say a negative number in this case - that way when a result is negative it means no new value was assigned to a variable.
constinteger values known at compile time, so no good here. But braces are always a good idea, even though they aren't technically needed here, I always do them even when there is one statement.
if(); /* or */ for();
using namespace std;and
doloops. The latter can always be written as a while loop, albeit at the expense of 1 more variable, and that would be less error prone.
using namespace std;in any file other than the file that has the main function. Yes, you could use a while loop instead of the do, but they are both equally error prone because you could easily forget to put the toggle statement in the loop to make the control variable false to break out of the loop.
if(); /* and */ for();wasn't to illustrate a null statement, but the rather common beginner mistake of doing
if(); /* or */ for();because of always remembering the statement that most books have about lines always ending with a semicolon. | http://www.cplusplus.com/forum/beginner/140664/ | CC-MAIN-2016-50 | refinedweb | 242 | 68.81 |
Here is something I needed recently that other people have been tweeting about needing, too:
This could also a place to collect other ways to do it.
Here is something I needed recently that other people have been tweeting about needing, too:
This could also a place to collect other ways to do it.
Continuing my experiment using Stan in IPython, here is a notebook to do a bit of the eight schools example from the RStan Getting Started Guide..
I came across a long blog about how to make ipython notebooks more aesthetically pleasing recently, and I think there is a lot to be learned there.
The good news is that you can try this out on a notebook-by-notebook basis with a little trick. Just drop this into a cell in any IPython notebook:
import IPython.core.display IPython.core.display.HTML(""" div.input { width: 105ex; /* about 80 chars + buffer */ } div.text_cell { width: 105ex /* instead of 100%, */ } div.text_cell_render { /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/ font-family: "Charis SIL", serif; /* Make non-code text serif. */ line-height: 145%; /* added for some line spacing of text. */ width: 105ex; /* instead of 'inherit' for shorter lines */ } /* Set the size of the headers */ div.text_cell_render h1 { font-size: 18pt; } div.text_cell_render h2 { font-size: 14pt; } .CodeMirror { font-family: Consolas, monospace; } """)
Filed under Uncategorized | http://healthyalgorithms.com/tag/ipython/ | CC-MAIN-2013-48 | refinedweb | 225 | 56.66 |
This is the mail archive of the insight@sourceware.org mailing list for the Insight project.
*** No rule to make... libtk8.0.a ???
? second
[Fwd: Cron <gdbadmin@sources> sh $HOME/ss/do-all-gdb-snapshots]
[Fwd: GDB 5.2 branch created]
[PATCH RFA] for NetBSD host, use RPATH to add X lib dir.
[PATCH] add vxworks targaet
[PATCH] Allow debugging of exes with no debug info
[PATCH] breakpoint table left-justify
[PATCH] can't find files? lookup_symtab change
[PATCH] ChangeLog->ChangeLog-2001
[patch] Check CLI_SRC and MI_SRC for _initialize_*()
[PATCH] console.test: make it do something
[PATCH] Delete Console:get_text and add Console:test
[PATCH] Fix itcl install "error"
[Patch] Fix Source-Navigator X-Ref on Tcl8.3.
[patch] fix srctextwin warning
[patch] fix srcwin test 5.1
[PATCH] Fix target output in console window
[PATCH] Fix tclIndex generation
[PATCH] Fix typo in SrcWin::location
[patch] generic cleanups
[patch] generic includes cleanup
[PATCH] make sure transient's master exists
[PATCH] Memory window optimization
[patch] memwin race condition
[Patch] Move line number and address display.
[PATCH] pass varobj errors
[PATCH] Remove cygnus.gif
[PATCH] Remove REGISTER_BYTES
[PATCH] return errors from varobj_get_value
[PATCH] Set bpwin initial size
[PATCH] srcwin search widget removal
[PATCH] tix build problems
[Patch] Tix shared library install issue.
[patch] tweek display of multiple BPs on same line
[PATCH] Update c/c++ varobj testsuite
[RFA] balloon.tcl
[RFA] breakpoint balloon info
[RFA] Change Windows menu font.
[RFA] debug window fix
Re: [RFA] fix session breakpoints
[RFA] gdbtk-cmds.c: tm_print_insn
[RFA] Ignore toplevel RANLIB in tcl/tk
[RFA] iwidgets: update and add "-fraction" option
[RFA] most-recently used file fix
[RFA] Move "search in editor" entry box.
[rfa] Move ``typedef value_ptr'' to gdbtk-wrapper.h
[RFA] print_frame_info_listing_hook cleanup
[RFA] readline cleanup
[RFA] Recognize unqualified itcl commands for auto_mkindex
[RFA] Remove src-font
[RFA] Run button - second try
[RFA] Sorting symbols. Again.
[RFA] source window focus patch
[RFC] Plugin tweaks
Adding Registers
Antw: ? second
ARM angel serial debugger don't work
ARM simulation support
Build failure: Where is 'struct cmd_list_element' defined?
Building CrossGCC for ARM ...
Code display question ( RE GCC - save-temps )
Console Window Logging.
FW: Default installation in kickstart must be in GUI mode
Re- DevPascal and devC++ debugger
External Program interaction with Insight
Re: ezmlm probe
Fix for illegal memory access in itk
Re: gdb 5.2 branch gcc v3.0.3 compiler errors
Re: GDB CVS won't build on OSF4.0's cc
GDB error for angel on ARM oki board
Re: gdb/Insight and WinNT problem
How to build Insight on Windows 9x
Insight 5.0 won't start after a remote target added
Insight feature request
Insight vs tcl vs tk et.al. on gdb_5_2-branch
Insight5.1 with target dbug
int 3 dialog box
Memory interpretation of calues via Memory Window
My updated resume
new photos from my party!
Output of printf command
Patch for fix libgui compile under VC++
Patch ping
Patch to add Motorola dBUG monitor to Insight GUI
Re: patch to add vxworks target to insight gui
Re: Patch to get rid of error when closing last window
Patch: Fix Windows Crashing.
Patch: session namespace
problem with DLL relocation alert panels
s/value_ptr/struct value */
Re: scaf problem with RDI on Cygwin
scanf problem with RDI on Cygwin?
Stack Window causes Hang
sub system delivery error
symbol with in disassembly window
untangling c & tcl code
Updated copyright for '02 changes
Very Vain Question
Watch your changelogs!
Win32 - Error /DEV/NULL.DLL was not found
xlib/X11/Xutil.h patch: XEmptyRegion | http://www.cygwin.com/ml/insight/2002-q1/subjects.html | crawl-003 | refinedweb | 590 | 55.95 |
In line 32 which is the lttr[ctr] = read.next().charAt(0); wont read all the letters that i input. it only reads the last letter that i entered. what should i do to be able to display all the letters i entered and be able to reverse there order so that they would act as a PUSH. Line 34 is required every after a letter was input by the user. and if you have another solution so that the user can use a 'Y' and 'N' as a reply instead of 1 or 0. Thanks
lttr --- is my array that reads the letter that the user inputs. it can only hold 10 arrays.
ctr --- is just for the loop.
package javaapplication4; import java.util.*; public class PushPop { static Scanner read = new Scanner (System.in); public static void main(String[] args) { char letter; char[] lttr = new char[10]; int ctr=0,again; System.out.println ("Main Menu"); System.out.println ("A.Push"); System.out.println ("B.Pop"); System.out.println ("C.Print"); System.out.println ("D.exit"); System.out.print ("Please enter a letter:"); letter = read.next().charAt(0); switch (letter) { case 'a': case 'A': System.out.println ("Push"); do { System.out.println ("Enter a letter:"); lttr[ctr] = read.next().charAt(0); System.out.println ("Again? 1 for yes 0 for no"); again = read.nextInt(); }while (again>0); for (ctr=lttr.length-1;ctr>=0;ctr--) { System.out.print (lttr[ctr]+" "); } break; } } } | https://www.daniweb.com/programming/software-development/threads/299864/push-and-pop-last-in-first-out | CC-MAIN-2017-17 | refinedweb | 242 | 61.73 |
We were given city administrative boundary data as .shp files with the permission to import those to OSM / use on AddisMap.com.
I have used the Ogr2Osm scripts to convert this data to the OSM format. I tried all three versions (old SVN, UVM rewrite, pnorman's updated version) which are linked in the Wiki.
All of them produce the same results, but when I load the data in JOSM and compare them with the existing city data (Addis Ababa, Ethiopia), the imported data seems to be shifted by 176m, 222° (I measured this by drawing a way from the point where it should be to the imported point in JOSM)
When using Ogr2Osm it produces the following output:
Detected projection metadata:
PROJCS["Adindan_UTM_Zone_37N",
GEOGCS["GCS_Adindan",
DAT .prj file we received has the following content:
PROJCS["Adindan_UTM_Zone_37N",GEOGCS["GCS_Adindan",DATUM[ data was exported from ArcGIS.
What can be the source for the error? How can it be fixed?
EDIT: Same problem when I use ogr2ogr and shp2osm
ogr2ogr -t_srs WGS84 -s_srs "ESRI::subcities.prj" "subcities_converted.shp" "subcities.shp"
perl shp2osm.pl subcities_converted.shp > subcities.osm
Semi cross-posted to Stackexchange GIS
asked
03 Dec '12, 13:00
AddisMap_Ale...
880●24●32●50
accept rate:
0%
edited
07 Apr '15, 09:54
As found out on GIS.stackexchange I need to specify the projection string manually, because the ogr library does not detect it properly / does not do the datum conversion:
python ogr2osm.py -p "+proj=utm +zone=37 +ellps=clrk80 +towgs84=-166,-15,204,0,0,0,0 +units=m +no_defs" inputfile.osm
answered
04 Dec '12, 14:26
I think we used to have a similar problem with EPSG:27700.
@SK53: did you solve it the same way? Or another?
yes I added the explicit Helmert factors (the 7 towgs84 parameters), Chris Hill blogged about it at the time (), but IIRC there were still bugs in proj4 (and therefore ogr2ogr, PostGIS) relating to WGS84 and OSGB transformations in 2011.
A useful test if you have postgis, but I expect can be done with ogr2ogr is to use a well-defined point and perform transforms between various projections to test accuracy (particularly if there is a non-porj4 transformation available for comparison, as was the case for OSGB).
Once you sign in you will be able to subscribe for any updates here
Answers
Answers and Comments
Markdown Basics
learn more about Markdown
This is the support site for OpenStreetMap.
Question tags:
import ×131
shapefile ×54
gis ×26
arcgis ×21
ogr2osm ×5
question asked: 03 Dec '12, 13:00
question was seen: 2,550 times
last updated: 07 Apr '15, 09:54
Importing shapefile and saving to OSM with Potlatch2
Importing only items with certain Tags into QGIS
números de portal en SHP como los subo todos de una en addr:housenumber
how to download the territorial borders (violet line) as a shapefile
[closed] How to Import Building Shapefiles
how to upload the map of a place made with GIS
Is layer based export possible?
How can I use OpenStreetMap data in my GIS program?
How do I convert shp files to GPX
Exporting shapefiles from OpenStreetMap on QGis
First time here? Check out the FAQ! | https://help.openstreetmap.org/questions/18166/ogr2osm-imported-data-shifted-by-176m-222exported-from-arcgis | CC-MAIN-2017-09 | refinedweb | 535 | 58.21 |
This article explains in brief how to create a Hello World API in Python, and publish it on the WSO2 API Manager. It is intended for first-time users of WSO2 API Manager and those who are new to the REST API.
WSO2 API Manager is an open source tool that supports complete API life cycle management. It provides support for creating, publishing, monitoring and managing APIs. An API Manager (APIM) provides various features for providing security, versioning, publishing, monitoring, life cycle management, governance, etc, for the APIs. APIM is available on multiple platforms like AWS Cloud Formation, Kubernetes, Docker, Docker Compose, Vagrant, Helm, CentOS, Mac OS, Ubuntu, Windows, etc.
This article is divided into two parts, the first of which explains how to create a Hello World API and then host it using the Flask server. The second part covers the essential steps for setting up the API manager to publish and access the APIs.
Setting up the Hello World API on Flask
The API (Hello World) to be published using APIM is set up on a Flask server. The API returns ‘Helloooo World!’ text on the GET request.
1) Install Python from.
2) Install the Flask server using the command pip install Flask.
3) Create a ‘Hello World’ program in a normal editor like Notepad or Python IDEs like PyCharm with the following code:
from flask import Flask app = Flask(__name__) app.config[“DEBUG”] = True @app.route(‘/hello’, methods=[‘GET’]) def hello(): return ‘Helloooo World!’ if __name__ == “__main__”: app.run()
4) Save the above code as hello.py. The program can be executed using the command python hello.py. The following messages are displayed in the terminal when you run the program:
* Serving Flask app “hello” (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 301-321-685 * Running on (Press CTRL+C to quit)
5) Access localhost:5000/hello using a browser and your ‘Hello World’ application is ready.
Setting up the API Manager (APIM)
WSO2 APIM can be downloaded from. For this article, APIM has been installed on Windows with a single node deployment. Before running APIM, you need to install Java and set the JAVA_HOME environment variable.
Start APIM using the command wso2server.bat –run from the path <installation Path>API Manager\2.6.0\bin. The following messages get displayed in the command prompt if APIM has started successfully:
INFO - StartupFinalizerServiceComponent Server : WSO2 API Manager-2.6.0 INFO - StartupFinalizerServiceComponent WSO2 Carbon started in 83 sec INFO - CarbonUIServiceComponent Mgt Console URL : INFO - CarbonUIServiceComponent API Store Default Context : INFO - CarbonUIServiceComponent API Publisher Default Context :
Publishing the ‘Hello World’ API using APIM
APIM’s ‘Publisher’ publishes APIs, provides documentation, etc. The API Publisher URL is https://<IPAddress or hostname>:9443/publisher. The default credentials are admin/admin. You need to access the Publisher URL to publish the Hello World API. Figure 1 shows the page when no other API is published on APIM. The page allows you to add a new API.
The steps for publishing a new API are as follows:
1) Select ‘ADD NEW API’ to start publishing the first API, as shown in Figure 1.
2) Select ‘Design a New REST API’ to add a new API.
3) You will get a Design API page, where you need to enter the general details of the API to be published like the name, context, version, etc. The context is the path in the URL that will be used to access the API. Access control and visibility of the API can be controlled by adding the appropriate values.
4) Next, define the API details like the URL pattern and resources. Note that the context and the version data given in the ‘General Details’ section is already reflected in the URL pattern. For the Hello World API, the resource can be selected as GET and the resource path can be given as ‘/’. Select ‘Add’ after entering the details.
5) Click on GET / to add details of the API like the parameters, content type, etc. Select Implement to add the URL details of the Hello World API to be published.
6) Select Endpoint Type as HTTP/REST Endpoint. Provide the production endpoint as, the URL that is used to access the API endpoint on Flask. Click Test to check whether the APIM is able to access the URL. If Test is successful, then we will get the following output in the Flask server:
127.0.0.1 - - [26/Mar/2019 18:55:26] “HEAD /hello HTTP/1.1” 200 -
7) APIM will show the endpoint as ‘valid’ as shown in Figure 2.
8) Select Manage to provide details of API throttling, configurations, subscription tiers, etc.
9) Select Save & Publish to publish the API.
10) When the API is published successfully, the publisher will list the details as shown in Figure 3. The published API can be viewed in the API Store.
Get access to the Hello World API from APIM
APIs can be discovered and subscribed from the API Store, the URL for which is https://<IPAddress or hostname>:9443/store. The default credentials are admin/admin.
Create applications in APIM
APIs can be accessed using subscriptions against an ‘Application’. An application is a logical collection of APIs. Applications allow you to use a single access token to invoke a collection of APIs and to subscribe to one API multiple times with different SLA levels. The DefaultApplication is pre-created and allows unlimited access, by default.
Follow Steps 1 and 2 to add a new application to an API from Store.
1) Select Applications from the left-hand side of the page. It will display the list of applications.
2) Select Add Application to add a new application. Enter the details of the application like the name and description, and then select the Token Type (OAuth and JWT) to be used for authentication, and the API request quota per access token. Select Add to add the new application. The new application’s ‘TestApp’ gets added to the list of applications available.
3) Select TestApp from the applications list and go to Subscriptions. As you can see, there are no subscriptions for the new application created. Before subscribing to APIs, an access token/key has to be generated once for every application. This access token needs to be present with every request sent to APIM to access the subscribed API. The APIM checks the token value before allowing access to the API.
4) Go to Production Keys to generate keys. As you can see in Figure 7, no keys have been generated till now for this application. Select Generate Keys.
5) Keys will be generated as shown in Figure 8. The access token generated needs to be used in the ‘Authorization : Bearer’ of the Request Header. The keys generated have a validity period as mentioned in the Validity Period. The key has to be regenerated once the validity is over. The validity period can be changed as per the requirements.
Now that you have created an application and access token, you can start subscribing to the Hello World API.
1) Select ‘APIS’ from the left-hand side of the page. It will display the list of APIs available. Select the Hello World API. The API details will be displayed as shown in Figure 9. The URLs used to access the APIs through APIM are listed in the ‘Overview’ section. Http URL is http://<ipaddress/hostname>:8280/helloworld/1.0.0. Https URL is https://<ip-address/hostname>:8243/helloworld/1.0.0.
2) Select TestApp from the applications list in the top right corner of the page and click on Subscribe. Go to the API Console Tab and you can see the access token getting automatically reflected against the authentication part.
3) The API can be accessed via the cURL command as given below:
curl -k -X GET “http://<ip-address/hostname>:8280/helloworld/1.0.0” -H “accept: text” -H “Authorization: Bearer 25697571-945c-3a69-b490-9e80f06db19a”
4) You will get the following message in the Flask terminal:
127.0.0.1 - - [26/Mar/2019 18:55:26] “GET /hello HTTP/1.1” 200 -
5) You can also access the API using the Python code given below. For this code to work, you need to install the Python requests library by using the command pip install requests.
url = ‘’ header = {‘Authorization’: ‘Bearer 25697571-945c-3a69-b490-9e80f06db19a’} response = requests.get(url, headers=header) print(“Response code: “ + str(response.status_code)) print(“content: “ + str(response.text))
This article introduces beginners in REST API and API gateways to how to add a REST API to an API gateway. The latter can be used to host organisational or community APIs in the respective cloud environment. It helps in the reuse, adoption and faster acquisition of developed cloud services. | https://opensourceforu.com/2019/09/a-guide-to-publishing-your-first-api-in-wso2-api-manager/ | CC-MAIN-2019-39 | refinedweb | 1,489 | 57.77 |
Use components a lot, they are really really cool. (Sounds like zope3
components). One of the big tricks is to always access objects
through an interface.
ISomethingDoer(o).doSomething().
Raviolli pattern, Risotto pattern, Lasagna pattern (layered). Spaghetti pattern. I don't know what he meant by it, but it sure sounds funny :-)
Documentation generation tool. "API docs are basically impossible for
mortals to generate", so he created something new. He didn't look at
prior art and thought it all over fresh from the start. Extracting
docstrings is the easiest part. It knows about zope.interface. It can
cope moderately with
from xxxx import *. It's still fairly small
(2500 lines). Not release yet, no website. (I found an svn
repo ).
Instancemanager helps you to manager your zope/plone instances. At Zest software it replaced custom made scripts that had to be adapted for every project.
Some things it can do: create a zope instance, grap products and fill
the Products directory, copy a pre-made Data.fs if available,
start/stop zope, quickreinstall all products, etc. You can also do
several things with a "combining" call:
instancemanager vanrees
fresh.
Products can be extracted from .tgz, .zip or can be symlinked from svn checkouts. Bundles can also be handled.
Future: two people use it on the server, so it needs a look at the safety aspect: wiping your production server isn't a good idea and instancemanager will currently happily oblige you if you ask it to do just that. Also: Jim Fulton talked about buildout today which does something similar.
Thunk is a way to do lazy evaluation. Sharedref allows python sessions to share variables: they're no copies, they're real variables. You can append something to a list in one running python and you get it updated in the other. Just a demo prototype, but much fun.
Sometimes you just want to treat your web app as a black box, just sending http stuff at it from the outside, behaving as a real user.
Selenium is too slow and it can't be automated (with for instance buildbot). Zope.testbrowser is a programmable browser. There are three variants, one for http connections, one for talking directly to the zope3 publisher and a last one for the zope2 publisher.
All variants can be recorded with the testrecorder. correction 2006-07-05: you can install the server-side testbrowser in almost every webserver, you just have to figure out how to hook it up. It is easy to install inside zope, of course. Note: you need to install on the server which you are testing.
From the testrecorder, you can generate python doctests (and selenium tests, but the doctests are handier for automatic testing).
(Talk by video)
Mercurial is written in python.
He read all the abstracts and got some statistics out of it. A word you didn't see a lot is "security". Googling for "Python programming" versus "python security": security is 1.7% of the "programming" results. For perl it is 2.2% and for PHP it is 13%. Either they do a lot for security of they have a big security problem.
He build a small demo website giving the programmer advise based upon his chosen technologies. So: what do we think of the site and do we have input on python-related common problems and pitfals?.
Spreed is implemented in python for some 70-80%. Webcasts, conferencing, powerpoint sharing, etc. Spreed is available as software, as a service and as a hardware appliance.
Lxml is a python xml parser. Lxml is high performance, it is pythonic and it has lots of features. Not many of the other python xml libraries have all these three. lxml builds on libxml2, but has a much more pythonic interface than libxml2 itself has.
Some changes: there's a new maintainer that did loads of work. There is a 1.0 release and a 1.1 is in alpha. Lots of improvements. If you work with xml in python and you need high performance, pythonic api and lots of features: use lxml.
itools has a catalog engine.
With "property" he means those python new-style-classes that allow
you to have just
obj.property instead of
obj.getProperty() and
so.
Decorators allow you to do things like:
@property def feel(): #xxxxxxx
Doesn't really help when you also have a setter. He tried something
with
@getproperty and
@setproperty. Next try was using something
like:
class JamesBrown: class feel(classproperty): def getFeel(...) #xxxx def setFeel(...) #xxxx
PSF protects the python intellectual property, funds some research and organises pycon.
And.... Rob is going to raise money for the PSF tonight at the dinner by doing paid neck massages. (He's very good! I had one last year).
Demo on what you can automate on windows with pywinauto .
Treat a database as a neural net. You can investigate relationships, compensate for missing data, extrapolate values, etc.
Impossible to blog, all those screens of data, but it was pretty funny to see that it actually works a bit.
He'll have the python code up on the cookbook this evening.
One talk I didn't commit yet from this afternoon:
Tiny ERP manages accounting, sales/purchases department, stock/production, customer relationship management (CRM), project management, etc. The advantage is that it is integrated and extensible. The target market is small to medium businesses, they're not yet targetting the big customers.
The project was given wider publicity in 2005. There are 5 full-time developers at Tiny and they have some 23 partners in 11 countries.
One convenient feature is automatic partner segmentation: 20% of your customers deliver 80% of your sales, so tiny ERP allows you to filter them out.
The architecture is client/server, but it is server oriented: all the logic is on the server. The database layer is postgreSQL, the object layer is python and the view layer is in XML. The client has almost no logic, it communicates with the server using xml-rpc. Workflows are also defined in XML, but you can generate an image): | http://reinout.vanrees.org/weblog/2006/07/04/europython-lightning-talks.html | CC-MAIN-2015-32 | refinedweb | 1,017 | 68.47 |
In my models I have a class called "Add_prod",I have created few columns like book,author,price and so on.In the templates I have created two hyperlinks for sorting data in ascending/descending order of price."name" attribute is not supporting in anchor tag.I also tried with id attribute instead of name,but still no use.So how to fetch data from anchor tag so that I arrange products in sorted order.
Views.py,
def welcome_user(request):
if 'low_price' in request.GET:
my_products = Add_prod.objects.all().order_by('price')
elif 'high_price' in request.GET:
my_products = Add_prod.objects.all().order_by('-price')
else:
my_products = Add_prod.objects.all()
context = { "Products":my_products}
#rest of code for other functionalities
return render(request,"welcome-user.html",context)
<form>
<div style="text-align: right">
<a name="low_price" href="{% url 'welcome_user' %}">Low Price</a>
<a name="high_price" href="{% url 'welcome_user' %}">High Price</a>
</div>
</form>
You need to append the URLs with the
query parameters you are expecting in the view:
<a name="low_price" href="{% url 'welcome_user' %}?low_price">Low Price</a> <a name="high_price" href="{% url 'welcome_user' %}?high_price">High Price</a> | https://codedump.io/share/lnFCQ5Sw0dSh/1/how-to-fetch-data-from-link-tag-in-django | CC-MAIN-2017-04 | refinedweb | 185 | 51.75 |
Understanding Generic Classes
Many developers will view themselves primarily as consumers of generics. However, as you get more comfortable with generics, you're likely to find yourself introducing your own generic classes and frameworks. Before you can make that leap, though, you'll need to get comfortable with all the syntactic mutations that come along with creating your own generic classes. Fortunately, you'll notice that the syntax rules for defining generic classes follow many of the same patterns you've already grown accustomed to with non-generic types. So, although there are certainly plenty of new generic concepts you'll need to absorb, you're likely to find it quite easy to make the transition to writing your own generic types.
Parameterizing Types
In a very general sense, a generic class is really just a class that accepts parameters. As such, a generic class really ends up representing more of an abstract blueprint for a type that will, ultimately, be used in the construction of one or more specific types at run-time. This is one area where, I believe, the C++ term templates actually provides developers with a better conceptual model. This term conjures up a clearer metaphor for how the type parameters of a generic class serve as placeholders that get replaced by actual data types when a generic class is constructed. Of course, as you might expect, this same term also brings with it some conceptual inaccuracies that don't precisely match generics.
The idea of parameterizing your classes shouldn't seem all that foreign. In reality, the mindset behind parameterizing a class is not all that different than the rationale you would use for parameterizing a method in one of your existing classes. The goals in both scenarios are conceptually very similar. For example, suppose you had the following method in one of your classes that was used to locate all retired employees that had an age that was greater than or equal to the passed-in parameter (minAge):
[VB code] Public Function LookupRetiredEmployees(ByVal minAge As Integer) As IList Dim retVal As New ArrayList For Each emp As Employee In masterEmployeeCollection If ((emp.Age >= minAge) And (emp.Status = EmpStatus.Retired)) Then retVal.Add(emp) End If Next Return retVal End Function [C# code] public IList LookupRetiredEmployees(int minAge) { IList retVal = new ArrayList(); foreach (Employee emp in masterEmployeeCollection) { if ((emp.Age >= minAge) && (emp.Status == EmpStatus.Retired)) retVal.Add(emp); } return retVal; } }
Now, at some point, you happen to identify a handful of additional methods that are providing similar functionality. Each of these methods only varies based on the status (Retired, Active, and so on) of the employees being processed. This represents an obvious opportunity to refactor through parameterization. By adding status as a parameter to this method, you can make it much more versatile and eliminate the need for all the separate implementations. This is something you've likely done. It's a simple, common flavor of refactoring that happens every day.
So, with this example in mind, you can imagine applying this same mentality to your classes. Classes, like methods, can now be viewed as being further generalized through the use of type parameters. To better grasp this concept, let's go ahead and build a non-generic class that will be your candidate for further generalization:
[VB code] Public Class CustomerStack Private _items() as Customer Private _count as Integer Public Sub Push(item as Customer) ... End Sub Public Function Pop() as Customer ... End Function End Class [C# code] public class CustomerStack { private Customer[] _items; private int _count; public void Push(Customer item) {...} public Customer Pop() {...} }
This is the classic implementation of a type-safe stack that has been created to contain collections of
Customers. There's nothing spectacular about it. But, as should be apparent by now, this class is the perfect candidate to be refactored with generics. To make your stack generic, you simply need to add a type parameter (
T in this example) to your type and replace all of your references to the
Customer with the name of your generic type parameter. The result would appear as follows:
[VB code] Public Class Stack(Of T) Private _items() as T Private _count as Integer Public Sub Push(item as T) ... End Sub Public Function Pop() as T ... End Function End Class [C# code] public class Stack<T> { private T[] _items; private int _count; public void Push(T item) {...} public T Pop() {...} }
Pretty simple. It's really not all that different than adding a parameter to a method. It's as if generics have just allowed you to widen the scope of what can be parameterized to include classes.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c11887/Understanding-Generic-Classes.htm | CC-MAIN-2017-17 | refinedweb | 787 | 53.31 |
This page originally had 7 ways to take a screenshot in Linux. It keeps growing and now there are more than 7. If you know of other useful ways to take a screenshot in Linux, leave a comment below...
There are several ways to take a screenshot Linux in general. I'm going to use Ubuntu as an example, but most of these will work on any Linux distro. If you aren't using GNOME, then the GNOME-specific items won't work.
I'll start with the common ways to take screenshots in Linux, and then show you a nice shell script for taking custom screenshots in GNOME with just one click of the mouse. The shell script will also work in other windows managers like KDE, but you will have to figure out how to make the custom application launcher for it.
One way to take a screenshot in Ubuntu is to go to the main menu: Applications —> Accessories —> Take Screenshot.
You can also take a screenshot of the entire screen by pushing the "Print Screen" (PrtSc) button on your keyboard. To get a screenshot of only the active window, use Alt-PrtSc. This is easier than using the GNOME "Take Screenshot" tool. You can also control this GNOME screenshot tool from the terminal as described in a newer Linux screenshot tutorial.
To get more control over your screenshots, check out the other options below.
My favorite way of taking screenshots is with ImageMagick in the terminal. If you need a delay before taking the screenshot (for example, to get a screenshot of a menu that would disappear if you took a screenshot with GNOME) ImageMagick is the best way.
First, make sure you have ImageMagic installed: type import -version in the terminal. If ImageMagick is installed, you will see the ImageMagick version number. I don't think Ubuntu comes with ImageMagick. To install ImageMagick in Ubuntu (or any Debian-based distro), just type sudo apt-get install imagemagick.
To take a screenshot in the terminal with ImageMagick, type the following line into a terminal and then click-and-drag the mouse over a section of the screen:
import MyScreenshot.png
GNOME will beep once when the screenshot begins, and once again when the screenshot is complete. Then type eog MyScreenshot.png in the terminal to view your screenshot. "eog" is the command to start Eye of GNOME.
To capture the entire screen after a delay (so you can open some menus or whatever), type sleep 10; import -window root MyScreenshot2.png. The first part of that line, sleep 10; will give you a 10 second delay before the screenshot begins. The next part, import -window root, tells ImageMagick to import the "root" window — that is, the entire screen. The last part MyScreenshot2.png is the name of your screenshot.
The following command will wait for 15 seconds, take a screenshot, and then open the screenshot in the GIMP for editing:
sleep 15; import -window root MyScreenshot3.png; gimp MyScreenshot3.png;
You can also manipulate the screenshot with ImageMagick as you take it. For example, the following line will take a screenshot and resize the image to a width of 500 pixels:
import -window root -resize 500 AnotherScreenshot.png
For more information on how to take screenshots in the terminal with ImageMagick, type man imagemagick in the terminal. You can also type import -help to get a list of options for the import command.
Another way to take a screenshot from the terminal is with scrot. I learned about this at UbuntuForums.org.
To install scrot (on Ubuntu) type:
sudo aptitude install scrot
To take a screenshot in Linux from the terminal with scrot type:
scrot MyScreenshot.png by typing the following in the terminal:
man scrot
As described in my newer Linux screenshot tutorial, you can also take a screenshot from the Linux terminal in GNOME with the following command:
gnome-panel-screenshot
You can also add a delay:
gnome-panel-screenshot --delay 5
To take a screenshot with the GIMP, find the following menu option: File —> Acquire —> Screen Shot. You will then be offered some options for the screenshot such as length of delay and whether you want to take a screenshot of the entire screen, or just a window.
I use two different Firefox extensions to take screenshots of web pages, depending on what kind of screenshot I need.
If I just need to take a screenshot of a section of a web page, I use a Firefox extension called Snapper.
UPDATE: There is no longer a Snapper extension for Firefox and the Screengrab Extension mentioned below contains all of it's functionality.
A great Firefox extension for taking screenshots is called ScreenGrab. ScreenGrab will take screenshots of entire web pages — even the parts that run off the screen.
To take a screenshot of a web page in Firefox with ScreenGrab, just right click on a web page and choose: ScreenGrab! —> Save document as image. Give the extension a few seconds to startup and take the screenshot. When ScreenGrab is done it will open a save dialog box where you can choose a filename for your screenshot.
[This can be modified to work in KDE or any other windows manager also.]
[UPDATE: I learned of another one-click Linux screenshot method that might work better for you than this shell script. Read through the shell script and try it out if you would like because the shell script is more customizable. But also see the new screenshot tutorial.]
The shell script for taking one-click screenshots is below. Copy and paste it into your favorite text editor and save it somewhere in your home directory as screenshot-import.sh. Then run the following command on it in the terminal to make it executable: chmod +x screenshot-import.sh.
Then right-click on your GNOME Panel — that is the panel that runs across the top of your screen in GNOME (e.g., Ubuntu). Choose Add to Panel as shown in the image below:
Then click on the button that says Custom Application Launcher. You will then see the following window:
Fill out the information as shown. Choose an icon (see below for a custom icon). Click on "Browse" and navigate to the place where you saved the shell script below. Do not check the box that says "Run in terminal".
After you have set up the custom application launcher for the screenshot-import.sh script you will be able to quickly take a screenshot of part of the screen by clicking on the new launcher in the GNOME panel, and then clicking-and-dragging the mouse over a section of the screen. The shell script will save the screenshot to the desktop.
Here is an optional custom icon for this application launcher. Just download the eye.xpm file to your desktop and then copy it to your pixmaps directory like this:
sudo cp eye.xpm /usr/share/pixmaps/
Then right click on your new application launcher in the GNOME panel, click on Properties, and then choose this icon.
Note that it will save the screenshots to ~/Desktop/. Read through the script and try to understand what it is doing before you use it.
#!/bin/bash # # # # Use this script at your own risk # # Takes a screenshot with ImageMagick. # Link to this file from the GNOME panel # Do NOT check the box "run in terminal" # Remember to chmod +x this file # Screenshot will save to ~/Desktop/ # The name of your file screenshot='screenshot'; # Creates an unusual filename based on nanoseconds so that # you don't accidentally overwrite another screenshot. # The `backticks` tell the script to run another command (date). # Type 'man date' in the terminal for more info nano=`date '+%d%b%y-%N'`; # Adds the file extension extension='.png'; # Generate a filename for this screenshot file="$HOME/Desktop/$screenshot-$nano$extension"; # Use ImageMagick to take the screenshot # Saves to ~/Desktop import $file;
Another article describes how to edit your screenshots with the GIMP.
Did you find this post helpful? Leave a comment below, and subscribe to my RSS feed.
very good tools overview
Excellent review of the methods that can be used to get screenshots on Linux with Gnome (but not limited to Gnome). Since I needed only parts of the screen in the capture, I used the "import filename.png" command while adding the delay with sleep 10; as described above. It solved my problem!
The explanations about using gnome-screenshot-panel were very useful too; I would probably use that tip for other screen captures.
Thank you very much for these very complete explanations and for explaining in detail the steps required.
PS Unfortunately, I don't know of any other method that can be used for this task... The ones that you already described seem more than enough - anyone should find the right tool for their screenshot needs.
Also ksnapshot
ksnapshot is another excellent screen capture program. It runs in Gnome. Maybe KDE needs to be installed to run it?
Taking a Screenshot in Linux with ksnapshot
Thanks for pointing that one out. I have ksnapshot installed, but forgot to mention it. It runs in GNOME, but I do have KDE installed also.
Is it possible to take a
Is it possible to take a screenshot in the REAL terminal?
use xwd to screen a terminal
use xwd to screen a terminal window.
xwd > screen.xwd
use convert to convert to other format.
convert screen.xwd screen.png
you can pipe the commands or use the -root switch to cap the whole screen if your using term in a gui. i.e. xwd -root > screen.xwd
Which methods can I use, to
Which methods can I use, to make a screenshot that includes the mouse? When I used the Print-button (Ubuntu), it wasn't on the pic.
Taking a screenshot of the mouse pointer
I'm not sure how to do that, except using a workaround with Wink. Just set Wink to take one screenshot (i.e., by pressing the Pause key). Then export as HTML. Your screenshot will be in the exported directory. Here is a screenshot of the mouse pointer captured with Wink:
how to take desktop
how to take desktop screenshots in perticular intervel like every 5 min
How to take a screen shot every 5 minutes
You can write a simple shell script to automate the process.
For example, try something like this in the terminal:
for((i=0;i<12;i++))
do
import -window root screenshot_$i.png
sleep 5m
done
It will take a screenshot 12 times — once every 5 minutes. It will beep twice for every screenshot — once when the screenshot starts and once when it finishes.
such a long script...
Wow, such a long script for something that can fit easily on one line:
import $HOME/Desktop/screenshot-$(date '+%d%b%y-%N').png
I prefer to use the following format:
import -window root ~/screenshot-$(date +%F)--$(date +%T).png
Anyway, the Fox toolkit contains a utility called "shutterbug" which is a nice little screen capture utility.
why stop at 12? this will
Screen Tool
There is also another screenshot tool now: Screen Tool (). It works under Qt and with static build should work under any distro. What is so different with this tool?
But, (there is always "but") it is not free, but price of 10 euros is not too much for this kind of tool! Demo version is free to download.
Screenshot - Linux
Link above worked for me. Easy, simple and good....
Here's another really useful
Here's another really useful program:
Takes screenshots of a specific window, section, subsection of a window, site... apply effects / annotate and upload ;)
ScreenStamp!
ScreenStamp! was released today. | http://tips.webdesign10.com/how-to-take-a-screenshot-on-ubuntu-linux | CC-MAIN-2017-13 | refinedweb | 1,962 | 73.07 |
Tcl_CreateTrace, Tcl_CreateObjTrace, Tcl_DeleteTrace - arrange for com-
mand execution to be traced
#include <tcl.h>
Tcl_Trace
Tcl_CreateTrace(interp, level, proc, clientData)
Tcl_Trace
Tcl_CreateObjTrace(interp, level, flags, objProc, clientData, deleteProc)
Tcl_DeleteTrace(interp, trace)
Tcl_Interp *interp (in) Interpreter con-
taining command
to be traced or
untraced.
int level (in) Only commands at
or below this
nesting level
will be traced
unless 0 is
specified. 1
means top-level
commands only, 2
means top-level
commands or
those that are
invoked as imme-
diate conse-
quences of exe-
cuting top-level
commands (proce-
dure bodies,
bracketed com-
mands, etc.) and
so on. A value
of 0 means that
commands at any
level are
traced.
int flags (in) Flags governing
the trace execu-
tion. See below
for details.
Tcl_CmdObjTraceProc *objProc (in) Procedure to
call for each
sequence.
ClientData clientData (in) Arbitrary one-
word value to
pass to objProc
or proc.
Tcl_CmdObjTraceDeleteProc *deleteProc_Cre-
ateTrace).
__________________________________________________________________Create-
Trace). parame-
ter may be set to the constant value TCL_ALLOW_INLINE_COMPILATION. In
this case, traces on built-in commands may or may not result in trace
callbacks, depending on the state of the interpreter, but run-time per-
formance will be improved significantly. (This functionality is desir-
able, for example, when using Tcl_CreateObjTrace to implement an execu--
tions. If there is a syntax error in a command, or if there is no com-
mand procedure associated with a command name, then no tracing will
occur for that command. If a string passed to Tcl_Eval contains multi-
ple compati-
bility with code that was developed for older versions of the Tcl
interpreter. It is similar to Tcl_CreateObjTrace, except that its proc
parameter should have arguments and result that match the type Tcl_Cmd-
TraceProc:
ments to the command as character strings. Proc must not modify the
command or argv strings.
If a trace created with Tcl_CreateTrace is in effect, inline compila-
tion of Tcl commands such as if and while is always disabled. There is
no notification when a trace created with Tcl_CreateTrace is deleted.
There is no way to be notified when the trace created by Tcl_Create-
Trace is deleted. There is no way for the proc associated with a call
to Tcl_CreateTrace to abort execution of command.
command, create, delete, interpreter, trace
Tcl Tcl_CreateTrace(3) | http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/Tcl_CreateTrace.3.html | crawl-003 | refinedweb | 374 | 55.44 |
Hi,
Recently I’ve come across something weird… I needed a ComboBox that will allow the user to select multiple items.
The the solution coming to mind is using CheckBoxes. I have found several examples, but neither one displayed the selected items with pretty commas (like this:
).
I’ve decided the best solution willl be taking an example from MSDN and modifying it to suite my needs.
Steps: (actually took ALOT longer and was ALOT harder – learning curves and such)
- Created a UserControl.
- Added the ComboBox from the MSDN sample.
- Created 3 dependency properties:
- Text – retrieves the text of the selected items
- ItemsSource – the items to display (currently bound to Title and IsSelected)
- DefaultText – the text to display if no items were checked
- Bound the ItemsSource properties of the UserControl and the ComboBox.
- Added a Click event to the CheckBox that refreshes the text field in the ContentPresenter.
Usage
<Window
…
xmlns:controls="clr-namespace:Controls;assembly=Controls"
<controls:ComboWithCheckboxes x:
Result
Code
ComboWithCheckboxes.xaml
<UserControl x: <UserControl.Resources> <LinearGradientBrush x: <GradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFF" Offset="0.0"/> <GradientStop Color="#CCC" Offset="1.0"/> </GradientStopCollection> </GradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x: <GradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#CCC" Offset="0.0"/> <GradientStop Color="#444" Offset="1.0"/> </GradientStopCollection> </GradientBrush.GradientStops> </LinearGradientBrush> <SolidColorBrush x: <LinearGradientBrush x: <GradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFF" Offset="0.0"/> <GradientStop Color="#AAA" Offset="1.0"/> </GradientStopCollection> </GradientBrush.GradientStops> </LinearGradientBrush> > <SolidColorBrush x: <SolidColorBrush x: <SolidColorBrush x: <SolidColorBrush x: <ControlTemplate x: <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="20" /> </Grid.ColumnDefinitions> <Border x: <Border Grid. <Path x: </Grid> <ControlTemplate.Triggers> <Trigger Property="ToggleButton.IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Background" Value="{StaticResource DarkBrush}" /> </Trigger> <Trigger Property="ToggleButton.IsChecked" Value="true"> <Setter TargetName="Border" Property="Background" Value="{StaticResource PressedBrush}" /> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" /> <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" /> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> <Setter TargetName="Arrow" Property="Fill" Value="{StaticResource DisabledForegroundBrush}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> <ControlTemplate x: <Border x: </ControlTemplate> > </UserControl.Resources> <ComboBox x: <ComboBox.ItemTemplate> <HierarchicalDataTemplate> <CheckBox Content="{Binding Title}" IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Tag="{RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}" Click="CheckBox_Click" /> </HierarchicalDataTemplate> </ComboBox.ItemTemplate> <ComboBox.Template> <ControlTemplate TargetType="ComboBox"> <Grid> <ToggleButton Name="ToggleButton" Template="{StaticResource ComboBoxToggleButton}" Grid. </ToggleButton> <ContentPresenter x: <ContentPresenter.Content> <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Path=Text,Mode=TwoWay,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" /> </ContentPresenter.Content> </ContentPresenter> <!-- <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide"> <Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"> <Border x: <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True" DataContext="{Binding}"> <StackPanel IsItemsHost="True" KeyboardNavigation. </ScrollViewer> </Grid> </Popup> </Grid> <ControlTemplate.Triggers> <Trigger Property="HasItems" Value="false"> <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </Trigger> <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="true"> <Setter TargetName="DropDownBorder" Property="CornerRadius" Value="4"/> <Setter TargetName="DropDownBorder" Property="Margin" Value="0,2,0,0"/> </Trigger> <Trigger Property="IsEditable" Value="true"> <Setter Property="IsTabStop" Value="false"/> <Setter TargetName="EditableTextBox" Property="Visibility" Value="Visible"/> <Setter TargetName="Presenter" Property="Visibility" Value="Hidden"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </ComboBox.Template> </ComboBox> </UserControl>
ComboWithCheckboxes.xaml.cs
usingSystem.Windows;
namespace Controls
{
/// <summary>
///Interaction logic for ComboWithCheckboxes.xaml
/// </summary>
public partial classComboWithCheckboxes
{
#regionDependency Properties
/// <summary>
///Gets or sets a collection used to generate the content of the ComboBox
/// </summary>
public objectItemsSource
{
get{ return(object)GetValue(ItemsSourceProperty); }
set
{
SetValue(ItemsSourceProperty, value);
SetText();
}
}
public static readonlyDependencyPropertyItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(object), typeof(ComboWithCheckboxes), newUIPropertyMetadata(null));
/// <summary>
///Gets or sets the text displayed in the ComboBox
/// </summary>
public stringText
{
get{ return(string)GetValue(TextProperty); }
set{ SetValue(TextProperty, value); }
}
public static readonlyDependencyPropertyTextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ComboWithCheckboxes), newUIPropertyMetadata(string.Empty));
/// <summary>
///Gets or sets the text displayed in the ComboBox if there are no selected items
/// </summary>
public stringDefaultText
{
get{ return(string)GetValue(DefaultTextProperty); }
set{ SetValue(DefaultTextProperty, value); }
}
// Using a DependencyProperty as the backing store for DefaultText. This enables animation, styling, binding, etc…
public static readonlyDependencyPropertyDefaultTextProperty =
DependencyProperty.Register("DefaultText", typeof(string), typeof(ComboWithCheckboxes), newUIPropertyMetadata(string.Empty));
#endregion
publicComboWithCheckboxes()
{
InitializeComponent();
}
/// <summary>
///Whenever a CheckBox is checked, change the text displayed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private voidCheckBox_Click(objectsender, RoutedEventArgse)
{
SetText();
}
/// <summary>
///Set the text property of this control (bound to the ContentPresenter of the ComboBox)
/// </summary>
private voidSetText()
{
this.Text = (this.ItemsSource != null) ?
this.ItemsSource.ToString() : this.DefaultText;
// set DefaultText if nothing else selected
if(string.IsNullOrEmpty(this.Text))
{
this.Text = this.DefaultText;
}
}
}
}
That’s it!
Adi.
hi.. that was good article please send me the control on from to email address “im.masoomali@gmail.com”
Hi. This article is great, i need to do the exact same thing. Could you please send me the control via email or upload it here? I tried to modify the code in here, but i´m new at this and i have errors that i don´t know how to correct.
Help me please!!
My email address is: mmgv5@yahoo.com
Thanks!!
what ItemSource i can provide to this control?
Adi, this is so good it’s not even funny. Thank you!!
Gajender – This worked for me:,’});
}
}
Fantastic work Adi, this is an extremely useful control! Just solved my multi-selection headache.
Rob – side note, the using statements required for your nodelist are:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
I got compile errors because I was missing .ObjectModel.
Hi, guys,
Sorry for the late response. The web’s been keeping me busy…
Glad to see someone found a use for this control.
I hope Gavin’s comment helped with the errors.
This is great! You saved me
I liked this post so much that I revisited other posts discussing about multiselect combobox to come to this post. Thank you, thank you Adi!
Thank you for posting this code Adi. Would you please give some ideas on how to use this multiselect combobox in a datagrid? My users want to have multiselect columns in a datagrid.
Thanks,
Amy
Thx for the code. However that does not work for me:
1) I imported the code in a separate project and referenced from my VB.Net project.
2) I created a class that contains checkboxes data (the Node class of the Rob Lewis comment)
3) Then I created a collection with an overrided ToString method to contain the nodes collection.
4) Setting the ItemsSource to that populated collection binds everything well, but the data:
The dropdown will populate the popup and show the text (“Checkbox A, Checkbox B, …”).
The popup will show the correct number of checkboxes, but will not bind to the Node class: checkboxes will not be checked and the Text property will not be set. Neither the object>source binding will work: checking the checkbox will not change the IsSelected property of my Node.
Yes, the Node class has IsSelected and Title fields.
May you post or send an example?
Thx in advance!
Great code!
I use it in a wpf toolkit datagrid, and it almost works perfectly. But when a row is selected, the usercontrol dosen´t display the default text or if any values is selected, them as a comma seperated string, it displays nothing, otherwise it works fine.
Any suggestions?
Thanks in advance!
Hi, Alberto,
I’m sorry, but my laptop dropped dead, and I don’t have an example to provide.
Can anyone else help?
Great example thought this is not working for me and I can’t understand why.
I have copied the user control with the .cs, and created the node and the collection classes.
I populate the item source in the code behind :
(the button.YParametersFieldNames holds the previously selected parameters)
ObservableNodeList itemSource = new ObservableNodeList();
List
selectedParameters = new List (button.YParametersFieldNames);
foreach (DataColumn column in button.DataSource.Columns)
{
Node item = new Node(column.Caption);
item.IsSelected = selectedParameters.Contains(item.Title);
itemSource.Add(item);
}
comboYParameters.ItemsSource = itemSource;
and the result if the comboBox looks empty with no available items to select from.
what am I missing here ?
forget my last comment, found the erorr – I accidently removed the x:name of the user control which made the binding of the item source to not work correctly.
Hi,
can you please post the code that goes in window.xaml.cs ,I am a newbie trying to use usercontrols and i am unable to get your code working,
Thanks you so much
Hi all,
those who got it to work.
can you plesae see what is wrong in my code.
This is how my window.xaml.cs looks.Rest of teh code is directly from the code above.I cannot get the checkboxes to display.
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ObservableNodeList itemSource = new ObservableNodeList();
itemSource.Add(new Node(“Willa”));
itemSource.Add(new Node(“Isak”));
itemSource.Add(new Node(“Victor”));
itemSource.Add(new Node(“Jules”));
cbLanguages.ItemsSource = itemSource;
cbLanguages.DataContext = itemSource;
// listBox1.ItemsSource = itemSource;
}
},’ });
}
}
}
Cant see my two posts
Can you please provide, proper sample.
Steps to make it work:
1. Update the property “ItemsSource” in ComboWithCheckboxes class with the following code.
public object ItemsSource
{
get { return (object)GetValue(ItemsSourceProperty); }
set
{
this.CheckableCombo.ItemsSource = (System.Collections.IEnumerable)value;
SetValue(ItemsSourceProperty, value);
SetText();
}
}
2. Add the following code in the window1.xaml.cs
ObservableNodeList itemSource = new ObservableNodeList();
Node a = new Node(“Dog”);
a.IsSelected = true;
itemSource.Add(a);
Node b = new Node(“Monkey”);
b.IsSelected = false;
itemSource.Add(b);
cbLanguages.ItemsSource = itemSource;
Hi, thank you for the control.
But I can’t find the DisabledBorderBrush resource… can you add it or point to the location?
Hi Folks,
Can anyone of you who got it to work can please email me the usercontrol.
Will appreciate it. Thanks a lot!!!
my email id is mkkeerthi@rediffmail.com
I am having a problem getting the ItemSource events to fire.
For example, I databind the ItemsSource property to an ObservableNodeList as a public property. However, when I write my data into this property, the data is written into the ItemsSource and is available in the drop down but the SetText is not called so the selected items in the list are not updated in the ComboBox view when collapsed.
If I subsequently open the combopox and deselect an item , then the combobox refreshes from the ButtonClick event.
I checked and for some reason the Set and Get methods are not being called at all when I assign to the ItemSource property.
any ideas what I could be doing wrong?
Hello,
Great control, I like it. But I’ve got some problems with stretching it horizontally. It doesn’t behave like usual combobox – setting HorizontalAlignment isn’t enough for stretching it. Removing Width=”120″ setting of UserControl also dodn’t help me. Could somebody help me?
The task is to show this control stretched horizontally.
Never mind, please. The problem was in code around the control, not in control itself.
Is it possible to download the latest version of the control from somewhere? Or could somebody mail me this to
“rgb64(at)bluemail.ch”
Thanks
Hey there. I’m having some problems with GetValue and setValue in the codebehind file. can anyone tell me how to correct these errors or maybe send a working sourcefile to me at:
Mikael_Madkasse@Hotmail.com
kthxbye
You can resolve the GetValue/SetValue compile errors by deriving the control (in the codebehind) from UserControl.
public partial class ComboWithCheckboxes : UserControl
Hi Adi,
It is really a beautifull code. Can you please send me the code to me subham11@gmail.com
Thanks & Regards,
Satyam Kumar.
You can use generics to make multi-select entity collections easier:
1) Create interface “ISelectable”:
public interface ISelectable
{
bool IsSelected { get; set; }
string DisplayName { get; }
}
2) Implement ISelectable on entity:
public partial MyEntity : ISelectable
{
public bool IsSelected { get; set; }
public string DisplayName {
get { return this.PropertyToDisplay; }
}
}
3) Create MultiSelectEntityCollection
:
public class MultiSelectEntityCollection
: ObservableCollection
where T : ISelectable
{
public override string ToString()
{
var str = new StringBuilder();
Items.ToList().ForEach( item =>
{
if ( item.IsSelected )
{
str.Append( item.DisplayName );
str.Append( “, ” );
}
} );
return str.ToString().TrimEnd( ‘,’ );
}
}
4) Use MultiSelectEntityCollection in your code:
public MultiSelectEntityCollection
MyMultiSelectableEntityCollection { get; set; }
Cheers,
refereejoe at yahoo dot com
Implementing this user control in MVVM pattern, itemsource doesn’t change when we change this from code
ItemsSource doesn’t work initially in a Datagrid (wpftoolkit).
This is a workaround. In the grid:
The Converter:
[ValueConversion(typeof(object), typeof(string))]
public class InitialTextConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (value is ObservableNodeList)
{
ObservableNodeList list = (ObservableNodeList)value;
if (list.AllChecked())
return “All”;
if (list.NoneChecked())
return “None”;
return list.ToString();
}
return string.Empty;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
// we don’t intend this to ever be called
return null;
}
}
I also had to change the content of the default Combobox (as the text was not visible sometimes):
So far so good, I have tried to figure out how to get it done via using xaml only, but sound seems to be we have to handle it on both xaml & code behind
This example works great! Thanks for that!
There is only a small “bug” I have with the xaml:
When I select some items, sometimes I click “between” two items (meaning: somewhere in the top or bottom of an item). The instead of selecting this item, the selection box disappears. Does anyone have a solution for that?
Please send me the wpf control in mailid as soon as possible.
my mail id:-
debasish.das04@gmail.com
Please send me the control with code…my mail id:- debasish.das04@gmail.com
If found a solution to the follwing issuee posted a little bit earlier by me:
The problem was when I selected some items, sometimes when clicking “between” two items (meaning: somewhere in the top or bottom of an item), instead of selecting this item the selection box was closed. Apparently the check box did not register the click, and somehow the event was registered as clicking outside of the popup.
There is an easy way to solve the problem: Set the margin of the checkbox in the
to negative values!
So, e.g. Margin=”0,-5,0,-5″ added to the checkbox tag would resolve the issue.
Hi.
Just went through your code.
It is the same type of control I wanted to implemented.
But somehow the code is not working.
Can you please share the sourcecode once again?
I am able to fix the code and make it run. I want to using this control in MVVM model. I am not able to get the selected checkbox value. Does any one tryit. If yes please post the code.
Thanks,
How can I add
1. tooltip (TextBox) and
2. quick search (like on key press of D should highlight items starting with D)
to the above example?
I have been trying to clear all the checkbox for a button Clear All.
The TextProperty works but the checkbox are still in check state although ObservabelNodeList shows isSelected = false.
private void button1_Click(object sender, RoutedEventArgs e)
{
foreach (Node n in (ObservableNodeList)comboCheckBox1.ItemsSource)
{
if (n.IsSelected) n.IsSelected = false;
}
}
Hi I like your solution, can you email me the complete solution. My email is venkatap@gmail.com
Hi, I will be able to use your solution in my project if I can make the control editable (i.e. user can type as well as check boxes). In other words I need IsEditable property to be true. I tried to add this property but it didn’t work.
Solution looks elegant. Can you please email me the solution at vilash001@yahoo.com. Thanks again
Can you please email me the solution at cpjack@yahoo.cn. Thanks again
This is what i wanted. Other 3rd party ones doesn’t work for my scenarios. Please email me the solution at deshmukhsandeep023@gmail.com.
I want to implement it, but a lot of errors appeared.
So, can someone send me the source codes? Please help me.
Thanks.
ras
Please send me the control with code…my mail id: sexyminho@hotmail.com
Hey,
Just wanted to say thank you. I got it working easily, this solution is perfect for my application.
I implemented it using MVVM pattern and I am having an issue when switching tabs, the Text property becomes empty again, even tough things are checked in the list… have to figure this out!
Thanks again!
Nice, but my problem with this is that if you click *between* an item while the box is dropped-down, the box closes. This, to me, renders the control unusable. Is there any way to prevent this?
Getting this error in my project
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=IsDropDownOpen; DataItem=’ComboBox’ (Name=’CheckableCombo’); target element is ‘ToggleButton’ (Name=’ToggleButton’); target property is ‘IsChecked’ (type ‘Nullable`1′) XamlParseException:’System.Windows.Markup.XamlParseException: Provide value on ‘System.Windows.Markup.StaticResourceHolder’ threw an exception. —> System.Exception: Cannot find resource named ‘ValidationToolTipTemplate’. Resource names are case sensitive.
at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider serviceProvider
I do indeed have the template resource and it is in my project. Not sure where else to find help for this… It errors out with a Object not set to an instance..
Would u please send a example for me?
sunny29301@163.com,I have some problem with the data binding,It shows nothing.Thank u very much
Please send me the code mrachek@gmail.com
To fix the problem Andreas and Mathew talk about remove the Padding=2 from the Border in the ComboBoxItem Style
Thanks for providing the “Padding=2″ removal suggestion, and while it does indeed work, it jams the checkboxes up so that there’s no space between them! It’s a great control, but shame I’m still a WPF newbie and am not able to solve things such as this for myself!
Hi Adi, Can u plz send me the code of above control. i am in need of the same. plz help me……………..
Pls send me the code.
roshilk@gmail.com
Hi Adi,
Code works a charm after a bit of fiddling.
Most appreciated. Saved me some time and learned interesting stuff.
Thanks mate.
am in urgent need of this control. please send me at the given email id. please help me out guys….
ankur_juneja2004@yahoo.co.in
Hi mochy,
I am facing an problem in binding the ItemsSource using the Binding Path. The item source does not bind by using MVVM. When i bind directly in code behind it is working perfectly.
I tried by setting by the binding using the Dependency property but did not work as well.
You have mentioned that you were able to achive this control in MVVM. Can you please send me the complete solution to sivasankar.s4u@gmail.com
Thanks,
Siva
where could i get this code sample.
Plz Send source code of this article. Thanks
can you please help me how to implement combobox with checkbox in windows form application(c sharp)……gurpreetsingh225@hotmail.com
If anyone knows how to implement this control in datagrid. Please share your code to khyati.shah@yahoo.co.in.
hi this is nice artical , but i dont have that much knowledge to understand , please explain me the full atrical particularlly and send this to my mail address sivakumarmr10@gmail.com , thankq very much
Why do you use HierarchicalDataTemplate instead of just DataTemplate?
i had used the Usercontrol but iam getting This Error So please Rectify this error
error:
Provide value on ‘System.Windows.Markup.StaticResourceHolder’ threw an exception.
Is there anyway I can uncheck all the checked items programatically?? I tried change in datasource (itemsource) but it didnt work out. What will be the best way to reinitilize these combos??
Great solution. Can you mail me the control code at nirnirkal@yahoo.com
Great work buddy…but i’m find it hard to implement…i would appreciate if you could mail the solution on my email ID : dkale86@gmail.com
Can you please mail the solution at nishanth2@gmail.com? Thanks in advance.
please mail solution to me at
rohit.arora@irissoftware.com
Thanks
I need a solutions hard to implement please mail
me : ramakrishna.bariki@gmail.com
this is excellent!! Great work!
can someone please mail the source to me at bhardwaj.cs@gmail.com
Great!
Can someone please mail the source code or better a small working project to me at hb.itdev@gmail.com
I’m not able to use the control without error at runtime
Hi
This is a great article and useful to me.But i need some more events.I have two groups of checkboxes country and state.When i select one checkbox in country combo then the relevant states of the country should appear in state combo.I am not able to fire any event which will refresh the state combo.Can someone help me to resolve the issue. It will be a great pleasure if you could send the solution to my mail urvenkatg@gmail.com
Thanks in advance
Venkat
Please, post or send me an example?
Best Regards
Genial code…..thanks a lot…
Some of the brushes used as StaticResource in the user control in the xaml file are missing. It would be great if you can add it.
I am getting
Visual Studio designer gave an error dialog “Provide value on ‘System.Windows.Markup.StaticResourceHolder’ threw an exception.”
when i try to use control in wpf form
Great work buddy…but i’m find it hard to implement…i would appreciate if you could mail the solution on my email ID : jjalexrayer@yahoo.com
I try to get it work but seem to be not working well. Can some send me the code on my email: cjwiphone@hotmail.com. Thank you very much.
Hi its workling fine. but when i select a item and click directly on button results are not obtained as combo box requires a click event after the selection.
any suggestion about this.
thank u
Remove the SolidBorderBrush in the xaml and it will remove the error
System.Windows.Markup.StaticResourceHolder’ threw an exception
Good work! Can you mail me the control code and a working sample: at valefior AT inwind DOT it?
Thanks
I am using MS VS 2010. I have create component as you described on the top and created it in C#.
Now i want to use the component in VB.NET but it say ‘Object reference not set to an instance of object’
Please advise
Would you please upload ZIP file with latest c# code, which i can use in VB.NET?
Great solution it is Working fine, but how to implement Cascading Drop Down lists,, in my project i have to develop it for States, Districts and Mandals
Great Combo Box, Thanks.
Mine throws an exception when I try to set IsEnabled = “false”
It also doesn’t handle TabOrdering very well, for example if you add the property: KeyboardNavigation.TabIndex=”11″
Because it doesn’t work I try to set it to be NOT a tabstop, but that doesn’t work either, as it still stops on this combo box. KeyboardNavigation.IsTabStop=”false”
Otherwise great work, thanks
My brother recommended I might like this website. He was entirely correct. This submit really produced my day. You cann’t consider merely how so much time I had spent for this information! Thank you!
I’m assuming the code I’m working with came from this blog because there are just too many similarities. The control for its normal use is working fine but I’ve run into a problem that I cannot figure out. If I have a number of these checkboxes (let’s say 4 calling them A, B, C and D). If I manually set checkbox B with a selection and then checkbox C with a selection all is good. Now I have a menu item that lets me copy the settings of one checkbox to all the others. So if I select checkbox C and say “copy to all” all the settings are updated on all the checkboxes and the text is also update except for any checkbox that I set manually. So in my example above, copying C to A, B and D all the settings are updated but the text on B is not. I cannot figure out what is controlling (stopping) the update. Does anyone have any clues? I’m very new to WPF/XAML/C#.
Great control, please send me the working code on my gmail address
pradeepkandale@gmail.com
Anyone can send me the control code? fsimchi@gmail.com
I got it to work on its own but I am not able to connect data to itemsouce using MVVM pattern although it works from code behind. Also items are not visible but when I select them it appears int the textbox!!
Any ideas?
thx!! please send me olso | http://blogs.microsoft.co.il/justguy/2009/01/19/wpf-combobox-with-checkboxes-as-items-it-will-even-update-on-the-fly/ | CC-MAIN-2015-32 | refinedweb | 4,177 | 50.94 |
On 08/08/12 12:36, Adam Borowski wrote: > Could you please tell me a single benefit from such a change? All I see are > downsides. It would degrade tab completion and pollute the namespace. Access to programs without the need to specify the full path. Not all programs in the sbin directories require root privileges. It is about providing good defaults for users. > The reason you say, is a single obsolete tool, ifconfig, being in the wrong > directory. So let's instead move it to /bin/ -- or preferably, to /dev/null > (unless depended upon). Not just ifconfig, there is also route, iwconfig, blkid etc. And moving them to other directories and add symlinks from sbin/$PROG to bin/$PROG is error prone. | https://lists.debian.org/debian-devel/2012/08/msg00174.html | CC-MAIN-2014-23 | refinedweb | 123 | 68.16 |
On Thu, 6 Jul 2017 14:15:49 +0200Ingo Molnar <mingo@kernel.org> wrote:> * Masami Hiramatsu <mhiramat@kernel.org> wrote:> > > > Also, 'function_offset_within_entry' is way too long a name, and it's also a > > > minomer I think. The purpose of this function is to enforce that the relative > > > 'offset' of a new probe is at the standard function entry offset: i.e. 0 on most > > > architectures, and some ABI dependent constant on PowerPC, right?> > > > > > That's not at all clear from that name, plus it's a global namespace symbol, yet > > > has no 'kprobes' prefix. So it should be named something like > > > 'kprobe_offset_valid()' or such, with an arch_kprobe_offset_valid() counterpart.> > > > Hmm, I would rather like kprobe_within_entry(), since offset != 0 is> > actually valid for normal kprobe, that is kretprobe and jprobe limitation.> > But what entry? That it's within a range or that offset is always 0 is really an > implementational detail: depending on what type of kprobe it is, it is either > validly within the confines of the specified function symbol or not.Hmm, right. In most cases, it just checks the address (symbol+offset) ison the function entry.> What _really_ matters to callers is whether it's a valid kprobe to be inserted > into that function, right?No, for that purpose, kprobes checks it in other places (kprobe_addr() and check_kprobe_address_safe()). This function is an additional safety checkonly for kretprobe and jprobe which must be placed on the function entry.(kprobe can probe function body but kretprobe and jprobes are not)> I.e. the long name came from over-specifying what is done by the function - while > simplifying makes it actually more meaningful to read.I see, but kprobe_offset_valid is too simple. How about kprobe_on_func_entry()?Thank you,-- Masami Hiramatsu <mhiramat@kernel.org> | https://lkml.org/lkml/2017/7/6/860 | CC-MAIN-2018-47 | refinedweb | 290 | 66.33 |
Created on 2014-01-14 19:46 by barry, last changed 2014-02-23 07:06 by larry. This issue is now closed.
I've been debugging a crash in nose 1.3.0, the root cause of which turned out to be an instance containing an attribute which itself was an instance of the following class (boiled down):
class Picky:
def __getstate__(self):
return {}
def __getattr__(self, attr):
return None
This crashes with a TypeError in Python 2.7 and Python 3 (albeit with slightly different tracebacks; and Python 3 is more difficult to debug because the TypeError doesn't include any useful information).
TypeError: 'NoneType' object is not callable
The culprit is __getattr__() returning None. In Python 3 for example, pickle tries to get the object's __reduce_ex__() function and then call it.
The problem is the (IMHO) bogus __getattr__() and I'm not sure why nose has this. But I wonder if the pickle documentation should warn against this kind of thing.
This isn't a bug in Python - the crash makes sense when you understand the implications, but perhaps a warning in the docs would have helped prevent this nose bug in the first place. I suppose I could also see improving _pickle.c to provide some additional feedback on the offending attribute, but that's probably more difficult.
It's okay to close this as won't fix if we can't think of appropriate wording. It's enough that there's a record of this issue for search engines now.
Hmm, actually, this is a regression in Python 3.4. Let's amend the test class to include a __getnewargs__():
class Picky(object):
"""Options container that returns None for all options.
"""
def __getstate__(self):
return {}
def __getnewargs__(self):
return ()
def __getattr__(self, attr):
return None
This class is picklable in Python 2.7 - 3.3, but not in 3.4.
This is a duplicate of #16251, no? Pickle looks up dunder ;) methods on instances rather than on classes, so __getattr__() gets triggered unexpectedly. I had to work around this in some code of mine by special-casing in __getattr__() names that start with '_'. I've said my peace over in #16251.
I'll go ahead and dupe this to 16251, but will note the __getnewargs__() regression in 3.4.
Fixed. Should be in 3.4.0.
I'll deal with #16251 in 3.5.
(See)
My understanding is, this is fixed, and cherry-picked into 3.4. If that's in error please reopen. | https://bugs.python.org/issue20261 | CC-MAIN-2018-26 | refinedweb | 421 | 74.19 |
libbase32
libbase32 is a C library to encode and decode integers using Douglas Crockford's Base 32 Encoding.
Synopsis
#include "base32.h" int base32_decode(const char* string); const char* base32_encode(int x); char* base32_encode_r(int x, char* dst); BASE32_STRING_SIZE(x);
How it works
base32_decode decodes a string encoded in base 32 and returns the
corresponding integer:
int x = base32_decode("1A");
base32_encode ignores the character
'-', so
"1-A" is the same as
"1A".
If there is any invalid character in the string, it returns -1. Otherwise
base32_decode only returns positive integer, the call
base32_decode("-2")
will return 2 and not -2 since
'-' characters are ignored.
base32_encode encodes an integer into a string.
char* s = base32_encode(42);
base32_encode returns a pointer to a string containing
"1A". The string will
be modified by subsequent calls to
base32_encode. If you want to keep the
result you must copy it.
base32_encode is not thread-safe, but
base32_encode_r is.
base32_encode_r encodes an integer and store the result into the passed
string.
char buffer[BASE32_STRING_SIZE(int)]; base32_encode_r(42, buffer);
base32_encode_r returns a pointer to
buffer which contains
"1A". You can
use
base32_encode_r in an expression, since it returns a pointer to the
modified string:
char buffer[BASE32_STRING_SIZE(int)]; printf("result: %s\n", base32_encode_r(42, buffer));
The macro
BASE32_STRING_SIZE returns the number of bytes needed to store a
variable or a type.
void function(int x) { char buffer[BASE32_STRING_SIZE(x)]; printf("result: %s\n", base32_encode_r(42, buffer); }
How to use libbase32
libbase32 can be used like a regular library. It can also be embedded into a C/C++ project. Copy base32.c and base32.h into the source directory, and add the files to the build system. libbase32 is small and shouldn't impact the size of the project too much.
libbase32 is licensed under the ISC license, a simple, permissive, BSD-like license. | http://henry.precheur.org/projects/base32.html | CC-MAIN-2018-17 | refinedweb | 306 | 65.22 |
J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
This is part two in a series that explores J2ME with MIDP 2.0. "Part 1: Creating MIDlets" showed you how to acquire, install, and use the Wireless Toolkit for developing MIDlets. Part one also showed how to develop MIDlets without using the Toolkit, which is important in order to understand the behind-the-scenes activity involved in creating a MIDlet. Part one finished with an exploration of the lifecycle of a MIDlet, with a step-by-step guide through the events in the life.
Let's start with a discussion of the overall architecture of the UI elements.
User Interface Architecture
MIDP 2.0 provides UI classes in two packages,
javax.microedition.lcdui and
javax.microedition.lcdui.game, where
lcdui stands for liquid crystal display user interface (LCD UI). As expected, the game package contains classes for development of a wireless game UI. I will discuss this package in the next part of this series.
The UI classes of of MIDP 2.0's
javax.microedition.lcdui package can be divided into two logical groups: the high- and low-level groups.. These classes are shown in Figure 1.
Figure 1. High-level MIDP 2.0 UI classes
The classes of the low-level group are perfect for MIDlets where precise control over the location and display of the UI elements is important and required. Of course, with more control comes less portability. If your MIDlet is developed using these classes, it may not be deployable on certain devices, because they require precise control over the way they look and feel. There are only two classes in this group, and they are shown in Figure 2.
Figure 2. Low-level MIDP 2.0 UI classes
There is another class in the low-level group called
GameCanvas, which is not shown here, as it will be discussed in the next part of this series.
For you to be able to show a UI element on a device screen, whether high- or low-level, it must implement the
Displayable interface. A displayable class may have a title, a ticker, and certain commands associated with it, among other things. This implies that both the
Screen and
Canvas classes and their subclasses implement this interface, as can be seen in Figure 3. The
Graphics class does not implement this interface, because it deals with low-level 2D graphics that directly manipulate the device's screen.
Figure 3.
Canvas and
Screen implement the
Displayable interface
A
Displayable class is a UI element that can be shown on the device's screen while the
Display class abstracts the display functions of an actual device's screen and makes them available to you. It provides methods to gain information about the screen and to show or change the current UI element that you want displayed. Thus, a MIDlet shows a
Displayable UI element on a
Display using the
setCurrent(Displayable element) method of the
Display class.
As the method name suggests, the
Display can have only one
Displayable element at one time, which becomes the current element on display. The current element that is being displayed can be accessed using the method
getCurrent(), which returns an instance of a
Displayable element. The static method
getDisplay(MIDlet midlet) returns the current display instance associated with your MIDlet method.
A little bit of actual code here would go a long way in helping understand the MIDlet UI concepts that we have just discussed. Rather than write new code, let's try and retrofit our understanding on the Date-Time MIDlet example from part one, which is reproduced in Listing 1.
package com.j2me.part1;
import java.util.Date;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
public class DateTimeApp extends MIDlet {
Alert timeAlert;
public DateTimeApp() {
timeAlert = new Alert("Alert!");
timeAlert.setString(new Date().toString());
}
public void startApp() {
Display.getDisplay(this).setCurrent(timeAlert);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Listing 1. DateTimeApp MIDlet
A
Displayable UI element, an
Alert, is created in the constructor. When the device's Application Management Software (AMS) calls the
startApp() method, the current display available for this MIDlet is extracted using the
Display.getDisplay() method. The
Alert is then made the current item on display, by setting it as a parameter to the
setCurrent() method.
As seen from Figure 1, there are four high-level UI elements that can be displayed on a MIDlet's screen. Let's discuss each of these elements in detail.
Alert
You already know how to create a basic alert message from Listing 1. Alerts are best used in informational or error messages that stay on the screen for a short period of time and then disappear. You can control several aspects of an alert by calling the relevant methods or using the right constructor.
- The title must be set while creating the alert and it cannot be changed afterwards:
Alert("Confirm?");.
- To set the message the alert displays use,
setString("Message to display")or pass the message as part of the constructor,
Alert( "Confirm", "Are you sure?", null, null);.
- Use
setTimeout(int time)to set the time (in milliseconds) for which the alert is displayed on the screen. If you pass
Alert.FOREVERas the value of
time, you will show the alert forever and make the alert a modal dialog.
- There are five types of alerts defined by the class
AlertType:
ALARM,
CONFIRMATION,
ERROR,
INFO, and
WARNING. These have different looks and feels and can have a sound played along with the alert.
- Associate an image with the alert using the method
.
setImage(Image img);
- Set an indicator with the alert using
setIndicator(Gauge gauge);method.
List
A list contains one or more choices (elements), which must have a text part, an optional image part, and an optional font for the text part. The
List element implements the
Choice interface, which defines the basic operations of this element. The list must itself have a title, and must define a policy for the selection of its elements. This policy dictates whether only one element can be selected (
Choice.EXCLUSIVE), multiple elements can be selected (
Choice.MULTIPLE), or the currently highlighted element is selected (
Choice.IMPLICIT). Figure 4 shows the difference between the three selection policies.
Figure 4. Selection policies for
List elements
You can create a list in one of two ways.
- Create an list that contains no elements, and then append or insert individual
elements.
- Create the elements beforehand and then create a list with these elements.
Listing 2 shows both ways.
[/prettify][/prettify]
[prettify] package com.j2me.part2; import javax.microedition.lcdui.List; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.Display; import javax.microedition.midlet.MIDlet; public class ListExample extends MIDlet { List fruitList1; List fruitList2; public ListExample() { fruitList1 = new List("Select the fruits you like", Choice.MULTIPLE); fruitList1.append("Orange", null); fruitList1.append("Apple", null); fruitList1.insert(1, "Mango", null); // inserts between Orange and Apple String fruits[] = {"Guava", "Berry", "Kiwifruit"}; fruitList2 = new List( "Select the fruits you like - List 2", Choice.IMPLICIT, fruits, null); } public void startApp() { Display display = Display.getDisplay(this); display.setCurrent(fruitList1); try{ Thread.currentThread().sleep(3000); } catch(Exception e) {} display.setCurrent(fruitList2); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }
Listing 2. Using
Lists
List elements can be modified after the list has been created. You can modify individual elements by changing their text, text font, or image part, using the list index (starting at 0). You can delete elements using
delete(int index) or
deleteAll(). Any changes take effect immediately, even if the list is the current UI element being shown to the user.
TextBox
Text is entered by the user using a textbox. Like the other UI elements, a textbox has simple features that can be set based on your requirements. You can restrict the maximum number of characters that a user is allowed to enter into a textbox, but you need to be aware of the fact that the implementation of this value depends upon the device that you are running it on. For example, suppose that you request that a textbox is allowed a maximum of 50 characters, by using
setMaxSize(50), but the device can only allocate a maximum of 32 characters. Then, the user of your MIDlet will only be able to enter 32 characters.
You can also constrain the text that is accepted by the textbox, as well as modify its display using bitwise flags defined in the
TextField class.);.
There are six constraint settings for restricting content:
ANY,
NUMERIC,
PHONENUMBER,
URL, and
DECIMAL.
ANY allows all kinds of text to be entered, while the rest constrain according to their names. Similarly, there are six constraint settings that affect the display. These are:
UNEDITABLE,
SENSITIVE,
NON_PREDICTIVE,
INITIAL_CAPS_WORD, and
INITIAL_CAPS_SENTENCE. Not all of these settings may be functional in all devices..
package com.j2me.part2;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
public class TextBoxExample extends MIDlet {
private TextBox txtBox1;
private TextBox txtBox2;
public TextBoxExample() {
txtBox1 = new TextBox(
"Your Name?", "", 50, TextField.ANY);
txtBox2 = new TextBox(
"Your PIN?",
"",
4,
TextField.NUMERIC | TextField.PASSWORD);
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(txtBox1);
try{
Thread.currentThread()Sleep(5000);
} catch(Exception e) {}
txtBox1.setString("Bertice Boman");
try{
Thread.currentThread()Sleep(3000);
} catch(Exception e) {}
// inserts 'w' at the 10th index to make the
// name Bertice Bowman
txtBox1.insert("w", 10);
try{
Thread.currentThread()Sleep(3000);
} catch(Exception e) {}
display.setCurrent(txtBox2);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Listing 3. Using
TextBoxes
The listing creates two textboxes: one that accepts anything under 50 characters, and one that accepts only four numeric characters that are not shown on the screen. If you try entering anything other than numbers in the numeric-only box, the device will not accept it, but the actual behavior may vary across actual devices.
Form
A form is a collections of instances of the
Item interface. The
TextBox class (discussed in the preceding section) is a standalone UI element, while the
TextField is an
Item instance. Essentially, a textbox can be shown on a device screen without the need for a form, but a text field requires a form.
An item is added to a form using the
append(Item item) method, which simply tacks the added item to the bottom of the form and assigns it an index that represents its position in the form. The first added item is at index 0, the second at index 1, and so on. You can also use the
insert(int index, Item newItem) method to insert an item at a particular position or use
set(int index, Item newItem) to replace an item at a particular position specified by the index.
There are eight
Item types that can be added to a form.
StringItem: A label that cannot be modified by the user. This item may contain a title and text, both of which may be null to allow it to act as a placeholder. The
Formclassclass provides a shortcut method for adding an image:
append(Image image). More about images in a later section.
CustomItem:
CustomItemis an abstract class that allows the creation of subclasses that have their own appearances, their own interactivity, and their own notification mechanisms. If you require a UI element that is different from the supplied elements, you can subclass
CustomItemto create it for addition to a form.
These items (except
CustomItem) can be seen in Figure 5, and the corresponding code is shown in Listing 4. (NOTE: The image, duke.gif, should be kept in the res folder of this MIDlet application.).midlet.MIDlet;
public class FormExample extends MIDlet { to segregate) {}
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Listing 4. Using forms
Figure 5. The elements of a form
Images, Tickers, and Gauges
Using images, tickers, and gauges as UI elements in MIDlets is quite straightforward. A gauge, as you saw in the last section, is an item that can only be displayed on a form to indicate progress or to control a MIDlet feature (like volume). A ticker, on the other hand, can be attached to any UI element that extends the
Displayable abstract class, and results in a running piece of text that is displayed across the screen whenever the element that is attached to it is shown on the screen. Finally, an image, can be used with various UI elements, including a form, as we saw in the last section.
Since the ticker can be used with all displayable elements, it provides a handy way to display information about the current element on the screen. The
Displayable class provides the method
setTicker(Ticker ticker), and the ticker can itself be created using its constructor
Ticker(String msg), with the message that you want the ticker to display. By using
setString(String MSG), you can change this message, and this change is effected immediately. For example, the form used in the previous section can have its own ticker displayed by setting
form.setTicker(new Ticker("Welcome to Vandalay Industries!!!")). This will result in a ticker across the top of the screen (in the Toolkit's emulator), while the user is filling out the form. This is shown in Figure 6.
Figure 6. Setting a
Ticker on a
Displayable
In the previous section, we saw an example of a gauge in a non-interactive mode. It was there to represent the progress of a form being filled out by the MIDlet user. A non-interactive gauge can be used to represent the progress of a certain task; for example, when the device may be trying to make a network connection or reading a datastore, or when the user is filling out a form. In the previous section, we created a gauge by specifying four values. The label ("Step 1 of 3"), the interactive mode (false), the maximum value (3) and the initial value (1). However, when you don't know how long a particular activity is going to take, you can use the value of
INDEFINITE for the maximum value.
A non-interactive gauge that has an
INDEFINITE maximum value acquires special meaning. (You cannot create an interactive gauge with an
INDEFINITE maximum value.) This type of gauge can be in one of four states, and this is reflected by the initial value (which is also the current value of the gauge). These states are
CONTINUOUS_IDLE,
INCREMENTAL_IDLE,
CONTINUOUS_RUNNING, and
INCREMENTAL_UPDATING. Each state represents the best effort of the device to let the user know the current activity of the MIDlet, and you can use them to represent these states yourself. Listing 5 shows an example of using these non-interactive gauges, along with an example of an interactive gauge. Remember that a
Gauge is a UI
Item, and therefore, can only be displayed as part of a
Form.
Package com.j2me.part2;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
public class GaugeExample extends MIDlet {
private Form form;
private Gauge niIndefinate_CI;
private Gauge niIndefinate_II;
private Gauge niIndefinate_CR;
private Gauge niIndefinate_IU;
private Gauge interactive;
public GaugeExample() {
form = new Form("Gauge Examples");
niIndefinate_CI =
new Gauge(
"NI - Cont Idle",
false,
Gauge.INDEFINITE,
Gauge.CONTINUOUS_IDLE);
form.append(niIndefinate_CI);
niIndefinate_II =
new Gauge(
"NI - Inc Idle",
false,
Gauge.INDEFINITE,
Gauge.INCREMENTAL_IDLE);
form.append(niIndefinate_II);
niIndefinate_CR =
new Gauge(
"NI - Cont Run",
false,
Gauge.INDEFINITE,
Gauge.CONTINUOUS_RUNNING);
form.append(niIndefinate_CR);
niIndefinate_IU =
new Gauge(
"NI - Inc Upd",
false,
Gauge.INDEFINITE,
Gauge.INCREMENTAL_UPDATING);
form.append(niIndefinate_IU);
interactive =
new Gauge(
"Interactive ",
true,
10,
0);
form.append(interactive);
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Listing 5. Using
Gauges
Each mobile device will use its own set of images to represent these gauges. This will, in all probability, be different from the gauges that you will see if you run this listing in the Emulator supplied with the Toolkit.
You can also associate an image with an
Alert and a
Choice-based UI element. When an image is created, either by reading from a physical location or by making an image in-memory, it exists only in the off-screen memory. You should, therefore, be careful while using images, and restrict the size of images to the minimum possible to avoid filling the device's available memory.
The
Image class provides several static methods to create or acquire images for use in MIDlets. An image that is created in-memory, by using the
createImage(int width, int height) method, is mutable, which means that you can edit it. An image created this way initially has all of its pixels set to white, and you can acquire a graphics object on this image by using the method
getGraphics() to modify the way it is rendered on screen. More about the
Graphics object follows in the low-level API section.
To acquire an immutable image, you can use one of two methods:
createImage(String imageName) or
createImage(InputStream stream). The first method is used for looking up images from an associated packaged .jar file, while the second method is good for reading an image over a network. To create an immutable image from in-memory data, you can either use
createImage(byte[] imageData, int imageOffset, int imageLength) or
createImage(Image source). The first method allows you to form an image out of a byte array representation, while the second allows the creation of an image from an existing image.
Note that the MIDlet specification mandates support for the Portable Network Graphics (PNG) format for images. Thus, all devices that support MIDlets will display a *.png image. These devices may support other formats, especially GIF and JPEG formats, but that is not a guarantee.
You have already seen an example of acquiring an image in the section on forms. In Listing 4, an image was wrapped up in an
ImageItem class so that it could be displayed in a form. The image was kept in the res folder of the MIDlet for the Toolkit and the Emulator to find. The
createImage(String imageName) method uses the
Class.getResourceAsStream(String imageName) method to actually locate this image. The Toolkit takes care of packaging this image in the right folder when you create a ,jar file. In this case, this will be the top-level .jar folder. Make sure that whenever you reference images in your MIDlets that the images are kept in the right location. For example, if you want to keep all of your images for a MIDlet in an image folder in the final packaged .jar file, and not the top-level .jar folder, you will need to keep these images under an image folder under the res folder itself. To reference any of these images, you will need to ensure that you reference them via this images folder. For example:
createImage("/images/duke.gif"); will reference the image duke.gif under the images folder.
Handling User Commands
None of the UI elements so far have allowed any interaction from the user! A MIDlet interacts with a user through commands. A command is the equivalent of a button or a menu item in a normal application, and can only be associated with a displayable UI element. Like a ticker, the
Displayable class allows the user to attach a command to it by using the method
addCommand(Command command). Unlike a ticker, a displayable UI element can have multiple commands associated with it.
The
Command class holds the information about a command. This information is encapsulated in four properties. These properties are: a short label, an optional long label, a command type, and a priority. You create a command by providing these values in its constructor:
Command exitCommand =,
ITEM,
SCREEN, and
STOP. The
SCREEN type relates to an application-defined command for the current screen. Both
SCREEN and
ITEM will probably never have any device-mapped keys.
By specifying a priority, you tell the AMS running the MIDlet where and how to show the command. A lower value for the priority is of higher importance, and therefore indicates a command that the user should be able to invoke directly. For example, you would probably always have an exit command visible to the user and give it a priority of 1. Since the screen space is limited, the device then bundles less-important commands into a menu. The actual implementation varies from device to device, but the most likely scenario involves one priority-1 command displayed along with an option to see the other commands via a menu. Figure 7 shows this likely scenario.
Figure 7. The way commands are displayed. The menu pops up when the user presses the key corresponding to the menu command.
The responsibility for acting on commands is performed by a class implementing the
CommandListener interface, which has a single method:
commandAction(Command com, Displayable dis). However, before command information can travel to a listener, The listener is registered with the method
setCommandListener(CommandListener listener) from the
Displayable class.
Putting this all together, Listing 6 shows how to add some commands to the form discussed in Listing 4..lcdui.Command;
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.CommandListener;
public class FormExample
extends MIDlet
implements CommandListener {) {}
// create some commands and add them
// to this form
form.addCommand(
new Command("EXIT", Command.EXIT, 2));
form.addCommand(
new Command("HELP", Command.HELP, 2));
form.addCommand(
new Command("OK", Command.OK, 1));
// set itself as the command listener
form.setCommandListener(this);
}
// handle commands
public void commandAction(
Command com, Displayable dis) {
String label = com.getLabel();
if("EXIT".equals(label))
notifyDestroyed();
else if("HELP"Equals(label))
displayHelp();
else if("OK"Equals(label))
processForm();
}
public void displayHelp() {
// show help
}
public void processForm() {
// process Form
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Listing 6. Adding commands to a form
The differences from Listing 4 are highlighted in bold. The command listener in this case is the form class itself, and therefore, it implements the
commandAction() method. Note that this method also accepts a displayable parameter, which is very useful. Because commands are immutable, they can be attached to multiple displayable objects, and this parameter can help distinguish which displayable object invoked the command.
Working with the Low-Level API
The low-level API for MIDlets is composed of the
Canvas and
Graphics classes (we will discuss the
GameCanvas class in the next article). The
Canvas class is abstract; you must create your own canvases to write/draw on by extending this class and providing an implementation for the
paint(Graphics g) method, in which the actual drawing on a device is done. The
Canvas and
Graphics classes work together to provide low-level control over a device.
Let's start with a simple canvas. Listing 7 shows an example canvas that draws a black square in the middle of the device screen.
g.setColor(0x000000); // make sure it is black
g.fillRect(
getWidth()/2 - 10,
getHeight()/2 - 10,
20, 20);
}
}
Listing 7. Creating and displaying a
Canvas
The class
MyCanvas extends
Canvas and overrides the
paint() method. Although this method is called as soon as the canvas is made the current displayable element (by
setCurrent(myCanvas)), it is a good idea to call the
repaint() method on this canvas soon afterwards. The
paint() method accepts a
Graphics object, which provides methods for drawing 2D objects on the device screen. For example, in Listing 7, a black square is created in the middle of the screen using this
Graphics object. Notice that before drawing the square, using the
fillRect() method, the current color of the
Graphics object is set to black by using the method
g.setColor(). This is not necessary, as the default color is black, but this illustrates how to change it if you wanted to do so.
If you run this listing, the output on the emulator will be as shown in Figure 8.
Figure 8. Drawing a single square in the middle of a
Canvas
Notice the highlighted portion at the top in Figure 8. Even though the MIDlet is running, the AMS still displays the previous screen. This is because in the
paint() method, the previous screen was not cleared away, and the square was drawn on the existing surface. To clear the screen, you can add the following code in the
paint() method, before the square is drawn.
g.setColor(0xffffff);
// sets the drawing color to white
g.fillRect(0, 0, getWidth(), getHeight());
// creates a fill rect which is the size of the screen
Note that the
getWidth() and
getHeight() methods return the size of the display screen as the initial canvas, which is the whole display screen. Although the size of this canvas cannot be changed, you can change the size and location of the clip area in which the actual rendering operations are done. A clip area, in
Graphics, is the area on which the drawing operations are conducted. The
Graphics class provides the method
setClip(int x, int y, int width, int height) to change this clip area, which in an initial canvas is the whole screen, with the top left corner as the origin (0, 0). Thus, if you use the method
getClipWidth() (or
getClipHeight()) on the
Graphics object passed to the paint method in Listing 7, it returns a value equal to the value returned by the
getWidth() (or
getHeight()) method of the
Canvas.
The
Graphics object can be used to render not only squares and rectangles, but arcs, lines, characters, images, and text, as well. For example, to draw the text "Hello World" on top of the square in Listing 7, you can add the following code before or after the square is drawn:
g.drawString("Hello World", getWidth()/2, getHeight()/2 - 10,
Graphics.HCENTER | Graphics.BASELINE);
This will result in the screen shown in Figure 9.
Figure 9. Drawing text using the
Graphics object
Text, characters, and images are positioned using the concept of anchor points. The full syntax of the
drawString() method is
drawstring(String text, int x, int y, int anchor). The anchor positioning around the
x,
y coordinates is specified by bitwise
ORing of two constants. One constant specifies the horizontal space (
LEFT,
HCENTER,
RIGHT) and the other specifies the vertical space (
TOP,
BASELINE,
BOTTOM). Thus, to draw the "Hello World" text on top of the square, the anchor's horizontal space needs to be centered around the middle of the canvas (
getWidth()/2) and hence, I have used the
Graphics.HCENTER constant. Similarly, the vertical space is specified by using the
BASELINE constant around the top of the square (
getHeight()/2 - 10). You can also use the special value of 0 for the anchor, which is equivalent to
TOP | LEFT.
Images are similarly drawn and positioned on the screen. You can create off-screen images by using the static
createImage(int width, int height) method of the
Image class. You can get a
Graphics object associated with this image by using the
getGraphics() method. This method can only be called on images that are mutable. An image loaded from the file system, or over the network, is considered an immutable image, and any attempt to get a
Graphics object on such an image will result in an
IllegalStateException at runtime.
Using anchor points with images is similar to using them with text and characters. Images allow an additional constant for the vertical space, specified by
Graphics.VCENTER. Also, since there is no concept of a baseline for an image, using the
BASELINE constant will throw an exception if used with an image.
Listing 8 shows the code snippet from the
MyCanvas class
paint() method that creates an off-screen image, modifies it by adding an image loaded from the file system, and draws a red line across it. Note that you will need the image duke.gif in the res folder of the CanvasExample MIDlet.
// draw a modified image
try {
// create an off screen image
Image offImg = Image.createImage(25, 19);
// get its graphics object and set its
// drawing color to red
Graphics offGrap = offImg.getGraphics();
offGrap.setColor(0xff0000);
// load an image from file system
Image dukeImg =
Image.createImage("/duke.gif");
// draw the loaded image on the off screen
// image
offGrap.drawImage(dukeImg, 0, 0, 0);
// and modify it by drawing a line across it
offGrap.drawLine(0, 0, 25, 19);
// finally, draw this modified off screen
// image on the main graphics screen
// so that it is just under the square
g.drawImage(
offImg, getWidth()/2,
getHeight()/2 + 10,
Graphics.HCENTER | Graphics.TOP);
} catch(Exception e) { e.printStackTrace(); }
Listing 8. Creating, modifying, and displaying an off-screen image on a
Canvas
The resultant screen, when combined with the "Hello World" text drawn earlier, will look like Figure 10.
Figure 10. Text, a square, and a modified image drawn on a
Canvas
The
Canvas class provides methods to interact with the user, including predefined game actions, key events, and, if a pointing device is present, pointer events. You can even attach high-level commands to a canvas, similar to attaching commands on a high-level UI element.
Each
Canvas class automatically receives key events through the invocation of the
keyPressed(int keyCode),
keyReleased(int keyCode), and
keyRepeated(int keyCode). The default implementations of these methods are empty, but not abstract, which allows you to only override the methods that you are interested in. Similar to the key events, if a pointing device is present, pointer events are sent to the
pointerDragged(int x, int y),
pointerPressed(int x, int y), and
pointerReleased(int x, int y) methods.
The
Canvas class defines constants for key codes that are guaranteed to be present in all wireless devices. These key codes define all of the numbers (for example,
KEY_NUM0,
KEY_NUM1,
KEY_NUM2, and so on) and the star (
*) and pound (
#) keys (
KEY_STAR and
KEY_POUND). This class makes it even easier to capture gaming events by defining some basic gaming constants. There are nine constants that are relevant to most games:
UP,
DOWN,
LEFT,
RIGHT,
FIRE,
GAME_A,
GAME_B,
GAME_C, and
GAME_D. But how does a key event translate to a gaming event?
By the use of the
getGameAction() method. Some devices provide a navigation control for moving around the screen, while some devices use the number keys
2,
4,
6, and
8. To find out which game action key was pressed, the
Canvas class encapsulates this information and provides it in the form of the game actions. All you, as a developer, need to do is to grab the key code pressed by the user in the right method, and use the
getGameAction(int keyCode) method to determine if the key pressed corresponds to a game action. As you can guess, several key codes can correspond to one game action, but a single key code may map to, at most, a single game action.
Listing 9 extends the original code from Listing 7 to add key code handling. In this listing, the square in the middle of the screen is moved around with the help of the navigation buttons.
// clear the screen first
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x000000); // make sure it is black
// draw the square, changed to rely on instance variables
g.fillRect(x, y, 20, 20);
}
public void keyPressed(int keyCode) {
// what game action does this key map to?
int gameAction = getGameAction(keyCode);
if(gameAction == RIGHT) {
x += dx;
} else if(gameAction == LEFT) {
x -= dx;
} else if(gameAction == UP) {
y -= dy;
} else if(gameAction == DOWN) {
y += dy;
}
// make sure to repaint
repaint();
}
// starting coordinates
private int x = getWidth()/2 - 10;
private int y = getHeight()/2 - 10;
// distance to move
private int dx = 2;
private int dy = 2;
}
Listing 9. Handling key events to move the square
Notice that in this listing, the code to paint the square has been modified to rely upon instance variables. The
keyPressed() method has been overridden and therefore, whenever the user presses a key, this method is invoked. The code checks if the key pressed was a game key, and based on which game key was pressed, changes the coordinates of the square accordingly. Finally, the call to
repaint() in turn calls the
paint() method, which moves the square on the screen as per the new coordinates.
In this article, you created the UI elements and were introduced to much of the user interface APIs for MIDlets. In the next installment, you will learn to use the Gaming API of MIDP 2.0 present in the package
javax.microedition.lcdui.game.
- Login or register to post comments
- Printer-friendly version
- 106316 reads | https://today.java.net/pub/a/today/2005/05/03/midletUI.html | CC-MAIN-2015-27 | refinedweb | 5,487 | 55.44 |
> > * roman at 248112.vserver.de > | > | Is there a utility function or something to recursivly compare two DOM > | Nodes for equivalence? > > The trouble with that is that there's no definition of what is > required for two XML fragments to be the same. XML just doesn't have > any notion of identity for elements. > > So while there might be such a method you couldn't really trust it to > be The One True Element Comparison Method. Not that such a thing > wouldn't be nice to have... :-( That's obviously true. There is no such standard. I need this, to implement some test cases and want to compare plain XML documents for equivalence, not equality or identity. Equivalent Nodes should meet the following conditions (there are more, but these are the most important): 1. Their (DOM) Node type must be the same. 2. for Elements: - each attribute in one element exists and has the same value in the other element and vice versa - both elements have the same namespace URI (but may have different prefixes) - both elements have the same name - the child elements must be the equivalent (recursion), with adjacent Text Nodes beeing put together. 3. Text Nodes are equivalent, if they have the same data. There may be an option to the function, which specifies, if whitespace is significant or not. 4. The other Node types are pretty straightforward, and since I don't need them, I don't really care about them. If nobody has implemented such a function yet, I think I will do it. Cheers, Roman -- SOAP for Python | https://mail.python.org/pipermail/xml-sig/2003-November/009994.html | CC-MAIN-2017-09 | refinedweb | 263 | 73.27 |
About DirectoryGenerator - simply comment out one line of code:
// protected EntityResolver resolver;
and it will work. SQL example works (partially) - for me, but XSP example -
does not.
There is some problem with namespaces. If in simple-sql2html.xsl replace
<xsl:template
with
<xsl:template
and so on - everything will work.
Does anybody knows what is wrong with namespaces?
Vadim
> -----Original Message-----
> From: Tom Klaasen [mailto:Tom.Klaasen@the-ecorp.com]
> Sent: Monday, August 28, 2000 7:48 AM
> To: 'cocoon-dev@xml.apache.org'
> Subject: RE: Broken examples?
>
>
> You're right, sorry I forgot to mention this.
>
> It is C2 I'm talking about.
>
> tomK
>
> > -----Original Message-----
> > From: Giacomo Pati [mailto:pati_giacomo@yahoo.com]
> > Sent: maandag 28 augustus 2000 12:37
> > To: cocoon-dev@xml.apache.org
> > Subject: Re: Broken examples?
> >
> >
> > --- Tom Klaasen <Tom.Klaasen@the-ecorp.com> wrote:
> > > Has anybody noticed that the SQL page example, as well as the
> > > directory
> > > listing, are broke in the CVS version?
> >
> > Are you taking about C1 or C2?
> >
> >: | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200008.mbox/%3CNEBBKBNHBMFHDJPKGCOBCEJJCAAA.vgritsenko@hns.com%3E | CC-MAIN-2015-40 | refinedweb | 166 | 54.79 |
The concepts of closures and lambda functions are definitely not new ones; they both come from the functional programming world. Functional programming is a style of programming that moves the focus from executing commands to the evaluation of expressions. These expressions are formed using functions, which are combined to get the results we may be looking for. This style of programming was more often used in an academic setting, but it is also seen in the realms of artificial intelligence and mathematics, and can be found in commercial applications with languages like Erlang, Haskell, and Scheme.
Closures were originally developed in the 1960s as part of Scheme, one of the most well-known functional programming languages. Lambda functions and closures are often seen in languages that allow functions to be treated as first-class values, meaning that the functions can be created on the fly and passed as parameters to other languages.
Since that time, closures and lambda functions have found their way out of the functional programming world and into languages like JavaScript, Python, and Ruby. JavaScript is one of the most popular languages that supports closures and lambda functions. It actually uses them as a means to support object-oriented programming, where functions are nested inside other functions to act as private members. Listing 1 provides an example of how JavaScript uses closures.
Listing 1. A JavaScript object built using closures
var Example = function() { this.public = function() { return "This is a public method"; }; var private = function() { return "This is a private method"; }; }; Example.public() // returns "This is a public method" Example.private() // error - doesn't work
As we see in Listing 1, the member functions of the
Example object are defined as closures. Since the private method is scoped to a local variable (vs. the public method attached to the
Example object using this keyword), it is not visible to the outside world.
Now that we've seen some historical perspective on where these concepts have come from, let's look at lambda functions in PHP. The concept of lambda functions is the basis for closures and provides a much-improved way to create functions on the fly vs. the
create_function() function already in PHP.
Lambda functions
Lambda functions (or "anonymous functions," as they are often referred to) are simply throwaway functions that can be defined at any time and are typically bound to a variable. The functions themselves only exist in the scope of the variable of which they are defined, so when that variable goes out of scope, so does the function. The idea of lambda functions comes from mathematics work back in the 1930s. Known as lambda calculus, it was designed to investigate the function definition and application, as well as the concept of recursion. The work from lambda calculus was used to develop functional programming languages, such as Lisp and Scheme.
Lambda functions are handy for a number of instances, most notably for many PHP functions that accept a callback function. One such function is
array_map(), which allows us to walk through an array and apply a callback function to each element of the array. In earlier versions of PHP, the biggest problem with these functions is that there wasn't a clean way to define the callback function; we were stuck taking one of three available approaches to the problem:
- We could define the callback function somewhere else in the code so we know it's available. This is somewhat ugly since it moves part of the implementation of the call elsewhere, which is rather inconvenient for readability and maintainability, especially if we aren't going to use this function elsewhere.
- We could define the callback function in the same code block, but with a name. While this does help keep things together, we need to add an
ifblock around the definition to avoid namespace clashes. Listing 2 is an example of this approach.
Listing 2. Defining a named callback in the same code block
function quoteWords() { if (!function_exists ('quoteWordsHelper')) { function quoteWordsHelper($string) { return preg_replace('/(\w)/','"$1"',$string); } } return array_map('quoteWordsHelper', $text); }
- We can use
create_function(), which has been a part of PHP since V4, to create the function at runtime. While functionally, this does what we want, it has a few disadvantages. One major one is that it is compiled at runtime vs. compile time, which won't permit opcode caches to cache the function. It also is rather ugly syntax-wise, and the string highlighting present in most IDEs simply doesn't work.
Although the functions that accept callback functions are powerful, there isn't a good way to do a one-off callback function without some very inelegant work. With PHP V5.3, we can use lambda functions to redo the above example in a much cleaner way.
Listing 3.
quoteWords() using a lambda function for the callback
function quoteWords() { return array_map('quoteWordsHelper', function ($string) { return preg_replace('/(\w)/','"$1"',$string); }); }
We see a much cleaner syntax for defining these functions, which can be optimized for performance by opcode caches. We've also gained improved readability and compatibility with string highlighting. Let's build upon this to learn about using closures in PHP.
Closures
Lambda functions by themselves don't add much in terms of something we couldn't do before. As we saw, we could do all of this using
create_function(), albeit with uglier syntax and less-than-ideal performance. But they are still throwaway functions and don't maintain any sort of state, which limit what we can do with them. This is where closures step in and take the lambda functions to the next level..
Let's take a look at how to define a closure in PHP. Listing 4 shows an example of a closure that will import a variable from the outside environment and simply print it out to the screen.
Listing 4. Simple closure example
$string = "Hello World!"; $closure = function() use ($string) { echo $string; }; $closure(); Output: Hello World!. Listing 5 shows an example of this.
Listing 5. Closure passing variables by reference
$x = 1 $closure = function() use (&$x) { ++$x; } echo $x . "\n"; $closure(); echo $x . "\n"; $closure(); echo $x . "\n"; Output: 1 2 3
We see the closure using the outside variable $x and incrementing it each time the closure is called. We can mix variables passed by value and by reference easily within the use clause, and they will be handled without any problem. We can also have functions that directly return closures, as we see in Listing 6. In this case, the closure's lifetime will actually be longer than the method that has defined them.
Listing 6. Closure returned by a function
function getAppender($baseString) { return function($appendString) use ($baseString) { return $baseString . $appendString; }; }
Closures and objects
Closures can be a useful tool not only for procedural programming but also for object-oriented programming. Using closures serves the same purpose in this situation as it would outside of a class: to contain a specific function to be bound within a small scope. They also are just as easy to use within our objects as they are outside an object.
When defined within an object, one handy thing is that the closure has full access to the object through the
$this variable, without the need to import it explicitly. Listing 7 demonstrates this.
Listing 7. Closure inside an object
class Dog { private $_name; protected $_color; public function __construct($name, $color) { $this->_name = $name; $this->_color = $color; } public function greet($greeting) { return function() use ($greeting) { echo "$greeting, I am a {$this->_color} dog named {$this->_name}."; }; } } $dog = new Dog("Rover","red"); $dog->greet("Hello"); Output: Hello, I am a red dog named Rover.
Here, we explicitly use the greeting given to the
greet() method in the closure defined within it. We also grab the color and name of the dog, passed in the constructor and stored in the object, within the closure.
Closures defined within a class are fundamentally the same as those defined outside an object. The only difference is the automatic importing of the object through the
$this variable. We can disable this behavior by defining the closure to be static.
Listing 8. Static closure
class House { public function paint($color) { return static function() use ($color) { echo "Painting the house $color...."; }; } } $house = new House(); $house->paint('red'); Output: Painting the house red....
This example is similar to the
Dog class defined in Listing 5. The big difference is that we don't use any properties of the object within the closure, since it is defined as static.
The big advantage of using a static closure vs. a nonstatic one inside an object is for the memory savings. By not having to import the object into the closure, we can save quite a bit of memory, especially if we have many closures that don't need this feature.
One more goody for objects is the addition of a magic method called
__invoke(), which allows the object itself to be called as a closure. If this method is defined, it will be used when the object is called in that context. Listing 9 illustrates this.
Listing 9. Using the
__invoke() method
class Dog { public function __invoke() { echo "I am a dog!"; } } $dog = new Dog(); $dog();
Calling the object reference shown in Listing 9 as a variable automatically calls the
__invoke() magic method, making the class itself act as a closure.
Closures can integrate just as well with object-oriented code, as well as with procedural code. Let's see how closures interact with PHP's powerful Reflection API.
Closures and reflection
PHP has a useful reflection API, which allows us to reverse-engineer classes, interfaces, functions, and methods. By design, closures are anonymous functions, which means they do not appear in the reflection API.
However, a new
getClosure() method has been added to the
ReflectionMethod and
ReflectionFunction classes in PHP for dynamically creating closure from the specified function or method. It acts like a macro in this context, where calling the method of function via the closure makes the function call in the context of where it's defined. Listing 10 shows how this works.
Listing 10. Using the
getClosure() method
class Counter { private $x; public function __construct() { $this->x = 0; } public function increment() { $this->x++; } public function currentValue() { echo $this->x . "\n"; } } $class = new ReflectionClass('Counter'); $method = $class->getMethod('currentValue'); $closure = $method->getClosure() $closure(); $class->increment(); $closure(); Output: 0 1
One interesting side effect of this approach is that it allows us to access private and protected members of a class via a closure, which can be handy for unit testing classes. Listing 11 is an example of accessing a private method in a class.
Listing 11. Accessing a private method in a class
class Example { .... private static function secret() { echo "I'm an method that's hiding!"; } ... } $class = new ReflectionClass('Example'); $method = $class->getMethod('secret'); $closure = $method->getClosure() $closure(); Output: I'm an method that's hiding!
Also, we can use the reflection API to introspect a closure itself, as shown in Listing 12. We simply pass the variable reference to the closure into the constructor of the
ReflectionMethod class.
Listing 12. Inspecting a closure using the reflection API
$closure = function ($x, $y = 1) {}; $m = new ReflectionMethod($closure); Reflection::export ($m); Output: Method [ <internal> public method __invoke ] { - Parameters [2] { Parameter #0 [ <required> $x ] Parameter #1 [ <optional> $y ] } }
One thing to note in terms of backward-compatibility is that the class name
Closure is now reserved by the PHP engine for storing closures, so any classes that use that name will need to be renamed.
The reflection API has great support for closures, as we've now seen, in the form of being able to create them from existing functions and methods dynamically. They can also introspect into a closure just like a normal function can.
Why closures?. One such example occurs when refactoring old code to help simplify it and make it more readable. Take the following example, which shows a logger being used while running some SQL queries.
Listing 13. Code logging SQL queries
$db = mysqli_connect("server","user","pass"); Logger::log('debug','database','Connected to database'); $db->query('insert into parts (part, description) values ('Hammer','Pounds nails'); Logger::log('debug','database','Insert Hammer into to parts table'); $db->query('insert into parts (part, description) values ('Drill','Puts holes in wood'); Logger::log('debug','database','Insert Drill into to parts table'); $db->query('insert into parts (part, description) values ('Saw','Cuts wood'); Logger::log('debug','database','Insert Saw into to parts table');
One thing that sticks out in Listing 13 is how much repeating we are doing. Every call made to
Logger::log() has the same first two arguments. To solve this, we can push that method call into a closure and make the calls against that closure, instead. The resulting code is shown below.
Listing 14. Refactored code logging SQL queries
$logdb = function ($string) { Logger::log('debug','database',$string); }; $db = mysqli_connect("server","user","pass"); $logdb('Connected to database'); $db->query('insert into parts (part, description) values ('Hammer','Pounds nails'); $logdb('Insert Hammer into to parts table'); $db->query('insert into parts (part, description) values ('Drill','Puts holes in wood'); $logdb('Insert Drill into to parts table'); $db->query('insert into parts (part, description) values ('Saw','Cuts wood'); $logdb('Insert Saw into to parts table');
Not only have we made the code cleaner in appearance but we also made it easier to change the log level of the SQL queries log since we only need to make the change in one place now.
Summary
This article demonstrated how useful closures are as a functional programming construct within PHP V5.3 code. We discussed lambda functions and the advantages that closures have over them. Objects and closures get along very well, as we saw by the special handling of closures within object-oriented code. We saw how well we can use the reflection API to create dynamic closures, as well as introspect existing closures.
Resources
Learn
- Start this series with "What's new in PHP V5.3, Part 1: Changes to the object interface." Continue the series with Part 3, and Part 4.
- Learn more about closures at Wikipedia.
- See PHP.net's Request for Comments: Lambda functions and closures for more information about how closures work.
- Read "A PHP V5 migration guide" to learn how to migrate code developed in PHP V4 to V5.
- "Connecting PHP Applications to Apache Derby" shows how to install and configure PHP on Windows® (some steps are applicable to Linux®).
-. | http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html?ca=drs-tp5008 | CC-MAIN-2013-48 | refinedweb | 2,422 | 60.55 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
Is it possible to programmatically create a palette with commands that I specify? I would like to be able to create palettes on demand with certain commands so that a user can dock them.
Hello @kbar,
Thank you for reaching out to us. I am sure you are aware that this has been discussed before and nothing has changed here. It is not possible to programmatically instantiate, open, or populate palettes from the public C++ API. While we technically have the possibility to do it internally, our internal code does not really make use of this either. Which is why such a function does not exist although frequently requested.
There are two options you have:
LoadFile
CommandData
Cheers,
Ferdinand
The result:
The script:
"""Loads a palette file into Cinema 4D.
Showcases the ability of LoadFile() to handle almost all file formats Cinema 4D can deal with,
including layout files for palettes or the whole window.
"""
import c4d
import os
def main() -> None:
"""Loads a palette into Cinema 4D.
"""
# Determine and assert the palette file path, the palette file in this
# example is meant to be located in the same directory as this script.
directory = os.path.dirname(__file__)
paletteFile = os.path.join(directory, "myPalette.l4d")
if not os.path.exists(paletteFile ):
raise OSError(f"The path {paletteFile } does not exist.")
# Open the palette with LoadFile().
c4d.documents.LoadFile(paletteFile)
if __name__ == '__main__':
main() | https://plugincafe.maxon.net/topic/14069/programmatically-create-a-palette | CC-MAIN-2022-27 | refinedweb | 276 | 57.67 |
ec_message_rsrc_set
Name
ec_message_rsrc_set — This function associates I/O object source with the resource name for message
Synopsis
#include "ec_message.h"
|
int **ec_message_rsrc_set** ( | message, | |
| | name, | |
| | io
); | |
ec_message * <var class="pdparam">message</var>;
const char * <var class="pdparam">name</var>;
io_object * <var class="pdparam">io<.
This function associates I/O object source with the resource name for message.
If a resource with the given name does not exist then a new resource is created. If a resource exists with the provided name then the resource's I/O object is replaced with source. The source I/O object will have a reference added to it. The previous I/O object will be placed in a backlog and be destroyed either with an explicit ec_message_rsrc_flush or during swap-out (ec_message_swap_out). Behavior is undefined if source is NULL. Any set operation will indicate that the message resource has been updated so it can be explicitly swapped out during message swap out.
the message to associated the resource with
- name
the name of the resource to set or create
- state
the state of the associated I/O object
- io
the I/O object associated with the resource
Returns 0 on success. Returns -1 on failure and sets errno to indicate the reason.
**Configuration Change. ** This feature is available starting from Momentum 3.1. | https://support.sparkpost.com/momentum/3/3-api/apis-ec-message-rsrc-set | CC-MAIN-2022-05 | refinedweb | 218 | 54.63 |
Board index » python
All times are UTC
I decided to write this because I have a Expect/Tk program to ping my ISP so PPP stays open until the program exits. I've been thinking for more than a year about writing my own Expect module in Python and replacing the program with the Python version. (I've been more busy with the module than the rewrite though.) This is my first large scale attempt at a Python extension, but it seems to work. ;)
Documentation is at <.*-*-*.com/ ~arcege/python/ExpectPy/>. I'll be packaging this doc soon.
Unfortunately I'm limited by the platforms that I can test on: currently this has only been fully tested on Solaris 2.5 on Intel. It's been built on both AIX 4.2.1 and RedHat Linux, but with some problems. The AIX issues deal with the link editor options and testing on Linux was though a friend's machine with limited access. The shared library build has been tested the most. The static python interpreter still needs full testing.
Currently, there is only one known bug (I said known ;). The documentation above describes it in some detail. But it deals with a name conflict between my PCRE support inside Expect and other modules with Tcl (like Tkinter). I have a compile-time alternative for PCRE support (TclRE) when this conflict manifests.
I've had no end of problems with using Python's makesetup outside of the Python build area, so I chose to using GNU's autoconf. But I will continue to work on the makesetup solution.
What it works with: Python 1.4, Python 1.5, Python 1.5.1, Expect 5.22, Expect 5.26, Tcl 8.0 (for TclRE support)
Arcege
<P><A HREF=".*-*-*.com/ ~arcege/python/ExpectPy/">ExpectPy 1.6.1</A> - Python adaptation of Don Libes's "Expect" library for automation of interactive UNIX processes. (09-Aug-98)
-- -------- comp.lang.python.announce (moderated) --------
Python Language Home Page:.*-*-*.com/ -------------------------------------------------------
1. ExpectPy 1.7 - Expect extension for Python
2. ExpectPy 1.8.2 - Expect extension for Python
3. ExpectPy 1.8 - Expect extension for Python
4. ExpectPy 1.8 - Expect extension for Python
5. Beta release of ExpectPy 1.9
6. X-extension 1.4 and the DEC Alpha
7. NT extension for Tcl/Tk, Alpha 0.2
8. Mea 0.1/alpha : tcl namespace *extension*
9. RegularExpression plugin (alpha) for DR2 released
10. ANN: New Official Harbour Alpha Release!
11. MultiMedia Logic 0.4 Alpha Released
12. MultiMedia Logic ALPHA 0.3 is released | http://computer-programming-forum.com/37-python/c7309deccd8a7d13.htm | CC-MAIN-2017-43 | refinedweb | 428 | 71.1 |
Roy Leban
Microsoft Corporation
Created: January 1999
Revised: September 1999
Note The original version of this article included sections on working with data access pages on the Internet or an intranet. Those sections have been rewritten by Mark Roberts and moved into a separate article titled Deploying Data Access Pages on the Internet or Your Intranet.
Applies To: Microsoft Access 2000; Microsoft FrontPage 2000; Microsoft Internet Explorer 5; Microsoft Internet Information Server 4.0
Summary: This article shows you how to use Microsoft® FrontPage® to edit and enhance your data access pages, and how to use frames and server filters to create an easy-to-use and easy-to-navigate Web site. (12 printed pages)
Introduction
Getting Started
Using FrontPage with Data Access Pages
Next Steps
Data access pages in Microsoft® Access 2000 allow you to make your data available to anybody who has Microsoft Internet Explorer 5 and a Microsoft Office license. When you combine Access with FrontPage® 2000 and Microsoft Internet Information Server (IIS) version 4.0 or later, you'll have all the tools you need to create a dynamic Web site that serves data from Access or Microsoft SQL Server™ databases.
Note For security information about working with Web sites and Web servers, see FrontPage Security Best Practices.
This paper won't make you an expert on FrontPage, IIS, or managing a Web site. For complete information about FrontPage and IIS, consult the documentation that comes with those products. If you're new to the Web, you'll probably want to pick up a book about FrontPage and/or Web site creation. Additional resources for working with data access pages and Web sites are listed in the "Next Steps" section at the end of this paper.
As part of the Microsoft product family, Access works with all the other products you'll use to build a Web site.
FrontPage 2000, part of the Microsoft Office 2000 Premium package, allows you to create engaging Web sites that look and work exactly the way you want them to. FrontPage includes the ability to lay out pages with exacting care, design the pages with elements that color-coordinate, and use such cutting-edge features as dynamic HTML (DHTML) and cascading style sheets, which add style, movement, and interest to Web pages. The FrontPage Explorer, which is integrated into FrontPage 2000, makes it easy to manage the pages and the navigation structure of your Web site.
FrontPage also includes publishing features that make it easy to post your site to your Web server, as well as collaboration features. Because FrontPage 2000 preserves all foreign HTML, including formatting, you can use FrontPage 2000 to edit and enhance data access pages without any loss of functionality.
Microsoft Internet Information Server (IIS) is built into the Microsoft Windows NT® Server operating system. It was designed to deliver the highest level of security for corporate intranets and the Internet. Additionally, IIS provides.
Microsoft Site Server 3.0, a separate product optimized for use with IIS, adds publishing and searching capabilities and personalized delivery. Microsoft Site Server 3.0 Commerce Edition adds transaction capabilities for secure online commerce.
For low-use Web sites, or for sites on an intranet, you can use Microsoft Personal Web Server with Microsoft Windows® 95 or 98, or Microsoft Windows NT Workstation. Personal Web Server is simpler to install and administer than Internet Information Server, but because it was not designed to support high-volume Web sites, it does not include support for three-tier data access or use with Site Server. Personal Web Server also does not offer some of the security features found in IIS.
It's easy to edit your Web pages in both Access and FrontPage, but there are a few simple rules to follow.
When you open a data access page in FrontPage, FrontPage detects that the document is a data access page and automatically launches Access so you can edit the page. If you want to edit a data access page in FrontPage, click Open on the File menu, select the .htm file, click the arrow to the right of the Open button, and then click Open in Microsoft FrontPage.
Figure 1. File menu option to edit data access page in FrontPage
Tip If you add a data access page to a FrontPage-based Web site, you can open the data access page by double-clicking it in any FrontPage view.
At the bottom of the Page view window in FrontPage, you'll find the Normal and Preview tabs, which are analogous to the Design and Page views in Access. In addition, you'll find an HTML tab, which you can use to display the HTML code that makes up your data access page.
The Normal tab provides all of the FrontPage editing tools for your page, including frames, tables, styles, dynamic effects, transitions, and navigation bars. Many HTML features that can be accessed only from the property sheet in Access are available through the FrontPage formatting tools.
The Preview tab provides an easy way to try out your page without saving it and returning to Access or running Internet Explorer.
The HTML tab allows you to view and edit the HTML and XML code that makes up your data access page. You can use this tab to add or edit scripts for your page, though you'll probably find the Microsoft Script Editor better for that purpose. To open the Script Editor, press ALT+SHIFT+F11.
If you view your data access page by clicking the HTML tab, you'll notice that your page contains a lot of text that doesn't look like HTML tags, as shown below.
<PARAM name="XMLData" value="<?xml:namespace ns="urn:schemas-microsoft-com:office:access" prefix="a"?>
<xml>
<a:DataSourceControl>
<a:OWCVersion>9.0.0.2209</a:OWCVersion>
This text is the Extensible Markup Language (XML) representation of the data definition for the page. Be careful not to alter the XML code, or your data access page may not work when you return to Access or view it in Internet Explorer.
When you are moving between Access and FrontPage, make sure to close your data access page in Access before opening it in FrontPage, and vice versa. If you don't do so, you may not be able to save changes you make.
Note If you are using FrontPage or Internet Explorer to view a data access page that uses an Access database (.mdb file), the page will access your database directly. This means that you won't be able to make design changes in your database, including creating links to new data access pages. If you get an error message that says the database can't be put into exclusive mode, close any windows in which you are viewing the data access page, and try the operation again. This behavior occurs only with Access databases; it does not occur when you are using SQL Server databases.
If you're integrating database access into an existing Web site, you may find it easier to start in FrontPage and then edit the appropriate pages in Access. This will be especially true if you're using frames or have a complex Web site. When you use Access to open and modify a Web page that was created in FrontPage, the page will automatically be converted into a data access page, and the DataSourceControl object necessary for data binding will be added. To edit the Web page in Access, do the following:
The grid section is added at the end of your page. If you want your data to be within your FrontPage layout (for example, inside a table), you'll need to move the grid. The easiest way to do this is to use FrontPage as follows:
<DIV class=MicrosoftAccessBanner id=HeaderFoodsBanner ...>
Section: Foods</DIV>
<DIV class=MSOShowDesignGrid id=HeaderFoods ...>
(any objects you've added are here)
</DIV>
The first <DIV> is the section banner above the grid that is shown in Design view; the second <DIV> is the grid where you can position controls. The actual HTML code will be a lot more complicated than what is shown above because it will include all the size and positioning attributes.
.
Microsoft Office uses the content of your Web page, not just the .htm or .html suffix, to determine which application to edit the page in. Whenever you edit a Web page in either Access or FrontPage, that editor will become the default editor for that page.
Many Web sites make use of frames to maintain a standard interface while showing a variety of content. When combined with server filters in data access pages, frames enable you to create a dynamic Web site that allows easy navigation. The best way to create a frame-based site is to start in FrontPage and create your frame set and the basic set of pages. Next, open up each page you want to use with bound data and convert it into a data access page, as described earlier in "Editing FrontPage Pages in Access." Finally, add the appropriate links and code to the navigation page to activate the data-bound pages.
Figure 2. FrontPage "Header" frame layout template
For example, the "Header" frame layout template in FrontPage (Figure 2, above) has the following frame set associated with it:
<FRAMESET rows="64,*">
<FRAME name="header" scrolling="no" target="main">
<FRAME name="main">
</FRAMESET>
This frame set gives the top frame the name "header" and the bottom frame the name "main." You can target any hyperlink to any frame by supplying its name. This means the linked page will be shown in the designated frame rather than replacing the entire window. For example, when you create a Hyperlink object or a bound Hyperlink object in Access, you can set the Target property in the hyperlink's property sheet, as shown in Figure 3.
Figure 3. Setting Target properties for the Hyperlink object in Access
If you're creating regular hyperlinks in FrontPage, you can use the Target frame option in the Create Hyperlink dialog box to specify which frame the linked page should appear in. Using this option will result in HTML code similar to this:
<A href="products.html" target="main">Show Products</A>
Tip For flexibility, you should always use relative paths in hyperlinks rather than absolute links. Relative links work the same way on a Web server as they do on your local machine.
Server filters are particularly effective in frame sets. You can have links in one frame that show data access pages in a second frame. The server filter may be supplied as a search parameter that is included in the URL. For example, the server filters in the following three hyperlinks show lists of products that fall into one of three categories: they need to be reordered, they are out of stock, or they are on backorder:
<P><A href="products.html?stock<reorderlevel"
target="main">Low Stock Products</A></P>
<P><A href="products.html?stock=0"
target="main">Out of Stock Products</A></P>
<P><A href="products.html?backordered>0"
target="main">Backordered Products</A></P>
Using server filters can make your Web site appear larger and more dynamic without your having to create a lot of extra pages.
You can also generate server filters programmatically. For example, if you want to do a search based on a form value, as in Figure 4, you can't do the search with a static hyperlink.
Figure 4. Search based on a form value
For this kind of situation, you'll need to use a button (in this case, the Go button) that explicitly loads the page. The following HTML and Microsoft Visual Basic® Scripting Edition (VBScript) code does just that:
<FONT face="Arial Black" size="2">View Products:</FONT><BR>
<INPUT type="text" name="SearchText" size="20">
<INPUT border="0" src="go.gif" type="image" name=GoButton>
<SCRIPT for=GoButton event=onclick language=vbscript>
url = "products.html?serverFilter=""" & _
"products LIKE '%" & SearchText.value & "%'"""
parent.main.navigate url
</SCRIPT>
Passing search parameters in a URL works only when pages are hosted on a Web server. If your site is being deployed on a file server over a corporate intranet, or if you want the site to work locally, you can't supply server filters as part of the URL. Instead, you'll need to create the server filter programmatically and apply it as the page is loaded. Note also that when the server filter is supplied as part of the URL, it's visible to users. If you want to hide the details of your server filter, you'll need to create and apply it programmatically.
There's one catch: If the script that applies the server filter is in the page that is being replaced, the script won't be executed because the page will be closed before it can run. The solution is to add common filter-management routines to your navigation frame, because that frame will always be present. Any script that is set up to use a server filter when navigating to a page simply calls these filter-management routines.
The following is the code for the routines that manage the server filters in the navigation frame.
<SCRIPT language=vbscript>
' _________________________________________________________
' Variables and Initialization
Dim numTrackedPages
Dim pages(20)
Dim filters(20)
numTrackedPages = 0
' _________________________________________________________
' Navigation and Filtering
' The following routines keep track of a server filter
' for any pages that have been visited. This allows the user to
' return to the page and have the previous server filter
' stay in effect.
Sub SaveFilterForPage(url, serverfilter)
For i = 0 to numTrackedPages - 1
If (pages(i) = Right(url, len(pages(i)))) Then
filters(i) = serverfilter
Exit Sub
End If
pages(numTrackedPages) = url
filters(numTrackedPages) = serverfilter
numTrackedPages = numTrackedPages + 1
End Sub
Sub NavWithFilter(frame, url, serverfilter)
SaveFilterForPage url, serverfilter
frame.location.href = url
End Sub
Function SavedFilter(url)
For i = 0 to numTrackedPages - 1
If (pages(i) = Right(url, len(pages(i)))) Then
SavedFilter = filters(i)
Exit Function
End If
SavedFilter = ""
End Function
</SCRIPT>
The previous code keeps track of the server filters for up to 20 pages and handles the navigation, but doesn't set the server filter. To do that, you have to add the following script to the bottom of every Web page.
<SCRIPT language=vbscript>
' This script is used in conjunction with NavWithFilter
' to set the server filter for the current page
' after a navigation.
If (window.location.protocol <> "accdp:") Then
sf = parent.navFrame.SavedFilter(window.location.href)
If (sf <> "") Then
On Error Resume Next
n = MSODSC.RecordSetDefs.count-1
MSODSC.RecordSetDefs.item(n).ServerFilter = sf
End If
End If
</SCRIPT>
If you use the previous code in a lot of pages, you should put it in a separate file and use the src attribute of the SCRIPT element to point to the file instead of duplicating it, as shown in the following example:
<SCRIPT language=vbscript src=SetFilter.vb></SCRIPT>
Now, whenever you want to show a page with a server filter, you can do it with a single line of code, like this:
url = "products.htm"
sf = "ProductName LIKE '%green%'"
parent.navFrame.NavWithFilter self, url, sf
For more information about programming data access pages, see Programming Data Access Pages.
Both Access and FrontPage support Microsoft Office themes, but FrontPage themes have more features. FrontPage also allows you to customize the styles that make up a theme. You can use either Access or FrontPage themes on your data access page, but you shouldn't use both products to apply a theme to the same page.
From either Access or FrontPage, you can post Web pages by saving them directly to an http: path or by using Microsoft Office Web Folders. FrontPage also provides additional options for posting your entire Web site.
Once you have posted your Web site, you can directly edit and save pages on your site, as long as your server (1) supports http-put or http-post and (2) is either a FrontPage server or an Office Web server.
Tip To avoid disrupting visitors to your Web site while you're making changes, you should make changes to a "mirror" copy of the site, either on a local hard disk or on an alternative location on your Web server.
For more information about working with data access pages, see Deploying Data Access Pages on the Internet or Your Intranet, Programming Data Access Pages, Creating Secure Data Access Pages, and Connecting Data Access Pages Together.
For more information about working with Web sites, see the Microsoft Web site at.. To find them, click Search and paste (or type) the exact name of the paper.
You can find additional papers by searching for topics or products you're interested in (for example, "managing Web content" or "Site Server").
Finally, don't forget to consult your Web site and database administrators and the many books about creating Web sites available in your local bookstore. | http://msdn.microsoft.com/en-us/library/aa140027(office.10).aspx | crawl-002 | refinedweb | 2,834 | 58.42 |
Music as Discourse
Semiotic Adventures in Romantic Music
KO F I AG AW U
1
2009
1
Oxford University Press, Inc., publishes works that further
Oxford Universitys
I. Title.
P R E FAC E
Acknowledgments
I am grateful to Dniel Pter Bir for comments on a draft of this book, Christopher
Matthay for corrections and numerous helpful suggestions, Guillermo Brachetta
for preparing the music examples, and Suzanne Ryan for advice on content and
organization. It goes without saying that I alone am responsible for what is printed
here.
Some of this material has been seen in other contexts. The comparison between
music and language in chapter 1 is drawn from my article The Challenge of Semiotics, which is included in the collection Rethinking Music, edited by Nicholas Cook
and Mark Everist (Oxford University Press, 1999). The analysis of Beethovens op.
18, no. 3, in chapter 5 appears in expanded form in Communication in EighteenthCentury Music, edited by Danuta Mirka and myself (Cambridge University Press,
2008). The analysis of the slow movement of Mozarts Piano Sonata in A Minor, K.
310, originated in a paper presented to a plenary session at the Society for Music
Theorys 2006 annual meeting in Los Angeles. And some of the material in chapter 4, Bridges to Free Composition, began life as a keynote address delivered to
the International Conference on 19th-Century Music in Manchester, England, in
2005. Im grateful for this opportunity to recontextualize these writings and talks.
vi
Preface
antinarrative tendency in Stravinsky. For such exercises, you will find several leads
in this book. In place of models to be emulated directly or mechanically, I offer
suggestions and (deliberately) partial readings designed to stimulate your own
fantasies.
Reading a book on music analysis is not exactly like reading a novel. You will
need access to several scores and parallel recordings and a keyboard to try out
certain imagined patterns. For the shorter analyses in part I (chapters 3 and 5),
you will need, among others, scores of Schuberts Im Dorfe from Die Winterreise,
Schumanns Ich grolle nicht from Dichterliebe, the C-major Prelude from Book 1
of J. S. Bachs The Well-Tempered Clavier, the slow movement of Mozarts Piano
Sonata in A minor K. 310, Brahms song Die Mainacht, and the first movement
of Beethovens String Quartet in D major, op. 18, no. 3. For the longer analyses in
part II (chapters 6 through 9), you will need scores of Liszts Orpheus; Brahms
First Symphony (second movement); his Intermezzo in E Minor, op. 119, no. 2;
Mahlers Ninth Symphony (first movement); Beethovens String Quartet op. 130
(first movement); and Stravinskys Symphonies of Wind Instruments (1920, though
my analysis will use the 1947 version). Because the analyses constantly refer to
places in the score, it would be almost pointless to attempt to read these chapters
without the relevant scores at hand.
CONTENTS
Introduction
PART I
Theory
1.
2.
3.
4.
5.
Music as Language
Criteria for Analysis I
Criteria for Analysis II
Bridges to Free Composition
Paradigmatic Analysis
15
41
75
109
163
PART II
Analyses
6. Liszt, Orpheus (18531854)
7. Brahms, Intermezzo in E Minor, op. 119, no. 2 (1893),
and Symphony no. 1/ii (18721876)
8. Mahler, Symphony no. 9/i (19081909)
9. Beethoven, String Quartet, op. 130/i (18251826), and
Stravinsky, Symphonies of Wind Instruments (1920)
Epilogue
Bibliography
Index
211
229
253
281
317
321
331
Music as Discourse
Introduction
This book is an exercise in music analysis. I explore the nature of musical meaning from within the disciplinary perspective of music theory and propose a view
of music as discourse. I do not claim to offer a new theory of meaning; rather,
drawing on a handful of existing analytical theories and adding some insights of
my own, I seek to illuminate core aspects of a small group of well-known compositions chosen from the vast repertoires produced in nineteenth- and early twentieth-century Western Europe. Beethoven, Schubert, Mendelssohn, Schumann,
Liszt, Brahms, Mahler, Strauss, Bartk, and Stravinskyhousehold names for aficionados of European classical musicare among the composers whose works
I discuss; theoretically, I draw on Schenker, Ratner, Adorno, and the general field
of musical semiotics. My perspective is resolutely that of the listener, not a mere
listener but one for whom acts of composing and performing, be they real or imagined, necessarily inform engaged listening. Id like to think that my ultimate commitments are to the compositions themselves rather than to theories about them,
but the distinction is fragile and should not be made dogmatically or piously. The
book is aimed at those who are fascinated by the inner workings of music and
enjoy taking individual compositions apart and speculating on how (or, occasionally, whether) they cohere.1
Does music have meaning? This question has been debated ever since music
became a subject of discourse. Aestheticians, philosophers, historians, semioticians, and sociologists of music have had their say; in our own day, musicologists of a certain persuasion have been exercised by it. Some think that musical
meaning is intrinsic while others argue for extrinsic meanings. Some believe that
music is autonomous or relatively autonomous while others insist on permanent
1. In the terms of an ancient classification scheme, the discipline represented in this book is musica
theorica (theoretical speculation) as distinct from musica poetica (composition) or musica practica
(performance). These spheres are only notionally distinct, however; in analytical practice, they overlap and inform each other in significant and productive ways. See Manfred Bukofzer, Music in the
Baroque Era, from Monteverdi to Bach (New York: Norton, 1947), 370371.
Music as Discourse
social or historical traces on all musical products. Some are surprised to find that
the associations they prefer to make while listening to masterworksassociations
that seem self-evident to themare not necessarily shared by others: heroism or
aggressiveness in Beethoven, domination in Wagner, ambivalence in Tchaikovsky,
or femininity and worldliness in Schubert. No doubt, these debates will continue
into the future. And this is as it should be, for as long as music is made, as long as
it retains its essence as a performed art, its significance is unlikely to ever crystallize into a stable set of meanings that can be frozen, packaged, and preserved for
later generations. Indeed, it would be a profoundly sad occasion if our ideologies
became aligned in such a way that they produced identical narratives about musical works. One mark of the endurance of strong works of art is that they make
possible a diversity of responsesa diversity regulated by a few shared (social or
institutional) values.
Meanings are contingent. They emerge at the site of performance and are constituted critically by historically informed individuals in specific cultural situations.
Basic questions about musics ontology have never received definitive answers.
What music is, what and how it means, what meaning is, and why we are interested
in musical meaning in the first place: these questions are not meant to be answered
definitively nor with a commanding transhistorical attribution but posed periodically to keep us alert and honest. Then there are those considerations that arise
when history, culture, and convention inflect the search for meaningwhether
a work embodies a late style, conveys subjectivity, or reproduces the dynamics of
the society in which the composer lived. While interpretation can be framed dialogically to ensure that original meanings and subsequent accretions are neither
ignored nor left uninterrogated, the final authority for any interpretation rests on
present understanding. Todays listener rules.
The issues raised by musical meaning are complex and best approached
within carefully circumscribed contexts. For although no one doubts that music
making is or can be meaningful and satisfying, or that the resultant processes and
products have significance for those involved, be they composers, performers, or
listeners, the nonverbal essence of music has proved resistant to facile domestication within a verbal economy. My own curiosity about the subject stems in
part from an early interest in the confluence of composition, performance, and
analysis and from a sociological circumstance: but for a handful of exceptions,
card-carrying music theorists have been generally reticent about confronting
the subject of musical meaning.2 This does not mean that ideas of meaning do
not surface in their work from time to time, nor that, in producing voice-leading
graphs, metric reductions, paradigmatic charts, set-class taxonomies, and Tonnetz
2. Significant exceptions include Nicholas Cook, Analysing Musical Multimedia (Oxford: Oxford University Press, 2001); Cook, Review Essay: Putting the Meaning Back into Music; or, Semiotics Revisited, Music Theory Spectrum 18 (1996): 106123; Robert Hatten, Musical Meaning in Beethoven:
Markedness, Correlation, and Interpretation (Bloomington: Indiana University Press, 1994); Michael
L. Klein, Intertextuality in Western Art Music (Bloomington: Indiana University Press, 2005); and
the collection of essays in Approaches to Meaning in Music, ed. Byron Almen and Edward Pearsall
(Bloomington: Indiana University Press, 2006).
Introduction
5
Music as Discourse
its starting point rather than external factors.3 The operative phrase here is not
the polemical the music itself but starting point. To proclaim this other contingency is to promote an open-ended view of analysis; it is to encourage rigorous
speculation about musical meaning that takes certain core features as its point of
departure and that terminates on a path toward an enriched perspective.4
However elusive they may be, musics meanings are unlikely to be accessible to
those who refuse to engage with the musical code or those who deal with only the
most general and superficial aspects of that code. Defining a musical code comprehensively presents its own challenges, but there is by now a body of systematic and
historical data to facilitate such a task. The theories of Schenker, for exampleto
choose one body of texts that is indispensable for work on tonal musicmake
possible a range of explorations of everything from the imaginative expansion of
simple counterpoint in works by Bach, Beethoven, and Schubert through aesthetic
speculation about value and ideology in composers of different national provenance to the place of diminution in twentieth-century composers like Richard
Strauss, Mahler, and Stravinsky. Adhering to the code would ensure, for example,
that harmony is not ignored in the construction of a theory of meaning for Chopin
and Wagner, that melody is given due attention in Mendelssohn analysis, and that
the rhythmic narratives of Brahms or Stravinsky are duly acknowledged. And in
examining these aspects of the code, one is wise to seek the sharpest, most sensitive, and most sophisticated tools. Analysis may bear a complex relationship to
technology, but to ignore technological advancement in analytic representation is
to subscribe to a form of irrationality, even a form of mysticism, perhaps.
The defensive and at the same time aggressive tone in that last remark is forced
upon me by a strange circumstance. Despite the fact that music theory is one of the
oldest of humanistic disciplines, and despite the enviably precise vocabulary with
which the elements of music have been described and categorized, their essences
captured, recent attacks on formalism have sought to belittle this commanding
legacy with the claim that theorists do not deal with musics meaning and significance. This extraordinary claim is surprisingly deaf to the numerous meanings
enshrined in theorys technical processes and language. True, the meanings of a
motivic parallelism, or a middleground arpeggiation, or a modulation to a tritonerelated key are not always discussed in affective or expressive terms, but this does
not mean that the economy of relations from which they stem is pure, or based
solely on abstract, logical relations, or lacking semantic or affective residue. Since
the acquisition of such technical language still provides the basic elements of literacy for todays academic musician, there is work to be done in making explicit
what has remained implicit and in seeking to extend theorys domain without
undermining its commitment to the music itself. In short, it is not clear how a
theory of musical meaning that engages the musical language can be anything
other than a study of the musical code.
3. Ian Bent and Anthony Pople, Analysis, The New Grove Dictionary of Music and Musicians, 2nd ed.,
ed. Stanley Sadie (London: Macmillan, 2001).
4. For an elaboration of this view of analysis, see Agawu, How We Got Out of Analysis and How to Get
Back In Again, Music Analysis 23 (2004): 267286.
Introduction
7
Music as Discourse
sonata, but a more elusive quality in which the elements of a pieceevents and
periodsare heard working together and evincing a distinctive profile.
Theories of form abound. From the compositional or pedagogical theories of
Koch, Czerny, and Schoenberg through the aesthetic and analytical approaches
of Schenker, Tovey, Caplin, Rothstein, and Hepokoski and Darcy, scholars have
sought to distribute the reality of musical compositions into various categories,
explaining adherence as well as anomaly in reference to constructed norms, some
based on the symbolic value of an individual work (like the Eroica Symphony),7
others based on statistics of usage. Yet one cannot help feeling that every time
we consign a work to a category such as sonata form, we lie. For reasons that
will emerge in the course of this book, I will pay less attention to such standard
forms than to the events or groups of events that comprise them. Is there a difference between the two approaches? Yes, and a significant one at that. Placing
the emphasis on events promotes a processual and phenomenological view of the
work; it recognizes moment-by-moment succession but worries not at all about an
overall or resultant profile that can be named and held up as an archetype. Without denying the historical significance of archetypes or outer forms (such as ABA'
schemata) or their practical value for teachers of courses in music appreciation,
I will argue that, from a listeners point of view, such forms are often overdetermined, inscribed too rigidly; as such, they often block access to the rich experience
of musical meaning. The complex and often contradictory tendencies of musical
materials are undervalued when we consign them to boxes marked first theme,
second theme, and recapitulation. The ability to distribute the elements of a
Brahms symphony into sonata form categories is an ability of doubtful utility or
relevance, and it is a profound shame that musicology has devoted pages upon
pages to erecting these schemes as important mediators of musical meaning. At
best, they possess low-level value; at worst, they are distractions.8
Discourse thus embraces events ordered in a coherent fashion, which may operate in turn in a larger-than-the-sentence domain. There is a third sense of the term
that has emerged in recent years, inspired in part by poststructuralist thinking.
This is discourse as disciplinary talk, including the philosophical and linguistic
props that enable the very formulations we make about our objects of study. Discourse about music in this sense encompasses the things one says about a specific
composition, as Nattiezs Music and Discourse makes clear.9 In this third sense, discourse entails acts of metacriticism. The musical composition comments on itself
at the same time that it is being constituted in the discourse of the analyst. Both
the works internal commentary (represented as acts of inscription attributable
7. See Scott Burnham, Beethoven Hero (Princeton, NJ: Princeton University Press, 1995).
8. According to Janklvitch, sonata form is a something conceived, and not at all something heard,
not time subjectively experienced. Music and the Ineffable, trans. Carolyn Abbate (Princeton, NJ:
Princeton University Press, 2003), 17. Julian Horton notes that any study defining sonata practice in
relation to a norm must confront the problem that there is no single work which could necessarily
be described as normative. The idea exists only as an abstraction. Review of Bruckner Studies, ed.
Paul Hawkshaw and Timothy L. Jackson, Music Analysis 18 (1999): 161.
9. Jean-Jacques Nattiez, Music and Discourse: Toward a Semiology of Music, trans. Carolyn Abbate
(Princeton, NJ: Princeton University Press, 1990).
Introduction
9
to the composer) and the analysts external commentary feed into an analysis of
discourse. The internal commentary is built on observations about processes of
repetition and variation, while the external confronts the very props of insight formation. One sign of this metacritical awareness should be evident in the refusal to
take for granted any of the enabling constructs of our analyses. To analyze in this
sense is necessarily to reflect simultaneously upon the process of analysis.10
I use the phrase semiotic adventures in the subtitle in order to signal this
books conceptual debt to certain basic concepts borrowed from musical semiotics. Semiotics is a plural and irreducibly interdisciplinary field, and it provides, in
my view, the most felicitous framework (among contemporary competing analytical frameworks) for rendering music as structure and style. Writings by Nattiez,
Dougherty, Tarasti, Lidov, Hatten, Dunsby, Grabcz, Spitzer, Monelle, and others
exemplify what is possible without limiting the domain of the possible. I should
add quickly, however, that my aim is not to address an interdisciplinary readership but to speak within the narrower discourses of music analysis, discourses that
emanate from the normal, everyday activities of teachers and students of undergraduate courses in music theory and analysis.
What, then, are the central concerns of the books nine chapters? I have arranged
the material in two broad parts. The first, dubbed Theory, seeks to orient the
reader to perspectives that might facilitate an appreciation of the practical nature
of music as discourse. The second, Analyses, presents case studies encompassing
works by composers from Beethoven to Stravinsky. Specifically, chapter 1, Music
as Language, places music directly next to language in order to point to similarities and differences in sociology, ontology, psychology, structure, reception, and
metalanguage. The metaphor of music as language is oldvery oldand although
its meaning has changed from age to age, and despite the many limitations that
have been pointed out by numerous writers, it remains, in my view, a useful foil
for music analysis. Indeed, a greater awareness of musics linguistic nature may
improve some of the technical analyses that music theorists offer. The aim here,
then, is to revisit an old and familiar issue and offer a series of generalized claims
that might stimulate classroom discussion of the nature of musical language.
Chapters 2 and 3, Criteria for Analysis I and II, also retain a broad perspective in isolating certain key features of Romantic music, but instead of addressing the system of music as such, I turn to selected compositional features that
embrace elements of style as well as structure. Few would disagree with Charles
Rosen that it is disquieting when an analysis, no matter how cogent, minimizes
the most salient features of a work. This is a failure of critical decorum.11 These two
chapters (which belong together as a pair but are separated for practical reasons)
are precisely an attempt not to minimize such features. But salience is a contested
category. Salience is not given, not naturally occurring; it is constructed. Which is
10. For other invocations of music as discourse, see David Lidov, Is Language a Music? Writings on Musical Form and Signification (Bloomington: Indiana University Press, 2005), 1012, 7077, 138144;
and Michael Spitzer, Metaphor and Musical Thought (Chicago: University of Chicago Press, 2004),
107125. Discourse is, of course, a widely used term in the literature on musical semiotics.
11. Charles Rosen, The Classical Style: Haydn, Mozart, Beethoven (New York: Norton, 1972), 3.
10
Music as Discourse
why musical features that strike one listener as salient are judged to be peripheral
by another. I recall once listening to a recording of Schuberts Winterreise with an
admired teacher when he asked me what I thought was the most salient moment in
the beginning of Der greise Kopf (The hoary head) (example I.1). I pointed
to the high A-flat in the third bar, the high point of the opening phrase, noting
that it was loud and dissonant, marked a turning point in the melodic contour, and
was therefore rhetorically significant. He, on the other hand, heard something less
obvious: the change of harmony at the beginning of bar 11, the moment at which
the unyielding C pedal that had been in effect from the very first sound of the song
finally drops by a half-step. This surprised me initially, but I later came to admire the
qualitative difference between his construction of this particular salience and mine.
His took in the harmonic stream within the larger syntactical dimension; mine was
a statistical, surface event. The construction of salience in tonal music is especially
challenging because tonal expression relies as much on what is sounded as on what
is not sounded. The stated and the implied are equally functional. Inexperienced or
downright insensitive analysts who confine their interpretations to what is directly
observable in scores often draw their patterns of salience from what is stated rather
than what is implied; the result is a dull, impoverished, or untrue analysis.
Example I.1. Schubert, Der greise Kopf, from Winterreise, bars 116.
Etwas langsam.
Singstimme.
Der Reif hat ei - nen
Pianoforte.
12
Greis zu sein,
und
hab'
3
mich sehr ge - freu - et.
Introduction
11
12
Music as Discourse
notional purity and incorporating such things as motivic content, topical profile,
periodicity, and rhythm can strict counterpoint be brought into effective alliance
with free composition.
Chapters 2 and 3, on one hand, and 4, on the other, would therefore seem to
argue conflicting positions: whereas chapters 2 and 3 acknowledge the value of
constructing a first-level salience (based on stylistic features that are heard more
or less immediately), chapter 4 claims a more sophisticated relational approach by
peering into the subsurface. Chapter 5, Paradigmatic Analysis, adds to these competing views a semiological approach that attempts to wipe the slate clean in minimizing, but never completely eliminating, the amount of (musical) baggage that
the analyst brings to the task. The approach takes repetition, the most indigenous
of all musical attributes, as a guide to the selection of a compositions meaningful
units and speculates on the narrative path cut by the succession of repeating units.
The paradigmatic analyst in effect adopts a studiedly nave stance in dispensing
with the numerous a priori considerations that have come to burden a repertoire
like that of the Romantic period. Pretense succeeds only in a limited way, however,
but enough to draw attention to some of the factors we take for granted when we
analyze music and to impel a more direct encounter with musical form.
With these five chapters, the main theoretical exposition is over. Next follow a
number of case studies designed partly to exemplify the network of ideas exposed
in the theoretical chapters, partly to push beyond their frontiers, and partly to
engage in dialogue with other analytical approaches. First comes a study of the
narrative thread in Liszts symphonic poem Orpheus (chapter 6), followed by a
study of phrase discourse in two works by Brahms: the second movement of his
First Symphony and the Intermezzo for Piano, op. 119, no. 2 (chapter 7). The last
case studies are of narratives of continuity and discontinuity in the first movement of Mahlers Ninth (chapter 8) and in the first movement of Beethovens
String Quartet, op. 130, juxtaposed with Stravinskys Symphonies of Wind Instruments (chapter 9). The inclusion of Stravinskyand an austere work from 1920 at
thatmay seem strange at first, but I hope to show continuities with the Romantic
tradition without discounting the obvious discontinuities.
An analysts fondest hope is that something he or she says sends the reader/listener back to a particular composition or to a particular moment within it. Our
theoretical scaffoldings are useless abstractions if they do not achieve something
like this; they may be good theory but lousy analysis. Indeed, music was not made
to be talked about, according to Janklvitch.13 Talking, however, can help to reinforce the point that talking is unnecessary, while at the same time reinforcing the
belief that music was made to be (re)maderepeatedly, sometimes. Analysis, in
turn, leads us through inquiry back to the site of remaking. Therefore, I retain
some hope in the possibility that the analytical fantasies gathered here will inspire
some readers to reach for the works again; to see if their previous hearings have
been altered, enhanced, or challenged in any way; and, if they have, to seek to
incorporate some of these insights into subsequent hearings. If this happens, my
purpose will have been achieved.
13. Janklvitch, Music and the Ineffable, 79.
PA RT I
Theory
C HA P T E R
One
Music as Language
1. Roland Barthes, Mythologies, trans. Annette Lavers (New York: Hill and Wang, 1972), 115.
2. John Neubauer, The Emancipation of Music from Language: Departure from Mimesis in EighteenthCentury Aesthetics (New Haven, CT: Yale University Press, 1986), 2223.
3. Neubauer, The Emancipation of Music from Language, 40.
15
16
PART I
Theory
through the nineteenth century alongside a huge supplemental increase in worddominated (or at least word-inflected) genres like operas, tone poems, and lieder,
plus a variety of compositional experiments with language as sound, material, and
sense in the works of a number of twentieth-century composers (Stravinsky, Berio,
and Lansky)all of these provide further indication of the close rapport between
music and language.
The prevalence of language models for analysis of European music is the central concern of a 1980 article by Harold Powers, in which he cites the then recent
work of Fred Lerdahl and Ray Jackendoff as an exemplary attempt to model a
grammar of tonal music.4 Reviewing antecedents for such efforts, Powers mentions two medieval sources, the anonymous ninth-century Musica Enchiriadis
and the treatise of Johannes, circa 1100; he also mentions various discussions of
musical grammar in German theory (Dressler 1563; Burmeister 1606; Mattheson 1737, 1739; Koch 1787; Reicha 1818; Riemann 1903) and David Lidovs 1975
study of segmentation, On Musical Phrase.5 On a metalinguistic level, Powers
shows how musical analysis has borrowed from semantics (as in Deryck Cookes
The Language of Music, 1959), phonology (as in theories of South Indian classical
music), the making of propositional statements (as in Charles Boils semiological study of Tepehua thought songs), and, perhaps most significantly, grammar
and syntax (as in recent semiological applications by Ruwet, Nattiez, and Lidov).
In the quarter century since Powerss magisterial article appeared, research into
semiology, which typically indexes the linguisticity of music, has grown by leaps
and bounds, extending into areas of musical semantics, phonology, and pragmatics; embracing traditional studies that do not claim a semiotic orientation; and
expanding the repertorial base to include various non-Western musics. All of this
research tacitly affirms the pertinence of linguistic analogies for music.6
The decentering of previously canonical repertoires is one of the more dramatic outcomes of recent efforts to understand the relations between music and
language. The resulting geocultural depth is readily seen in ethnomusicological
work, which, because it is tasked with inventing other world cultures and traditions, disinherits some of the more obnoxious priorities enshrined in the discourse
about Western (musical) culture. Powerss own article, for example, unusual and
impressive in its movement across Western and non-Western repertoiresa
throwback to the comparative musicology of Marius Schneider, Robert Lach, and
Erich von Hornbostelincludes a discussion of improvisation and the mechanics of text underlay in South Asian music. A year earlier, Judith Becker and Alton
Becker had constructed a strict grammar for Javanese srepegan, a grammar that
was later revisited by David Hughes.7 The literature on African music, too, includes
several studies of the intriguing phenomenon of speech tone and its relationship
4.
5.
6.
7.
Harold Powers, Language Models and Music Analysis, Ethnomusicology 24 (1980): 160.
Powers, Language Models, 4854.
See Raymond Monelles Linguistics and Semiotics in Music for a valuable introduction to the field.
Judith Becker and Alton Becker, A Grammar of the Musical Genre Srepegan, Journal of Music
Theory 24 (1979): 143; and David W. Hughes, Deep Structure and Surface Structure in Javanese
Music: A Grammar of Gendhing Lampah, Ethnomusicology 32 (1988): 2374.
CHAPTER 1
Music as Language
17
to melody. There are studies of talking drums, including ways in which drums
and other speech surrogates reproduce the tonal and accentual elements of spoken language. And perhaps most basic and universal are studies of song, a genre
in which words and music coexist, sometimes vying for prominence, mutually
transforming each other, complementing each other, and often leaving a conceptually or phenomenally dissonant residue. The practices associated with lamentation, for example, explore techniques and territories of vocalization, from the
syllabic through the melismatic to the use of vocables as articulatory vehicles. And
by including various icons of crying (Greg Urbans phrase), laments (or dirges or
wails) open up other dimensions of expressive behavior beyondbut organically
linked tomusic and language.8
There is further evidence, albeit of an informal sort, of the music-language association. In aesthetic and evaluative discourses responding to performing and composing, one sometimes encounters phrases like It doesnt speak to me or S/he
is not saying anything.9 Metaphors of translation are also prominent. We imagine
music translated into visual symbols or images, or into words, language, or literary expression. In the nineteenth century, the common practice of paraphrasing
existing works suggested transformative rendition (saying something differently),
such as is evident in Liszts or Paganinis paraphrases of music by Beethoven and
Schubert. Ornamentation, likewise, involves the imaginative recasting of existing ideas, a process that resonates with certain oratorical functions. John Spitzer
studied Jean Rousseaus 1687 viol treatise and concluded, Rousseaus grammar of
ornamentation corresponds in many respects to the so-called morphophonemic
component of Chomskian grammars.10 Even the genre of theme and variations,
whose normative protocol prescribes a conscious commentary on an existing
theme, may be understood within the critical economy of explanation, criticism,
and metacommentary. Finally, improvisation or composing in the moment presupposes competence in the speaking of a musical language. Powers likens one
sense of improvisation to an extempore oratorical discourse while Lidov notes
that musical improvisation may be closest to spontaneous speech function.11
This highly abbreviated mappingthe fuller story may be read in, among other
places, articles by Powers (1980) and Feld and Fox (1994, which includes a magnificent bibliography), and books by Neubauer (1986) and Monelle (1992)should
be enough to indicate that the music-language alliance is unavoidable as a creative
challenge (composition), as a framework for reception (listening), and as a mechanism for understanding (analysis). Observe a certain asymmetry in the relationship,
8. Steven Feld and Aaron Fox, Music and Language, Annual Review of Anthropology 23 (1994): 2553.
9. See Ingrid Monson, Saying Something: Jazz Improvisation and Interaction (Chicago: University of
Chicago Press, 1996), 7396, for a discussion of Music, Language and Cultural Styles: Improvisation as Conversation.
10. John Spitzer, Grammar of Improvised Ornamentation: Jean Rousseaus Viol Treatise of 1687,
Journal of Music Theory 33(2) (1989): 305.
11. Powers, Language Models, 42; Lidov, On Musical Phrase (Montreal: Groupe de recherches en
smiologie musicale, Music Faculty, University of Montreal, 1975), 9, quoted in Powers, Language
Models, 42.
18
PART I
Theory
however. Measured in terms of the critical work that either term does, language
looms larger than music. Indeed, in the twentieth century, language, broadly
construed, came to assume a position of unprecedented privilege (according to
poststructuralist accounts) among the discourses of the human sciences. Salutary
reminders by Carolyn Abbate that the poststructuralist privileging of language
needs to be tempered when music is the object of analysis,12 and by anthropologist
Johannes Fabian that the aural mode needs to be elevated against the predominant
visual mode if we are not to forgo certain insights that come from contemplating
sound,13 have so far not succeeded in stemming the ascendancy of verbal domination. As Roland Barthes implies, to think and talk about music isnecessarily, it
would appearinevitably to fall back on the individuation of a language.14
Why should the music-as-language metaphor matter to music analysts? Quite
simply because, to put it somewhat paradoxically, language and music are as alike as
they are unlike. No two systemssemiotic or expressiveset against one another
are as thoroughly imbricated in each others practices and yet remain ultimately
separate and distinct. More important, the role of language as a metalanguage
for music remains essential and is in no way undermined by the development of
symbologies such as Schenkers graphic analysis or Hans Kellers notatedand
therefore performablefunctional analyses. The most imaginative music analysts
are not those who treat language as a transparent window onto a given musical
reality but those who, whether explicitly or implicitly, reflect on languages limitations even as they use it to convey insights about music. Languages persistence and
domination at the conceptual level is therefore never a mere given in music analysis, demanding that music surrender, so to speak; on the contrary, it encourages
acts of critical resistance which, whatever their outcome, speak to the condition of
music as an art of tone.
A few of these efforts at resistance are worth recalling. Adorno, looking beyond
material to aesthetic value, truth content, and psychological depth, has this to say:.15
12. Carolyn Abbate, Unsung Voices: Opera and Musical Narrative in the Nineteenth Century (Princeton,
NJ: Princeton University Press, 1991), 329.
13. Johannes Fabian, Out of Our Minds: Reason and Madness in the Exploration of Central Africa
(Berkeley: University of California Press, 2000).
14. Roland Barthes, Elements of Semiology, trans. Annette Lavers and Colin Smith (New York: Hill and
Wang, 1967), 10.
15. Theodor Adorno, Music and Language: A Fragment, in Quasi una Fantasia: Essays on Modern
Music, trans. Rodney Livingstone (London: Verso, 1992), 1.
CHAPTER 1
Music as Language
19
This string of negatives probably overstates an essential point; some will argue that
it errs in denying the possibilities set in motion by an impossible alliance. But the
work of music theory in which this statement appears is concerned with what is
specifiable, not with what occupies interstices. It comes as no surprise, then, that
the tenor of this statement notwithstanding, the authors later invoke a most valuable distinction between well-formedness and preference in order to register one
aspect of the music-language alliance. Criteria of well-formedness, which play an
essential role in linguistic grammar, are less crucial in musical grammar than preference rules. This is another way of stacking the musical deck in favor of the aesthetic. To put it simply: music is less about right and wrongalthough, as Adorno
says, these are importantthan about liking something more or less.
Jean Molino links music, language, and religion in arguing their resistance to
definition and in recognizing their symbolic residue:
16. Fred Lerdahl and Ray Jackendoff, A Generative Theory of Tonal Music (Cambridge, MA: MIT Press,
1983), 56.
20
PART I
Theory
The phenomenon of music, like that of language or that of religion, cannot be defined
or described correctly unless we take account of its threefold mode of existenceas
an arbitrarily isolated object, as something produced and as something perceived. It
is on these three dimensions that the specificity of the symbolic largely rests.17
These and numerous other claims form the basis of literally thousands of assertions about music as language. On one hand, they betray an interest in isomorphisms or formal parallelisms between the two systems; on the other, they point to
areas of inexactness, to the complexities and paradoxes that emerge at the site of
their cohabitation. They testify to the continuing vitality and utility of the music
and language metaphor, while reminding us that only in carefully circumscribed
contexts, rather than at a gross level, is it fruitful to continue to entertain the prospect of a deep linkage.
Accordingly, I plead the readers indulgence in setting forth a set of simple
propositions that might form the basis of debate or discussion in a music theory
class. Culled from diverse sources and originally formulated to guide a discussion
of the challenge of musical semiotics, they speak to aspects of the phenomenon
that have been touched upon by Powers, Adorno, Lerdahl and Jackendoff, and
Molino. I have attempted to mold them into capsule, generalizable form without,
I hope, oversimplifying the phenomena they depict.18 (By music in the specific
context of the discussion that follows, I refer to a literature, to compositions of the
common practice era which form the object of analytical attention in this book.
While a wider purview of the term is conceivable, and not just in the domain of
European music, it seems prudent to confine the reach of these claims in order to
avoid confusion.)
17. Jean Molino, Musical Fact and the Semiology of Music, trans. J. A. Underwood, Music Analysis
9(2) (1990): 114.
18. Agawu, The Challenge of Semiotics, in Rethinking Music, ed. Nicholas Cook and Mark Everist
(Oxford: Oxford University Press, 1999), 138160.
CHAPTER 1
Music as Language
21
presence in such societies of a species of rhythmic and tonal behavior that we may
characterize as music making is rarely in serious contention. Music, in short, is
necessary to us.19
There are, however, striking and sometimes irreconcilable differences in the
materials, media, modes of production and consumption, and significance of
music. Indeed, there appear to be greater differences among the worlds musics than
among its languages. Nicolas Ruwet says that all human languages are apparently
of the same order of complexity, but that is not the case for all musical systems.20
And Powers comments that the linguisticity of languages is the same from language to language, but the linguisticity of musics is not the same from music to
music.21 David Lidov see[s] no variation among languages so extreme as those
among musical styles.22 It appears that music is more radically constructed, more
artificial, and depends more crucially on context for validation and meaning. So
whereas the phrase natural language seems appropriate, natural music requires
some elaboration. While linguistic competence is more or less easily assessed,
assessing normal musical competence is a rather more elusive enterprise. Speaking a mother tongue does not appear to have a perfect correlative in musical practiceis it the ability to improvise competently within a given style, to harmonize
a hymn tune or folk melody in a native idiom, to add to the repertoire of natural
songs when given a text or a situation that brings on a text, to complete a composition whose second half is withheld, or to predict the nature and size of a gesture in
a particular moment in a particular composition? Is it, in other words, a creative
or compositional ability, a discriminatory or perceptual ability, or a performative
capability? So, beyond their mutual occurrence in human society as conventional
and symbolic media, the practices associated with language and music signal significant differences.23
2. Unlike language, which is both a medium of communication (ordinary
language) and a vehicle for artistic expression (poetic language), musical language exists primarily in the poetic realm, although it can be used for purely
communicative purposes. Please pass the marmalade uttered at the breakfast
table has a direct communicative purpose. It is a form of ordinary language that
19. Gayle A. Henrotte, Music as Language: A Semiotic Paradigm? in Semiotics 1984, ed. John Deely
(Lanham, MD: University Press of America, 1985), 163170.
20. Nicholas Ruwet, Thorie et mthodes dans les etudes musicales: Quelques remarques rtrospectives et prliminaires, Music en jeu 17 (1975): 19, quoted in Powers, Language Models, 38.
21. Powers, Language Models, 38. Perhaps the same is too strong and liable to be undermined by
new anthropological findings. See, for example, Daniel L. Everett, Cultural Constraints on Grammar and Cognition in Piraha: Another Look at the Design Features of Human Language, Current
Anthropology 46 (2005): 621646.
22. Lidov, Is Language a Music? 4.
23. The place of music and language in human evolution has been suggestively explored in a number
of publications by Ian Cross. See, for example, Music and Biocultural Evolution, in The Cultural
Study of Music: A Critical Introduction, ed. Martin Clayton, Trevor Herbert, and Richard Middleton (New York: Routledge, 2003), 1930. Also of interest is Paul Richardss adaptation of some of
Crosss ideas in The Emotions at War: Atrocity as Piacular Rite in Sierra Leone, in Public Emotions,
ed. Perri 6, Susannah Radstone, Corrine Squire and Amal Treacher (London: Palgrave Macmillan,
2006), 6284.
22
PART I
Theory
would normally elicit an action from ones companion at the table. Let me not
to the marriage of true minds admit impediments, by contrast, departs from the
ordinary realm and enters another in which language is self-consciously ordered
to draw attention to itself. This is poetic language. Whereas ordinary language is
unmarked, poetic language is marked. Like all such binary distinctions, however,
that between ordinary and poetic is not always firm. There are levels of ordinariness in language use; certain ostensibly linguistic formulations pass into the realm
of the poetic by opportunistic acts of framing (as in the poetry of William Carlos
Williams) while the poetic may inflect what one says in everyday parlance (the Ewe
greet each other daily by asking, Are you well with life?). So although the distinction is not categorical, it is nevertheless useful at low levels of characterization.
The situation is more ambiguous in music, for despite the sporadic evidence
that music may function as an ordinary medium of communicationas in the
talking drums of West and Central Africa, or in the thought-songs recorded by
Charles Boils among the Tepehua of Mexicomusics discursive communicative
capacity is inferior to that of language. In a magisterial survey of the music-language phenomenon, Steve Feld and Aaron Fox refer to the informational redundancy of musical structures, thus echoing observations made by aestheticians
like Leonard Meyer and others.24 And several writers, conscious of the apparently
asemantic nature of musical art, speak only with hesitation about musics communicative capability. It appears that the predominantly aesthetic function of music
compares only with certain heightened or designated uses of language.
Musics ordinary language is thus available only as a speculative projection.
One might think, for example, of an overt transition in, say, a Haydn sonata, which
in the moment suggests a shifting of gears, a lifting of the action onto a different
plane, an intrusion of craft, an exposure of seamsthat perhaps such transitions
index a level of ordinary usage in music. They command attention as mobile rather
than presentational moments. They are means to other, presumably more poetic,
ends. But one must not underestimate the extent to which a poetic impetus infuses
the transition function. The work of a transition may be the moment in which
music comes into its own, needing to express a credible and indigenously musical
function. Such a moment may be suffused with poetry. Attending to a functional
imperative does not take the composer out of his contemplative realm.
A similar attempt to hear ordinariness and poetry in certain operatic functions
conveys the complexity of the application. Secco recitative in conventional understanding facilitates the quick delivery of words, thus speeding up the dramatic
action, while aria slows things down and enables the beauty of musicwhich is
inseparable from the beauty of voiceto come to the fore. Recitative may thus
be said to perform the function of ordinary language while aria does the work
of poetic language. This alignment is already complicated. The ordinary would
seem to be musically dispensable but dramatically necessary, while the poetic is
not dispensable in either sense. This is another way of restating the musical basis
of the genre.
CHAPTER 1
Music as Language
23
Think, also, of functional music in opera. Think of the moment toward the end
of act 2 of Puccinis Tosca when Scarpia, in return for a carnal favor, consents to
give Tosca safe conduct so that she and Cavaradossi can leave the country. While
Scarpia sits at his desk writing the note, the musical narrative must continue.
Puccini provides functional, time-killing music, music which serves as a form of
ordinary language in contrast to the more elevated utterances sung by Tosca and
Scarpia both before and after this moment. Opera, after all, is music drama; the
foundation of operatic discourse is music, so the functional aspect of this moment
can never eclipse its contemplative dimension. The music that serves as time-killing music is highly charged, beautiful, and burdened with significance. It is as
poeticif not more so, given its isolationas any music in Tosca. So while Puccini
may be heard speaking (or singing, or communicating) in ordinary language,
his utterance is fully poetic. The fact that music is not a system of communication should not discourage us from exploring the messages that music sometimes
(intermittently) communicates. It is precisely in the tension between the aesthetic
and communicative functions that music analysis finds an essential challenge to its
purpose, its reason for being.25
3. Unlike language, music exists only in performance (actual, idealized, imagined, remembered). The claim that language as social expression is ever conceivable outside of the context of performance may appear counterintuitive at first.
When I greet you, or say a prayer in the mosque, or take an oath, am I not performing a text? And when I read a poem or novel to myself, am I not similarly engaged
in a performance, albeit a silent one? The system of language and the system of
music exist in a synchronous state, harboring potential relationships, relationships
waiting to be released in actual verbal or musical compositions. As soon as they
are concretized in specific compositions, they inevitably enshrine directions for
performance. However, partly because of languages communicative functionsas
contrasted with musics aesthetic functionpartly because it is possible to make
true or false propositional statements in language, and partly because of its domination of our conceptual apparatus, language appears to display a wider range of
articulatory possibility than does music, from performed or heightened to marked,
ordinary, or unmarked.
Music, by contrast, is more restricted in its social tendency, more marked when
it is rendered, and possibly silent when it is not being performed or remembered.
A musical work does not exist except in the time of its playing, writes Janklvitch.26 It is true that some musicians have music on the brain all the time, and it
is also true that some trained musicians can hear notated music in their heads
although this hearing is surely a hearing of something imagined, itself possible
only against a background of a prior (remembered) hearing if not of the particular
composition then of other compositions. It appears that the constraints placed on
25. I have elsewhere used this same example to undermine the distinction, sometimes drawn by
ethnomusicologists writing about African music, between functional music and contemplative
music. See Agawu, Representing African Music: Postcolonial Notes, Queries, Positions (New York:
Routledge, 2003), 98107.
26. Janklvitch, Music and the Ineffable, 70.
24
PART I
Theory
music making are always severe, presumably because the ontological modes of
verbal behavior are more diffuse. The difference in performability between music
and language is finally relative, however, not absolute.
4. Like language (in its manifestation as speech), music is organized into
temporally bounded or acoustically closed texts. Whether they be oral texts (like
greetings, oaths, prayers) or written texts (poems, novels, speeches, letters), verbal
texts share with musical texts a comparable internal mode of existence. Certain
otherwise pertinent questions about the identity of a musical work are, at this level,
rendered irrelevant by the undeniable fact that a text, work, or composition has,
in principle, a beginning, a middle, and an ending. At this level of material and
sonic specificity, the beginning-middle-ending scheme represents only the order
in which events unfold, not the more qualitative measure of the function of those
parts. The work of interpretation demands, however, that once we move beyond this
material level, compositions be reconfigured as open texts, conceptually boundless
fields, texts whose necessary but in a sense mundane temporal boundaries are not
necessarily coterminous with their sense boundaries.27
5. A musical composition, like a verbal composition, is organized into discrete
units or segments. Music is, in this sense, segmentable. Understanding a temporal
phenomenon is only possible if the whole, however imagined or conceptualized,
is grasped in terms of its constituent parts, units, or segments. Many writings in
music theory, especially the great seventeenth- and eighteenth-century treatises on
rhetoric and music (Burmeister, Bernhard, Mattheson) are either premised upon
or develop an explicit view of segments. And many later theories, be they prescriptive and compositional (Koch and Czerny) or descriptive and synthetic (Tovey and
Schenker), lay great store by building blocks, minimal units, basic elements, motives,
phrases, periodsin short, constitutive segments. In thus accounting for or prescribing the discourse of a composition, theorists rely on a conception of segmentation as an index of musical sense or meaning. Now, the issue of musics physical
segmentability is less interesting than what might be called its cultural or psychological segmentability. The former is a quantitative or objective measure, the latter a
heavily mediated qualitative or subjective one. Culturally conditioned segmentation
draws on historical and cultural data in a variety of formal and informal discourses
to determine a works significant sense units and their mode of succession. The
nature of the units often betrays allegiance to some metalanguage or other, as when
we speak of musical logic, developing variation, mixture, or octatonic collection.
6. Although segmentable, the musical composition is more continuous in its
real-time unfolding than is a verbal composition. The articulatory vehicles of verbal and musical composition differ, the former marked by virtual or physical rests
and silences, the latter by real or imagined continuities. The issue of continuity is
only partly acoustical. More important are the psychological and semantic sources
of continuity. Lacking an apparent semantic dimension that can activate certain
27. On open texts, see Umberto Eco, The Poetics of the Open Work, in Eco, The Role of the Reader:
Explorations in the Semiotics of Texts (Bloomington: Indiana University Press, 1979), 4766. For an
incisive discussion, see Nattiez, Music and Discourse, 69101.
CHAPTER 1
Music as Language
25
26
PART I
Theory
30. Cooke, The Language of Music (Oxford: Oxford University Press, 1959).
31. Cooke, The Language of Music, 115, 140.
32. Hans von Blow, Preface to C. P. E. Bach, Sechs Klavier Sonaten (Leipzig: Peters, 1862), 3.
CHAPTER 1
Music as Language
27
28
PART I
Theory
In painting words, the composer findsoften inventsan iconic sign for a nonmusical reality. Relying upon these musical-verbal dictionaries,37 composers and
listeners constrain musical elements in specified ways in order to hear them as one
thing or another. While such prescription does not eliminate alternative meanings
for the listener, it has a way of reducing the potential multiplicity of meanings and
directing the willing listener to the relevant image, narrative, or idea. Extrinsic
meaning therefore depends on layers of conventional signification.
Intrinsic meaning, too, depends on an awareness of convention, but because
we often take for granted our awareness of conventions, we tend to think of intrinsic meanings as internally directed and of immediate significance. A dominantseventh chord indexing an immediate or postponed tonic, a rising melodic gap
filled by a complementary stepwise descent, an opening ritornello promising a
contrasting solo, or an inaugural chromatic pitch bearing the full potential of later
enharmonic reinterpretationthese are examples of intrinsic meaning, meaning
that is apparently grasped without recourse to external, nonmusical, knowledge.
The extrinsic-intrinsic dichotomy is ultimately false, however, for not only
do intrinsic meanings rely on certain conventional constructs, but their status as
intrinsic is continually transformed in the very moment that we apprehend their
signifying work. It requires external knowledgeor, at least, conventional knowledgeto expect a dominant-seventh to move to the tonic; it could just as readily
move to the submediant; also, depending on its position and the local voice-leading situation, its behavior may be modified accordingly. Although some theories
claim nature as the origin of some of their central constructssuch as the major
triad or the notion of consonancenot until there has been cultural intervention
is the natural made meaningful. The extrinsic-intrinsic dichotomy, then, enshrines
an opposition that is only apparent, not real. Indeed, oppositions like this are common throughout the literature, including subjective-objective, semantic-syntactic,
extramusical-(intra)musical, extroversive-introversive, extrageneric-congeneric, exosemantic-endosemantic, expression-structure, and hermeneutics-analysis. As points
of departure for the exploration of musical meaning, as tools for developing provisional taxonomies, such dichotomies may be helpful in distributing the basic features
of a given composition. But beyond this initial stage of the analysis, they must be
used cautiously, for the crucial issue is not whether a given composition has meaning
extrinsically or intrinsically but in what sense one or the other term applies.
10. Whereas language interprets itself, music cannot interpret itself. Language
is the interpreting system of music.38 If musical units have no fixed meanings, if
the semantic element in music is merely intermittent,39 if it is not possible to
make a propositional statement in music, and if music is ultimately untranslatable,
then music cannot interpret itself. There are, to be sure, intertextual resonances
in music that might be described in terms of interpretive actions. For example, a
variation set displays different, sometimes progressively elaborate and affectively
37. Powers, Language Models, 2.
38. Benveniste, The Semiology of Language, 235.
39. Carl Dahlhaus, Fragments of a Musical Hermeneutics, trans. Karen Painter, Current Musicology
50 (1991): 520.
CHAPTER 1
Music as Language
29
30
PART I
Theory
order to simplify aspects of the analysis. The choice of instrumental (or untexted)
music should require no further justification at this point, except to say that if
musical analysis is obliged to deal with musical problems, then dispensingif only
temporarilywith the influence of words, drama, or dance may be advantageous.
The purpose of the analysis is to pinpoint a few salient features of each composition and to suggest some of the meanings to which they give rise. It will be obvious,
I trust, that although no attempt is made to apply the principles enshrined in the
ten propositions discussed earlier, the following observations about structure are
largely consistent with the ontology of music implicit in the propositions.43
CHAPTER 1
Music as Language
31
Example 1.1. Schubert, Piano Sonata in C Minor, D. 958, Adagio, bars 118.
Adagio.
sempre ligato
pp
14
pp
11
pp
32
PART I
Theory
musicians, meaning in this Schubert work is intimately tied to the tonal tendencies
in each phrase, and the sense of each phrase is, in turn, conveyed by the degree of
closure it exhibits. The first of these punctuation marks occurs in bars 34, where
the half-cadence pronounces the first 4 bars unfinished, incomplete, opena
promissory note. The status of the dominant chord in bar 4 is elevated in bars 78
through tonicization. By acquiring its own dominant in bars 67, the dominant
on the downbeat of bar 8 displays an egotistical tendency, as Schenker would say,
demanding recognition for itself rather than as a mere accessory to the reigning
tonic. But this moment in the sun is short-lived as D-natural is replaced by D-flat
in bar 8 to transform the E-flat major chord into a dominant-seventh of A-flat. The
join between bars 8 and 9 is smoothed over, and in no time we are back where we
started: bar 9 is the same as bar 1. Notice how the bass progression by fifths in
58 (CFBE) offers us a heightened view of the tonicized dominant in bar 8.
Thus, what was said at the conclusion of bars 14 is intensified in the course of
bars 58.
At 9, the motion begins again. By this act of beginning again, Schubert lets us
understand that the destination of the next 8 bars will be different, that whereas
the two previous 4-bar phrases (14 and 58) remained open, closure is now a
definite possibility. But for the registrally elevated lower voices, all is as before
from the downbeat of bar 9 through the third eighth-note of bar 11, after which
point Schubert slips into the subdominant (bar 12, downbeat), extending the
chord through its own minor subdominant. This is not a destination we would
have inferred from the beginning of the piece, and the manner of its attainment
tells us that the D-flat major chord is on its way somewhere, that it is not a goal
but a station. Schubert confirms the transitory nature of bar 12 by composing past
it into the cadence at bars 1314. In retrospect, we might hear the pause on the
subdominant in 12 as a pause on the predominant sonority within a larger cadential group, IVV7I across bars 1214. That the motion would end eventually in
a satisfying close we took for granted from the beginning; but with what imagination and play this would be accomplished, we could not have predicted. With the
cadence in 1314, the composition reaches an end, a definitive end, perhaps. Alas,
Schubert is not done yet. He opens up a new, upper register, repeats the progression of bars 1112, leading to the predominant at 1516, abandons that register,
and returns to the lower register in order to close, using the cadence figure from
1314 in 1718 to mark the end of the composition as a whole.44
With this first pass through the composition under the guide of its cadences,
we have begun to broach the nature of Schuberts tonal imagination and the nature
of musical meaning. There is more to the tonal life than the sense conveyed by
cadences, however. The golden rule for exploring tonal meaning is to be mindful
of the origin and destination of every event, to understand that no moment stands
in isolation. Tonal composing is premised on an always-connected ideology that
governs the community of tones. This is not to deny that some connections can be
interpreted in terms of contextual discontinuities; it is only to claim a premise of
44. The play with register hinted at here is brought to a spectacular finish at the end of the movement.
CHAPTER 1
Music as Language
33
connectedness. A chosen event comes from somewhere and leads elsewhere. Within
this broader goal-directedness, an engaging network of motions unfolds at more
local levels. Structural entities are elaborated, decorated, or extended in time. Some
events emerge as hierarchically superior within individual prolongational contexts.
Subsequent chapters in this book will explore the nature of tonal meaning, but
we can make a second start on the terrain of Schuberts sonata by observing the
process by which structural entities are elaborated. Example 1.2 rewrites Schuberts
18-bar composition as a series of 11 building blocks or units.45 Each expresses a
tonal-contrapuntal motion; therefore, each is akin to an item of vocabulary. My
presentation of each fragment begins with its putative structural underpinning
and then hypothesizes a series of transformations that set Schuberts surface into
relief. In this way, tonal meaning is understood in reference to tonal composition,
not external association. The best way to appreciate example 1.2 is to play through
it at the piano and observe what Schubert does with simple processes like extension of a chord (units 1, 6), voice exchange (units 2, 7), half-cadence (unit 3), full
cadence (units 5, 9, and 11), progression from tonic to subdominant (on its way to
a cadential dominant; units 8, 10), and circle-of-fifths progression (unit 4).
With these speculative derivations, we can claim to have accounted in one way
or another for all of the local harmonic and voice-leading motions in the composition. Here is a summary:46
Bars 121 = extension of tonic, II6
Bars 2131 = extension of tonic by voice exchange
Bars 314 = progression from IV
Bars 58 = cadence in V
Bars 891 = V7I progression
Bars 9101 = bars 121
Bars 101111 = bars 2131
Bars 11112 = progression from IIV, on its way to V (double meaning)
Bars 1314 = cadence in I
Bars 1516 = bars 1112
Bars 1718 = bars 1314
Understanding these ways of proceeding forms the basis of tonal understanding.
The analyst imagines Schuberts decision-making process from the point of view of
the finished work. There is no recourse to biography or other external information
45. Here and in subsequent examples, the units of a composition are numbered using a simple ordinal
scheme: 1, 2, 3, etc. The main advantage of this practice is the neutrality it confers on the succession
of units. This is part of a larger strategy to escape the overdetermination of a more conventional
apparatus. For an important (but by no means isolated) precedent, see Derrick Puffett, Bruckners
Way: The Adagio of the Ninth Symphony, Music Analysis 18 (1999): 5100. Puffetts units are designated as periods, and there are 33 of them in this movement. He also cites an earlier instance of
period analysis in Hugo Leichtentritts Musical Form (Cambridge, MA: Harvard University Press,
1951; orig. 1911).
46. Superscripts are used to locate a specific beat within the bar. Thus, 21 denotes beat 1 of bar 2, 22 is
beat 2 of bar 2, and so on.
34
PART I
Theory
1, 6
becomes
becomes
2, 7
becomes
becomes
becomes
becomes
becomes
becomes
becomes
becomes
8, 10
9, 11
becomes
becomes
11
becomes
13
at this level of the analysis, only an understanding of the possibilities of manipulating the language.
When we first noted the different registral placement of the nearly identical
material in bars 1112 and 1516, we retreated from assigning structural function
to registral differentiation. Register as a dependent dimension is not thought to have
a syntax. But without contesting this theoretical fact, we can see from the ways in
CHAPTER 1
Music as Language
35
which Schubert manipulates register during the return of the opening (example 1.3)
that speaking in terms of a registral discourse may not be hyperbolic. It is the destination of the tonal narrative in association with register that is of interest here.
Example 1.3. Schubert, Piano Sonata in C Minor, D. 958, Adagio, bars 102115.
ppp
pp
104
un poco cresc.
107
109
36
PART I
Theory
progression ii6v6/45/3. When juxtaposed, the two cadences carry the respective senses of question and answer, open utterance followed by closed one. Indeed,
from the beginning of the composition, we have been offered a dualistic gesture as
rhetorical figure and premise. The unison hunt-style figure that suggested trumpets or horns (bars 12) is answered by the more delicate figures of bars 34, perhaps a hint at the Empfindsamer style. Similarly, the sequential repetition of bars
12 as 56 poses another question that is answered immediately by the equivalent of bars 34, namely, bars 78. In terms of textural design, then, the period is
symmetrical: 4 + 4 subdivided into (2 + 2) + (2 + 2). Phrase division of this sort is
part of the unmarked or ordinary syntax of the classical style. From this point of
view, the period is regular and unproblematic.
Example 1.4. Mozart, Piano Sonata in D Major, K. 576, first movement, bars 18.
Allegro.
Beneath this trim, balanced, indeed classical exterior, however, there lurk a
number of meaningful tensions that grow out of the closing tendencies of Mozarts
materials. Three such tensions may be identified. The first resides in the play of
register. In the initial 2 + 2 pairing, the second pair answers the first in a higher
but contiguous register. The effect of registral change is readily felt if we rewrite the
4-bar phrase within a single register (example 1.5). Although it preserves the question-and-answer pattern together with topical and textural contrasts, this hypothetical version mutes the sense of a new plane of activity in bars 34. The second
4-bar phrase rehearses the registral patterning in the first, so we hear the contrast
of register as an emerging contextual norm. The norm, in other words, enshrines
a residual registral dissonance: the question posed at home, the answer delivered
away from home. When aligned with the syntactically normative, repeated IV
harmonic progression, an interdimensional dissonance results.
Example 1.5. Registral modification of bars 34 in Mozart, Piano Sonata in D
Major, K. 576, first movement.
CHAPTER 1
Music as Language
37
But this is only the most superficial of animating tensions, indeed one that
might be dismissed entirely by those who regard register as a secondary rather
than primary parameter. (According to Leonard Meyer, primary parameters in the
common practice era are harmony, melody, and rhythm, while dynamics, register,
and timbre are secondary.)47 Register apparently resists a syntactical reading. Consider, though, a second source of tension, namely, the events in bar 7. Had Mozart
continued the phrase mechanically, he would have written something like what is
shown in example 1.6, thereby preserving the rhythmic profile of bars 34. But he
eschews a mechanical answer in favor of a little display of invention via his variation technique.48 The charming figure in bar 7 seems literally to escape from the
phrase and to run toward a little infinity; it suggests an improvisation, an utterance
with an otherworldly aura. This heightened sense is set into relief by the decidedly
ordinary cadential chords in bars 78, which remind us of where we are in the
formal process. The cadence is unmarked, dutifully executed in fulfillment of a
syntactic obligation; it is part of Mozarts ordinary language.
but
38
PART I
Theory
Cross-referencing seems as significant as driving to a cadence. To speak implicitly of discontinuity between, say, bars 12 and 34 may seem exaggerated, but it
would be an interpretive deficit to discount resistance to continuity by acknowledging only our privileged lines and voice-leading paths.
There is yet another source of tension, one that takes us into the realm of tonal
tendency. Bar 5, too, is marked rather than unmarked. This is not the consequent
we would normally expect to the 4-bar antecedent. Since bars 14 began on I and
finished on V, bars 58 might begin on V and return to I, or begin on I and return to
it via V. To begin on ii, as Mozart does here, is to create a sense of a differentperhaps more extendedtemporal and tonal trajectory. It is as if we were beginning
a sequential motion in 4-bar units, one that would presumably result in a 12-bar
period. Thus, the initiating AD motion (bar 1, including upbeat) is followed by
BE (bar 5, including upbeat), and would presumably continue as CF; eventually, of course, the pattern will have to be broken. The promise of a sequence is not
fulfilled, however. Mozart turns the phrase inward and releases an ordinary functional cadence in bars 78. The effect of bars 56, then, is to reorient the overall
harmonic trajectory. The clear IV progression that shapes bars 14 is answered
by an expanded iiVI cadence in bars 58, with the ii occupying three-quarters
of the complementary phrase. It is as if the motion were begun and suspended at V
(bars 14) and then resumed and brought to completion in the complementary ii
VI progression (bars 58). To subsume this quite palpable drama under a simple
IVI global progression, as Felix Salzers Schenkerian reading does,49 would be
canonically correct, of course, but it would fail to convey the sharply etched shapes
that give Mozarts composition its distinct rhetorical character and meaning.
More could be said about these two compositions by Schubert and Mozart,
but what has been said should suffice in this introductory context. I hope that the
chapter has, first, provided a general orientation to the differences between music
and language, and second, through these preliminary analytical ventures, indicated
some of the issues raised in an analysis of musical meaning. Some readers may
sense a gapa phenomenological gap, perhapsbetween the more general discussion of music as language and the specific analytical discussion that followed.
This is partly a question of metalanguage. The language of music analysis often
incorporates nomenclature different from ordinary language, and this, in turn,
is motivated in part by the need to refer to specific portions of the musical text,
the object of attention. The score, however, is not a simple and stable object but a
nexus of possibilities. Analytical language carries a host of assumptions about the
analysts conception of musical languagehow notes connect, how tonal meanings are implied, how a sense of ending is executed, and so on. The point to be
emphasized here is that the search for meaning and truth content in any composition is not productive without some engagement with the musical material and its
technical structure. It should be clear, too, that probing the technical structure of
a composition is a potentially never-ending process. The answers obtained from
49. Felix Salzer, Structural Hearing: Tonal Coherence in Music, vol. 2 (New York: Dover, 1952), 95.
CHAPTER 1
Music as Language
39
such an exercise are provisional, never final. Ideally, such answers should engender
other, more complex questions, the process continuing ad infinitum. Final-state
declarations about the meaning of this or that composition should be approached
with the greatest care so as not to flatten, cheapen, or undercomplicate what the
work of art makes possible. Readers may wish to keep this ideal in mind while
reading the analyses in subsequent chapters, where the imperatives of theorybuilding sometimes enjoin us to curtail exploration in order to frame the (necessarily provisional) outcomes for critical assessment.
C HA P T E R
Two
Criteria for Analysis I
If music is like language but not identical to it, how might we formulate a description of its material content and modes of organization that captures its essence as
an art of tone within circumscribed historical and stylistic contexts? The purpose
of this chapter and the next is to provide a framework for answering this question.
To this end, I have devised six rubrics for distributing the reality of Romantic music:
topics or topoi; beginnings, middles, and endings; high points; periodicity (including discontinuity and parentheses); three modes of enunciation, namely, speech
mode, song mode, and dance mode; and narrative. The first three are discussed in
this chapter, the other three in chapter 3. Together, they facilitate an exploration of
the immediately perceptible dimensions of Romantic compositions. Not every criterion is pertinent to every analytical situation, nor are the six categories nonoverlapping. But for each compositional situation, one, two, or some combination of the
six can help to convey salient aspects of expression and structure. It is best, then, to
think of the criteria variously as enabling mechanisms, as schemes for organizing
intuited insights, and as points of departure for further exploration. Romantic repertoires are of course vast and diverse, but to claim that there is no consistent principle of structure that governs Romantic music may be to undervalue a number of
recurring strategies.1 We need to find ways to manage and characterize heterogeneity, not to contain, mute, or erase it. We need, in short, to establish some conditions
of possibility by which individual students can pursue in greater analytical detail
the effervescent, evanescent, and ultimately plural signification of Romantic music.
Topics
Setting out the compositional and stylistic premises of music in the classic era,
Leonard Ratner draws attention to its mimetic qualities:
1. Leonard G. Ratner, Music: The Listeners Art, 2nd ed. (New York: McGraw-Hill, 1966), 314.
41
42
PART I
Theory
From its contacts with worship, poetry, drama, entertainment, dance, ceremony,
the military, the hunt, and the life of the lower classes, music in the early 18th century developed a thesaurus of characteristic figures, which formed a rich legacy for
classic composers. Some of these figures were associated with various feelings and
affections; others had a picturesque flavor. They are designated here as topicssubjects for musical discourse.2
Ratners topics include dances like minuet, contredanse, and gavotte, as well as
styles like hunt, singing, fantasia, and Sturm und Drang. Although the universe
of eighteenth-century topics is yet to be formulated definitively as a fixed, closed
category with an attendant set of explicit discovery procedures, many of Ratners
core topics and his ways of reading individual compositions have served in recent
years to enliven interpretations of music by Mozart, Haydn, Beethoven, and their
contemporaries. The concept of topic provides us with a (speculative) tool for the
imaginative description of texture, affective stance, and social sediment in classic
music.3
A comparable exercise of establishing the compositional and stylistic premises
of Romantic music, although challenging in view of the greater heterogeneity of
compositional ideals in the latter repertoire, would nonetheless confirm the historical persistence of topoi. Chorales, marches, horn calls, and various figures of
sighing, weeping, or lamenting saturate music of this era. There is, then, a level of
continuity between eighteenth- and nineteenth-century styles that would undermine historical narratives posited on the existence of a categorical distinction
between them. It would be equally problematic, however, to assert a straightforward historical continuity in the way topics are used. On one hand, the largely
public-oriented and conventional topics of the eighteenth century often exhibit a
similar orientation in the nineteenth century. For example, the communal ethos
or sense of unanimity inscribed in a topic like march remains largely invariant.
The slow movement of Beethovens Eroica Symphony; Mendelssohns Song without Words in E minor, op. 62, no. 3; the little march with which the protagonist of
Schumanns Help me sisters, from Frauenliebe und Leben, no. 6, projects the joy
of a coming wedding; Liszts Rkozcy March; the Pilgrims march from Berliozs
Harold in Italy; and the determined opening movement of Mahlers Sixth Symphonyall are united by a mode of utterance that is irreducibly social and communal, a mode opposed to aloneness. On the other hand, the ascendancy in the
nineteenth century of figures born of a private realm, figures that bear the marks
2. Leonard G. Ratner, Classic Music: Expression, Form, and Style (New York: Schirmer, 1980), 9.
3. On topics in classic music, see Ratner, Classic Music; Wye Jamison Allanbrook, Rhythmic Gesture in
Mozart: Le nozze di Figaro and Don Giovanni (Chicago: University of Chicago Press, 1983); Agawu,
Playing with Signs: A Semiotic Interpretation of Classic Music (Princeton, NJ: Princeton University Press,
1991); Elaine Sisman, Mozart: The Jupiter Symphony (Cambridge: Cambridge University Press, 1993);
Hatten, Musical Meaning in Beethoven; Monelle, The Sense of Music; Raymond Monelle, The Musical
Topic: Hunt, Military and Pastoral (Bloomington: Indiana University Press, 2006); and William E.
Caplin, On the Relation of Musical Topoi to Formal Function, Eighteenth-Century Music 2 (2005):
113124.
CHAPTER 2
43
of individual composerly idiolects, speaks to a new context for topic. If topics are
commonplaces incorporated into musical discourses and recognizable by members of an interpretive community rather than secret codes to be manipulated
privately, then the transition into the Romantic period may be understood not as
a replacement but as the incorporation of classic protocol into a still more variegated set of Romantic discourses.
In order to analyze a work from the point of view of its topical content, one
needs access to a prior universe made up of commonplaces of style known to
composers and their audiences. Topics are recognized on the basis of prior
acquaintance. But recognition is an art, and there is simply no mechanical way of
discovering topics in a given work. Topics are therefore also constructions, not
naturally occurring objects. Without deep familiarity with contemporaneous as
well as historically sanctioned styles, it is simply not possible to know what the
categories are nor to be able to deploy them imaginatively in analysis.
Few students of classical music today grew up dancing minuets, bourres,
and gavottes, marching to janissary music, or hearing fanfares played on hunting
horns. Only a few are skilled at paraphrasing existing compositions, improvising
keyboard preludes, or setting poetry to music in a consistent personal idiom, not
in preparation for professional life as a composer but to enhance a general musical
education. In other words, thorough grounding in the sonic residue of late eighteenth- and nineteenth-century styles, which constitutes a prerequisite for effective topical analysis, is not something that can be taken for granted. Lacking this
background, we need to construct a universe of topics from scratch.
For the more extensively researched classic repertoire, a universe of topic is
already implicit in the writings of Ratner, Allanbrook, Hatten, and Monelle. I list
61 of the more common topics here without elaboration simply to orient readers to the worlds of affect, style, and technique that they set in motion. Some are
everyday terms used by musicologists; others are less familiar terms drawn from
various eighteenth-century sources. All occur in various compositionssome
well known, others obscure.
The Universe of Topic for Classic Music
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Alberti bass
alla breve
alla zoppa
allemande
amoroso style
aria style
arioso
bound style or stile
legato
bourre
brilliant style
buffa style
cadenza
chaconne bass
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
chorale
commedia dellarte
concerto style
contredanse
ecclesiastical style
Empfindsamer style
Empfindsamkeit
(sensibility)
fanfare
fantasia style
French overture
style
fugal style
fugato
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
galant style
gavotte
gigue
high style
horn call
hunt style
hunting fanfare
Italian style
Lndler
learned style
Lebewohl (horn
figure)
37. low style
38. march
44
39.
40.
41.
42.
43.
44.
45.
46.
47.
PART I
Theory
middle style
military figures
minuet
murky bass
musette
ombra style
passepied
pastorale
pathetic style
48. polonaise
49. popular style
50. recitative (simple,
accompanied,
oblig)
51. romanza
52. sarabande
53. siciliano
54. singing allegro
How is this universe domesticated within a given work? Because there exist,
by now, several considered demonstrations of topical analysis, we can pass over
the eighteenth-century portions of this discussion rapidly by simply mentioning
the topical content of four canonical movements by Mozart. The first movement
of the Piano Sonata in F Major, K. 332, includes aria style, singing style, Alberti
bass, learned style, minuet, horn duet, horn fifths, Sturm und Drang, fanfare,
amoroso style, bound style, and brilliant style. The first movement of the Piano
Sonata in D Major, K. 284, incorporates (references to) concerto style, murky bass,
singing style, Trommelbass, brilliant style, march, recitative oblig style, fanfare,
and bound style. The first movement of the Jupiter Symphony, K. 551, includes
fanfare, march, singing style, Sturm und Drang, contredanse, and learned style.
And the introduction to the Prague Symphony, K. 504, includes (allusions to)
French overture, Empfindsamkeit, singing style, learned style, fanfare, and ombra.
Where and how these topics are used and their effect on overall expression and
structure are the subjects of detailed studies by Allanbrook, Ratner, Sisman,
Silbiger, and myself.4
Topical analysis begins with identification. Compositional manipulations of
rhythm, texture, and technique suggest certain topical or stylistic affiliations, and
the analyst reaches into his or her stock (or universe of topics) assembled from
prior acquaintance with a range of works in order to establish correlations. Identification is followed by interpretation. Topics may enable an account of the form
or inner dynamic of a work, its expressive stance, or even its structure. The use
of identical or similar topics within or between works may provide insight into
a works strategy or larger aspects of style. And the shapes of individual topics
4. For a fuller discussion of topics in K. 332, see Wye J. Allanbrook, Two Threads through the
Labyrinth, in Convention in Eighteenth- and Nineteenth-Century Music: Essays in Honor of Leonard
G. Ratner, ed. Wye J. Allanbrook, Janet M. Levy, and William P. Mahrt (Stuyvesant, NY: Pendragon,
1992), 125171; and Alexander Silbiger, Il chitarrino le suoner: Commedia dellarte in Mozarts
Piano Sonata K. 332 (paper presented at the annual meeting of the Mozart Society of America,
Kansas City, November 5, 1999). On K. 284, see Leonard G. Ratner, Topical Content in Mozarts
Keyboard Sonatas, Early Music 19(4) (1991): 615619; on K. 551, see Sisman, Mozart: The Jupiter
Symphony; and on K. 504, see Ratner, Classic Music, 2728 and 105107; Agawu, Playing with Signs,
1725; and Sisman, Genre, Gesture and Meaning in Mozarts Prague Symphony, in Mozart Studies,
vol. 2, ed. Cliff Eisen (Oxford: Oxford University Press, 1997), 2784.
CHAPTER 2
45
may enhance appreciation of the sonic quality of a given work and the nature of a
composers rhetoric.
Constructing a comparable universe for Romantic music would fill more
pages than we have at our disposal. Fortunately, the material for constructing
such a universe may be gleaned from a number of books and articles. Ratners
book on Romantic music, although not deeply invested in notions of topic, draws
attention to those aspects of compositions that signify in the manner of topics
even while stressing the role of sheer sound, periodicity, texture, and harmony
in this repertoire.5 In two related books, Raymond Monelle has given due consideration to ideas of topic. The first, The Sense of Music, supplements a critical account of Ratners theory with a set of semiotic analyses of music by Bach,
Mahler, Tchaikovsky, and others. The second, The Musical Topic: Hunt, Military
and Pastoral, explores the musical and cultural contexts of three musical topics
through a broad historical landscape. Monelles interest in the latter book is not
in reading individual compositions for possible topical traces (although he provides a fascinating description of hunts in instrumental music by Mendelssohn,
Schumann, Paganini, Franck, and Bruckner),6 but in assembling a kaleidoscope of
contexts for topics. While The Sense of Music constitutes a more or less traditional
(but highly suggestive) music-analytical exercisecomplete with the theoretical
self-consciousness that became evident in musical studies during the 1990sThe
Musical Topic moves in the direction of the larger humanistic enterprise known
as cultural studies, emphasizing an array of intertextual resonances. There are,
however, writers who remain committed to close readings of musical works
informed by topic. One such writer is Robert Hatten, whose Interpreting Musical
Gestures, Topics, and Tropes: Mozart, Beethoven, Schubert extends the interpretive
and reflective exercise begun in his earlier book, Musical Meaning in Beethoven:
Markedness, Correlation and Interpretation, and supplements it with a new theory
of gesture.7
Most pertinent is a valuable article by Janice Dickensheets in which she cites
examples from a broad range of composers, among them Carl Maria von Weber,
Chopin, Schubert, Berlioz, Mendelssohn, Smetana, Grieg, Heinrich Herz, SaintSans, Liszt, Verdi, Brahms, Mahler, and Tchaikovsky. She notes the persistence
into the nineteenth century of some of Ratners topics, including the musical
types minuet, gigue, siciliano, and march, and the musical styles military, hunt,
pastoral, and fantasia; the emergence of new styles and dialects; and the contextual inflection of old topics to give them new meanings. Her lexicon includes the
following, each of which is illustrated with reference to a specific compositional
manifestation:8
5. Ratner, Romantic Music: Sound and Syntax (New York: Schirmer, 1992).
6. Monelle, The Musical Topic, 8594.
7. Robert Hatten, Interpreting Musical Gestures, Topics, and Tropes: Mozart, Beethoven, Schubert
(Bloomington: Indiana University Press, 2004).
8. Janice Dickensheets, Nineteenth-Century Topical Analysis: A Lexicon of Romantic Topoi,
Pendragon Review 2(1) (2003): 519.
46
1.
2.
3.
4.
5.
6.
7.
8.
PART I
Theory
archaizing styles
aria style
bardic style
bolero
Biedermeier style
Chinoiserie
chivalric style
declamatory
style (recitative
style)
9.
10.
11.
12.
13.
14.
15.
16.
demonic style
fairy music
folk style
gypsy music
heroic style
Indianist style
Italian style
lied style or song
style (including lullaby,
17.
18.
19.
20.
21.
22.
23.
24.
Kriegslied, and
Winterlied)
pastoral style
singing style
Spanish style
style hongrois
stile appassionata
tempest style
virtuosic style
waltz (Lndler)
10.
11.
12.
13.
recitativo
lamenting, elegiac
citations
the grandioso,
triumfando (going
back to the heroic
theme)
14. the lugubrious
type deriving at
the same time
from appassionato
and lamentoso
(lagrimoso)
15. the pathetic, which
is the exalted form
of bel canto
16. the pantheistic,
an amplified
variant of either
the pastoral theme
or of the religious
type
CHAPTER 2
47
In the music of Mahler, the essential utterance is heterogeneous at the core, and
although not all aspects of such heterogeneity can be given a topical designation,
many can. The following are some of the topics regularly employed by Mahler:11
1.
2.
3.
4.
5.
6.
nature theme
fanfare
horn call
bird call
chorale
pastorale
7. march (including
funeral march)
8. arioso
9. aria
10. minuet
11. recitative
12. scherzo
13.
14.
15.
16.
17.
18.
bell motif
Totentanz
lament
Lndler
march
folk song
Press, 1992], 115), and in Liszts use of symbols in his Transcendental tudes (see Samson, Virtuosity and the Musical Work: The Transcendental Studies of Liszt [Cambridge: Cambridge University
Press, 2007], 175197). In an unpublished study of Paganinis violin concertos, Patrick Wood highlights a sharply profiled expressive genre which progresses from a march topic to an opposing lyrical topic (such as the singing style) as the frame of the exposition of the first movement. See Wood,
Paganinis Classical Violin concerti (unpublished seminar paper, Princeton University, 2008).
11. Among commentators on Mahlers music, something approaching the notion of topos appears
most explicitly in the writings of Constantin Floros. See, for example, his Gustav Mahler: The Symphonies, trans. Vernon Wicker (Portland, OR: Amadeus, 1993).
48
PART I
Theory
compositions like the Rite of Spring, Pierrot Lunaire, Salome, or Weberns Five
Pieces for String Quartet, op. 5, resistance to the past is, paradoxically, a way of
registering belief in its potency, ultimately of displaying that past even while denying it. A topical approach supports such counternarratives.
The universe of topic has thus undergone a range of transformations from the
eighteenth through the nineteenth and twentieth centuries and into the twentyfirst. To put these developments in a nutshell: in the eighteenth century, topics
were figured as stylized conventions and were generally invoked without pathos
by individual composers, the intention being always to speak a language whose
vocabulary was essentially public without sacrificing any sort of will to originality.
In the nineteenth century, these impulses were retained, but the burgeoning of
expressive possibilities brought other kinds of topic into view. Alongside the easily recognized conventional codes were others that approximated natural shapes
(such as the dynamic curve or high-point scheme that we will discuss shortly) and
some that were used consistently within a single composers oeuvre or idiolect
(Schumanns numerous ciphers and the Florestan, Eusebius, and Raro personifications are cases in point). Twentieth-century topical practice became, in part, a
repository of eighteenth- and nineteenth-century usages even as the universe was
expanded to include the products of various strategic denials. Thus, certain rhetorical gestures associated with Romantic music took on a historical or topical role
in twentieth-century music, while the dynamic curve, which we will discuss under
the rubric high point, was, despite its quintessentially Romantic association, also
found in a variety of twentieth-century repertoires, including electronic music.12
Musics associated with specific groups (Jewish, gypsy) retained their vitality for
quotation and allusion, while newer musical developmentssuch as the AfricanAmerican traditions of blues, gospel, funk, jazz, and rapprovided material for
topical exploration and exploitation by composers.
In an unpublished construction of a topical universe for twentieth-century
music, Danuta Mirka divides topics into three groups. The first (group A) embraces
eighteenth-century dances, the second (group B) lists musics associated with various ethnicities, and the third (group C) is a diverse collection of styles:
Group A
1.
2.
3.
4.
5.
6.
7.
8.
menuet
gavotte
bourre
sarabande
gigue
pavane
passepied
tarantella
9. tango
10. waltz
Group B
11.
12.
13.
14.
Jewish music
Czech music
Polish music
Hungarian
music
15.
16.
17.
18.
Gypsy music
Russian music
Spanish music
Latin-American
music (Brazilian, Argentinean,
Mexican,)
19. Oriental music
(Chinese,
12. See Patrick McCreless, Anatomy of a Gesture: From Davidovsky to Chopin and Back, in
Approaches to Musical Meaning, ed. Byron Almen and Edward Pearsall (Bloomington: Indiana
University Press, 2006), 1140, for a study of this phenomenon.
CHAPTER 2
Japanese,
Indian)
20. North American
country music
Group C
21. Gregorian
chant
22. chorale
49
circus music
barrel organ
lullaby
childrens song
fanfare
military march
funeral march
pastoral style
elegy
machine music
The music of Bartk and Stravinsky lends itself well to topical analysis. In a study
of Bartks orchestral works, Mrta Grabcz has identified 10 recurring topics:13
1. the ideal or the quest for the ideal, expressed through the learned style
2. the grotesque, signaled by a combination of rhythmic practices (mechanical, the waltz), instrumental association (clarinet), and the octatonic collection
3. the image of the hopeless and gesticulating hero, expressed in dissonant,
bitonal contexts with repeated fourths and fifths
4. nature (calm, friendly, or radiant), signaled by the acoustic scale
5. nature (hostile, menacing), conveyed by minor harmonies and the chromatic
scale
6. nocturnal nature, expressed by string timbre, march-like melody, enchanting sonorities
7. elegy, expressed in a static or passive atmosphere
8. perpetuum mobile, manifest in ostinato or motoric movement
9. popular dance, song in a peasant style
10. metamorphosis, restricted to certain moments in the form and characterized by the transcendence or transubstantiation of the last appearance of a
musical idea that has been present in varied form since the beginning
In Stravinskys music, an essentialized parasitical tendency often originates in
a play with, or appropriation of, established topics. At the root of the aesthetic
lies a desire to creatively violate commonplaces or figures burdened with historical or conventional meaning. In their important study Apollonian Clockwork: On
Stravinsky, Louis Andriessen and Elmer Schnberger unveil many of the composers subtexts, thus bringing into aural view the foils and intertexts that form an
essential part of the composers work. Apollonian Clockwork is as much a study of
topic as of anything else. To choose just one example that readers can readily recall:
Lhistoire du soldat, composed in 1918, is a veritable catalog of topical references.
13. Mrta Grabcz, Topos et dramaturgie: Analyse des signifis et de la strategie dans deux movements symphoniques de B. Bartok [sic], Degrs 109110 (2002): j1j18. The article includes a summary of the secondary literature on Bartk that alludes to or deals directly with topics, even where
authors do not use the term.
50
PART I
Theory
To facilitate the narrating of the soldiers tale, Stravinsky draws on four central
topical classes. The first, march, is presented in different guises or expressive registers (soldiers march, royal march, and the devils triumphal march) without ever
losing its intrinsic directionality. The second is dance, of which tango, waltz, and
ragtime serve as conventional exemplars alongside a devils dance. The third is pastorale, complete with airs performed by a stream. The fourth is chorale, manifest
in two sizes, a little chorale that lasts only 8 bars and the grand chorale, which goes
on for some 29 bars, interspersed with the soldiers narration. Within these bigger
topical umbrellas, little topics are invoked: fanfares, drones reminiscent of musette,
and the Dies Irae chant. The play element that guides the disposition of these
materials is equally important, of course, especially as a window onto a discourse
of repetition. But recognizing the Soldiers March as a veritable parade of historical
styles is already a step in the right direction.14
To hear Romantic and post-Romantic music topically, then, is to hear it as a
repository of historically situated conventional styles that make possible a number
of dialogues. The examples mentioned hereby Mozart, Beethoven, Schumann,
Liszt, Mahler, and Stravinskyare only an indication of what is a vast and complex
universe. Identifying topics, however, is only the first stage of analysis; interpretation must follow. Interpretation can be confined to meanings set in motion within
a piece or include those that are made possible in intertextual space. The analyst
might assess the work done by individual topics in a composition and, if s/he so
desires, fashion a narrative that reflects their disposition. In some contexts, a plot
will emerge for the individual composition; in others, topics will be absorbed into
a larger expressive genre15 or indeed a commanding structural trajectory; in still
others, fragments will retain their identities on the deepest levels, refusing absorption into or colonization by an archetypal, unified plan. In practice, identifying
topics can produce relatively stable results; interpreting topics, by contrast, often
turns up diverse plots. Whereas identification entails a discovery of familiar or
relatively objective configurations, interpretation is the exercise of an imaginative
willa fantasy fueled by the analysts capacity for speculation. There are no firm
archetypes upon which to hang an interpretation of the plots arising from topical
succession. The results of identification differ from composition to composition.
A topical analysis confirms the uniqueness of a given composition while also making possible a comparison of material content that might enable an assessment of
affinity among groups of compositions.16
14. Debussys Prelude for Piano, Minstrels, makes a fascinating case study in topical expression. Within
its basic scherzo-like manner, it manages to incorporate diverse allusions to other musical styles. One
should perhaps distinguish between topical use and the kinds of deliberate quotation or allusion studied by Christopher Reynolds in Motives for Allusion: Context and Content in Nineteenth-Century Music
(Cambridge, MA: Harvard University Press, 2003); and David Metzer in Quotation and Cultural Meaning in Twentieth-Century Music (Cambridge: Cambridge University Press, 2003). Among twentiethcentury composers whose music strongly invites topical treatment, Kurt Weill ranks high.
15. Hatten, Musical Meaning in Beethoven, 6790.
16. For a recent assessment of topic theory, see Nicholas Peter McKay, On Topics Today, Zeitschrift
der Gesellschaft fr Musiktheorie 4 (2007). http:/.
Accessed August 12, 2008.
CHAPTER 2
51
17. Johann Mattheson, Der vollkommene Capellmeister, trans. Ernest Harriss (Ann Arbor, MI: UMI
Research Press, 1981; orig. 1739).
18. Heinrich Christoph Koch, Versuch einer Anleitung zur Composition, vols. 2 and 3 (Leipzig: Bhme,
1787 and 1793).
19. Schenker, Free Composition, 129.
20. Carl Dahlhaus, Between Romanticism and Modernism, trans. Mary Whittall (Berkeley: University
of California Press, 1980), 64.
21. Agawu, Playing with Signs, 5179.
22. William E. Caplin, Classical Form: A Theory of Formal Functions for the Instrumental Music of
Haydn, Mozart and Beethoven (Oxford: Oxford University Press, 2000), 35 and 24.
23. Craig Ayrey, Review of Playing with Signs, Times Higher Education Supplement 3 (May 1991), 7.
52
PART I
Theory
fact that, as a set of qualities, beginnings, middles, and endings are not located
in a single musical dimension but cut across various dimensions. In other words,
interpreting a moment as a beginning or an ending invariably involves a reading
of a combination of rhythmic, melodic, and harmonic factors as they operate in
specific contexts. In an institutional climate in which analysts tend to work within
dimensions as specialists, theories that demand an interdimensional approach
from the beginning seem to pose special challenges. These difficulties are, however, not insurmountable, and it will be part of my purpose here to suggest ways
in which attending to beginnings, middles, and endings can enrich our perception
of Romantic music.
For many listeners, the impression of form is mediated by beginning, middle, and
ending functions. Tchaikovskys First Piano Concerto opens with a powerful beginning gesture that, according to Edward T. Cone, dwarfs the rest of what followsa
disproportionately elaborate opening gesture that sets the introduction off as an
overdeveloped frame that fails to integrate itself with the rest of the movement.24
Some openings, by contrast, proceed as if they were in the middle of a process previously begun; such openings presuppose a beginning even while replacing it with
a middle. Charles Rosen cites the long dominant pedal that opens Schumanns Fantasy in C Major for Piano, op. 17, as an example of a beginning in medias res.25 And
an ending like that of the finale of Beethovens Fifth, with its plentiful reiteration of
the tonic chord, breeds excess; strategically, it employs a technique that might be
figured as rhetorically infantile to ensure that no listener misses the fact of ending.
Ending here is, however, not merely a necessary part of the structure; it becomes a
subject for discussion as wella meta-ending, if you like.26
As soon as we begin to cite individual works, many readers will, I believe, find
that they have a rich and complex set of associations with beginnings, middles,
and endings. Indeed, some of the metaphors employed by critics underscore the
importance of these functions. Lewis Rowell has surveyed a variety of beginning
strategies in music and described them in terms of birth, emergence, origins, primal cries, and growth.27 Endings, similarly, have elicited metaphors associated with
rest and finality, with loss and completion, with consummation and transfiguration, with the cessation of motion and the end of life, and ultimately with death
and dying. No more, we might say at the end of Tristan and Isolde.
How might we redefine the beginning-middle-ending model for internal
analytic purposes? How might we formulate its technical processes to enable
exploration of Romantic music? Every bound temporal process displays a beginning-middle-ending structure. The model works at two distinct levels. First is the
pure material or acoustical level. Here, beginning is understood ontologically as that
which inaugurates the set of constituent events, ending as that which demarcates
24. Cone, Musical Form and Musical Performance (New York: Norton, 1968) 22.
25. Rosen, The Classical Style, 452453.
26. Donald Francis Tovey comments on the appropriateness of this ending in A Musician Talks, vol. 2:
Musical Textures (Oxford: Oxford University Press, 1941), 64.
27. Lewis Rowell, The Creation of Audible Time, in The Study of Time, vol. 4, ed. J. T. Fraser, N.
Lawrence, and D. Park (New York: Springer, 1981), 198210.
CHAPTER 2
53
the completion of the structure, and middle as the necessary link between beginning and ending. At this level, the analyst is concerned primarily with sound and
succession, with the physical location of events.
There is a second, more qualitative level at which events (no longer mere
sounds) are understood as displaying tendencies associated with beginnings, middles, and endings. These functions are based in part on convention and in part on logic.
A beginning in this understanding is an event (or set of events) that enacts the normative function of beginning. It is not necessarily what one hears at the beginning
(although it frequently is that) but what defines a structure qualitatively as a beginning. A middle is an event (or set of events) that prolongs the space between the
end of the beginning and the beginning of the ending. It refuses the constructive
profiles of initiation and peroration and embraces delay and deferral as core rhetorical strategies. Finally, an ending is an event (or set of events) that performs the
functions associated with closing off the structure. Typically, a cadence or cadential
gesture serves this purpose. An ending is not necessarily the last thing we hear in
a composition; it may occur well before the last thing we hear and be followed by
rhetorical confirmation. The task of an ending is to provide a decisive completion
of structural processes associated with the beginning and middle.
The first level of understanding, then, embodies the actual, material unfolding
of the work and interprets the beginning-middle-ending model as a set of place
marks; this is a locational or ordinal function. The second speaks to structural
function within the unfolding. Distinguishing between location and function has
important implications for analysis. In particular, it directs the listener to some
of the creative ways in which composers play upon listeners expectations. For
example, a locational opening, although chronologically prior, may display functions associated with a middle (as in off-tonic beginnings, or works that open with
auxiliary cadences) or an ending (as in works that begin with cadences or with a
2
1 or 5
4
3
2
1 melodic progression). Location and function would thus be
3
nonaligned, creating a dissonance between the dimensions. Similarly, in a locational ending, the reiterative tendencies that index stability and closure may be
replaced by an openness that refuses the drive to cadence, thus creating a sense of
middle, perhaps an equivocal ending. Creative play of this kind is known in connection with classic music, whose trim procedures and firmly etched conventions
have the great advantage of sharpening our perception of any creative departures
that a composer might introduce. It is also frequently enacted by Romantic composers within their individual and peculiar idiolects.
Although all three locations are necessary in defining a structure, associated
functions may or may not align with the locations. It is also possiblefunctionally
speakingto lose one element of the model by, for example, deploying a locational ending without a sense of ending. It would seem, in fact, that beginnings and
endings, because they in principle extend in time and thus function as potential
colonizers of the space we call middle, are the more critical rhetorical elements of
the model. In certain contexts, it is possible to redefine Aristotles model with no
reference to middles: a beginning ends where the ending begins. It is possible also
to show that, in their material expression, beginnings and endings frequently draw
on similar strategies. The stability or well-formedness needed to create a point of
54
PART I
Theory
reference at the beginning of a musical journey shares the material formsbut not
necessarily the rhetorical presentationof a comparable stability that is needed to
ground a dynamic and evolving structure at its end. It is also possible that endings,
because they close off the structure, subtend an indispensable function. From this
point of view, if we had to choose only one of the three functions, it would be ending. In any case, several of these functional permutations will have to be worked
out in individual analyses.
It is not hard to imagine the kinds of technical processes that might be associated with beginnings, middles, and endings. Techniques associated with each of a
works dimensionsharmony, melody, rhythm, texturecould be defined normatively and then adapted to individual contexts. With regard to harmony, for example, we might say that a beginning expresses a prolonged IV(I) motion. (I have
placed the closing I in parenthesis to suggest that it may or may not occur, or that,
when it does, its hierarchic weight may be significantly less than that of the initiating I.) But since the beginning is a component within a larger, continuous structure, the IV(I) progression is often nested in a larger IV progression to confer
prospect and potential, to ensure its ongoing quality. A middle in harmonic terms
is the literal absence of the tonic. This often entails a prolongation of V. Since such
prolonged dominants often point forward to a moment of resolution, the middle is
better understood in terms of absence and promise: absence of the stable tonic and
presence of a dependent dominant that indexes a subsequent tonic. An ending in
harmonic terms is an expanded cadence, the complement of the beginning. If the
larger gesture of beginning is represented as IV, then the reciprocal ending gesture
is VI. The ending fulfills the harmonic obligation exposed in the beginning, but
not under deterministic pressure. As with the beginning and ending of the beginning, or of the middle, the location of the beginning and ending functions of the
ending may or may not be straightforward. In some genres, endings are signaled by
a clearly marked thematic or tonal return or by a great deal of fanfare. In others, we
sense the ending only in retrospect; no grand activity marks the moment of death.
Similar attributions can be given for other musical dimensions. In doing so, we
should remember that, if composition is figured essentially as a mode of play, what
we call norms and conventions are functional both in enactment and in violation.
On the thematic front, for example, we might postulate the imperatives of clear statement or definition at the beginning, fragmentation in the middle, and a restoration
of statement at the ending, together with epigonic gestures or effects of reminiscence.
In terms of phrase, we might postulate a similar plot: clarity (in the establishment of
premises) followed by less clarity (in the creative manipulation of those premises)
yields, finally, to a simulated clarity at the end. In addition to such structural procedures, we will need to take into account individual composerly routines in the choreographing of beginnings and endings. Beethovens marked trajectories, Schuberts
way with extensive parentheses and deferred closure, Mendelssohns delicately balanced proportions, and the lyrical inflection of moments announcing home-going
in Brahmsthese are attitudes that might be fruitfully explored under the aegis of a
beginning-middle-ending scheme. We have space here for only one composer.
As an example of the kinds of insights that might emerge from regarding a
Romantic work as a succession of beginnings, middles, and endings on different
CHAPTER 2
55
levels, I turn to Mendelssohns Song without Words in D major, op. 85, no. 4 (reproduced in its entirety as example 2.1). The choice of Mendelssohn is not accidental,
for one of the widely admired features of his music is its lucidity. In the collection
Example 2.1. Mendelssohn, Song without Words in D major, op. 85, no. 4.
Andante sostenuto.
sf
sf
sf
10
cresc.
13
cresc.
16
19
pi f
(continued)
56
PART I
Theory
sf
cresc.
25
cresc.
dim.
28
cresc.
dim.
31
34
of songs without words, each individual song typically has one central idea that
is delivered with a precise, superbly modulated, and well-etched profile. The compositional idea is often affectingly delivered. And one reason for the composers
uncanny success in this area is an unparalleled understanding of the potentials of
beginning, middle, and ending in miniatures. I suggest that the reader play through
this song at the piano before reading the following analytical comments.
We might as well begin with the ending. Suppose we locate a sense of homegoing beginning in the second half of bar 26. Why there? Because the rising minor
seventh in the melody is the first intervallic event of such magnitude in the composition; it represents a marked, superlative moment. If we follow the course of the
melody leading up to that moment, we hear a physical rise in contour (starting on
F-sharp in 24) combined with an expansion of intervals as we approach the high G
in bar 26. Specifically, starting from the last three eighth-notes in bar 25, we hear, in
succession, a rising fourth (AD), a rising sixth (GE), and finally a rising seventh
CHAPTER 2
57
(AG). Then, too, this moment is roughly two-thirds of the way through the song,
is underlined by an implicative 6/5 harmony that seeks resolution, and represents
the culmination of a crescendo that has been building in the preceding 2 bars. The
moment may be figured by analogy to an exclamation, an expected exclamation
perhaps. It also marks a turning point, the most decisive turning point in the form.
Its superlative quality is not known only in retrospect. From the beginning, Mendelssohn, here as in other songs without words, crafts a listener-friendly message
in the form of a series of complementary gestures. Melody leads (that is, functions
as a Hauptstimme); harmony supports, underlines, and enhances the progress of
the melody; and the phrase structure regulates the temporal process while remaining faithful in alignment. The accumulation of these dimensional behaviors prepares bar 26. Although full confirmation of the significance of this moment will
come only in retrospect, the balance between the prospective and retrospective,
here as elsewhere in Mendelssohn, is striking. Luminous, direct, natural, and perhaps unproblematic (as we might say today), op. 85, no. 4 exemplifies carefully
controlled temporal profiling.
Ultimately, the sense of ending that we are constructing cannot be understood
with respect to a single moment, for that moment is itself a product of a number
of preparatory processes. Consider bar 20 as the beginning of the ending. Why bar
20? Because the beautiful opening melody from bar 2 returns at this point after
some extraneous, intervening material (bars 1219). For a work of these modest
dimensions, such a large-scale return readily suggests a reciprocal sense of closure
within a tripartite formal gesture.
If we continue to move back in the piece, we can interpret the passage beginning in bar 12 as contrast to, as well as intensification of, the preceding 11 bars. Note
the quasi-sequential process that begins with the upbeat to bar 12. Phrase-wise, the
music proceeds at first in 2-bar units (114133, 134153; these and subsequent designations of phrase boundaries in this paragraph all include an eighth-note prefix),
then continues in 1-bar units in the manner of a stretto (154163 and 164173), and
finally concludes with 2 relatively neutral barsneutral in the sense of declining
a clear and repeated phrase articulationof transition back to the opening theme
(174193).28 The moment of thematic return on the downbeat of bar 20 is supported
not by tonic harmony as in bar 2 but by the previously tonicized mediant, thus
conferring a more fluid quality on the moment and slightly disguising the sense of
return. The entire passage of bars 1219 features rhetorically heightened activity
that ceases with the thematic return in bar 20. If, in contrast to the earlier hearing,
the passage from bar 20 to the end is heard as initiating a closing section at the largest level of the form, then bars 1219 may be heard as a functional middle.
Finally, we can interpret the opening 11 bars as establishing the songs premises, including its material and procedures. A 1-bar introduction is followed by a
4-bar phrase (bars 25). Then, as if repeating (bar 6), the phrase is modified (bar
7) and led through B minor to a new tonal destination, F-sharp minor (bars 893).
28. Bars 174182 begin in the manner of the previous 1-bar units but modify their end in order to lead
elsewhere.
58
PART I
Theory
but 325 (FEA not FED), the 1 sounding in an inner voice so that the less
conclusive melodic 5 can initiate a second attempt at closure. The local harmony at
283291 is not V6/45/3I (with the second and third chords in root position) but
the more mobile V6/4V4/2I6.29 Part of Mendelssohns strategy here is to embed
the more obvious gestures of closure within a larger descending-bass pattern that
will lend a sense of continuity to the closing moment. This line starts with bass A
on the third beat of 28, passes through G (also in 28) then falls through F-sharp,
F-natural, and E before reaching a mobile D on the downbeat of 30, making room
for an intervening A at 294. A similarly directed bass line preceded this one and
served to prepare the high point of bar 26. We can trace it from the third beat of
bar 23: DCB (bar 23), AAGF (bar 24), then, transferred up the octave,
EDCB (bar 25), and finally A (downbeat of 26), the whole spanning an octave
and a half.
Unlike the attempt at closure in bars 2829, the one in bars 3132 reaches its
2
1 over a VI offers what was previously denied.
destination. A conventional 3
Many listeners will hear the downbeat of bar 32 as a defining moment, a longed-for
moment, perhaps, and, in this context, the place where various narrative strands
meet. Schenker would call this the definitive close of the composition;30 it marks
the completion of the works subsurface structural activity. Syntactic closure is
achieved. We might as well go home at this point.
But syntactic closure is only one aspectalbeit an important oneof the full
closing act. There is also a complementary dimension that would secure the rhetorical sense of the close, for although we have attained 1 over I, we need to savor
D for a while, to repose in it, to dissolve the many tensions accumulated in the
course of the song. This other dimension of closure can be described in different
ways: as rhetorical, as gestural, or even as phenomenal. In this song without words,
Mendelssohn writes a codetta-like segment (bars 32end) to meet this need. These
last 6 bars are a tonic prolongation. We sense dying embers, a sense of tranquility,
the serenity of homecoming, even an afterglow. We may also hear in them a sense
of reminiscence, for the sense that death is approaching can be an invitation to
29. Here and elsewhere, I follow Schenkerian practice in understanding cadential 6/4s as dominantfunctioning chords featuring a double suspension to the adjacent root-position dominant chord.
Hence the symbol V6/45/3.
30. Schenker, Free Composition, 129.
CHAPTER 2
59
relive the past in compressed form. It is as if key moments in the form are made
to flash before our very eyes, not markedly as quotations, but gently and subtly, as
if in a mist, as if from a distance. One of the prominent elements in this ending is
6
5,
which was adumbrated in the very
a simple neighbor-note motive, ABA or 5
first bar of the song, where B served as the only non-chord tone within the tonic
expression. Subsequently, the notes B and A were associated in various contexts.
Then, in bars 3233, the ABA figure, now sounding almost like a wail, presses the
melodic tone A into our memories. The V6/5 harmony in the second half of bars
32 and 33 may also remind us of the high point in bar 26. Then, too, we experi 4
3
2
1 descent across bars 3335. This collection of
ence a touchingly direct 5
scale degrees was introverted in bars 2133, sung in V but without 4 in bars 1011,
introverted again in bars 201213, embedded in bars 2829, heard with 5 playing
only an ornamental role in bars 3132, before appearing in its most direct and
pristine form in bars 324353. Even the dotted-note anacrusis at bar 324 has some
precedent in bars 1112, where it energized the first major contrasting section in
the song. And the extension of the right hand into the highest register of the piece
in the penultimate bar recalls salient moments of intensification around bars 16
and 17 and of the high point in bar 26 and its echo in 29. These registral extensions
afford us a view of another world. Overall, then, the last 6 bars of Mendelssohns
song make possible a series of narratives about the compositional dynamic, among
which narratives of closure are perhaps most significant.
We began this analysis of Mendelssohns op. 85, no. 4, by locating the beginning
of the ending in bar 26; we then worked our way backward from it. But what if we
begin at the beginning and follow the course of events to the end? Obviously, the
two accounts will not be wholly different, but the accumulation of expectations
will receive greater emphasis. As an indication of these revised priorities and so
as to fill in some of the detail excluded from the discussion so far, let us comment
(again) on the first half of the song (bars 119). Bar 1 functions as a gestural prelude to the beginning proper; it familiarizes us with the sound and figuration of
the tonic, while also coming to melodic rest on the pitch A as potential head tone.
The narrative proper begins in bar 2 with a 4-bar melody. We are led eventually to
the end of the beginning in bar 11, where the dominant is tonicized. Mendelssohns
procedure here (as also frequently happens in Brahms, for example, in the song
Wie Melodien zieht es mir, op. 105) is to begin with a head theme or motif and
lead it to different tonal destinations. In the first 4-bar segment (bars 25), the
harmonic outline is a straightforward IV. A second 4-bar segment begins in bar
6, passes through the submediant in 78, and closes in the mediant in bar 9. But,
as mentioned before, the emphatic upbeat to bar 10, complete with a Vii6/5 of V
(thinking in terms of A major), has the effect of correcting this wrong destination. If one is looking to locate the end of the beginning, one might assign it to the
emphatic cadence on the dominant in bar 11. Yet, the end of the beginning and the
beginning of the middle are often indistinguishable. The exploratory potential signaled by A-sharp in bar 7, the first nondiatonic pitch in the song, confers a gradual
sense of middle on bars 711. This sense is intensified in a more conventional way
beginning with the upbeat to bar 12. From here until bar 20, the music moves
in five waves of increasing intensity that confirm the instability associated with a
60
PART I
Theory
middle. Example 2.2 summarizes the five waves. As can be seen, the melodic profile
is a gradual ascent to A, reached in wave 4. Wave 3 is interrupted in almost stretto
fashion by wave 4. Wave 5 begins as a further intensification of waves 3 and 4 but
declines the invitation to exceed the high point on A reached in wave 4, preferring
G-sharp (a half step lower than the previous A) as it effects a return from what, in
retrospect, we understand as the point of greatest intensity. Wave 5 also adopts the
contour of waves 1 and 2, thus gaining a local reprise or symmetrical function. It
emerges that the tonicized mediant in bar 9 was premature; the mature mediant
occurs in bars 1920.
Example 2.2. Five waves of action across bars 1220 in Mendelssohn, Song without Words in D major, op. 85, no. 4.
12
wave 1
14
wave 2
16
wave 3
17
wave 4
18
wave 5
Stepping back from the detail of Mendelssohns op. 85, no. 4, we see that the
beginning-middle-ending model allows us to pass through a Romantic composition by weighing its events relationally and thus apprehending its discourse. The
model recognizes event sequences and tracks the tendency of the musical material.
In this sense, it has the potential to enrich our understanding of what musicians
normally refer to as forma complex, summary quality that reflects the particular
constellation of elements within a composition. There is no mechanical way to
apply a beginning-middle-ending model; every interpretation is based on a reading of musical detail. Interpretations may shift depending on where a beginning
is located, what one takes to be a sign of ending, and so on. And while the general
features of these functions have been summarized and in part exemplified in the
Mendelssohn analysis, the fact that they are born of convention means that some
aspects of the functions may have escaped our notice. Still, attention to musical
rhetoric as conveyed in harmony, melody, phrase structure, and rhythm can prove
enlightening.
The beginning-middle-ending model may seem banal, theoretically coarse,
or simply unsophisticated; it may lack the predictive power of analytical theories
that are more methodologically explicit. Yet, there is, it seems to me, some wisdom in resisting the overdetermined prescriptions of standard forms. This model
CHAPTER 2
61
substitutes a set of direct functions that can enable an individual analyst to get
inside a composition and listen for closing tendencies. Musicology has for a long
time propagated standard forms (sonata, rondo, ternary, and a host of others) not
because they have been shown to mediate our listening in any fundamental way,
but because they can be diagrammed, given a two-dimensional visual appearance,
and thus easily be represented on screens and blackboards and in books, articles,
and term papers. A user of the beginning-middle-ending model, by contrast,
understands the a priori functions of a sonata exposition as mere designation;
a proper analysis would inspect the work afresh for the complex of functions
many of them of contradictory tendencythat define the activity within, say, the
exposition space. To say that a dialogue is invariably set up between the normative
functions in a sonata form and the procedures on the ground, so to speak, is an
improvement, but even this formulation may overvalue the conventional sense of
normative functions. Analysis must deal with the true nature of the material and
recognize the signifying potential of a works building blocksin short, respond
to the internal logic of the work, not the designated logic associated with external
convention. Reorienting thinking and hearing in this way may make us freshly
aware of the complex dynamism of musical material and enhance our appreciation of music as discourse.
High Points
A special place should be reserved for high points or climaxes as embodiments of
an aspect of syntax and rhetoric in Romantic musical discourse. A high point is a
superlative moment. It may be a moment of greatest intensity, a point of extreme
tension, or the site of a decisive release of tension. It usually marks a turning point
in the form (as we saw in bar 26 of example 2.1). Psychologically, a single high point
typically dominates a single composition, but given the fact that a larger whole
is often constituted by smaller parts, each of which might have its own intensity
curve, the global high point may be understood as a product of successive local
high points. Because of its marked character, the high point may last a moment,
but it may also be represented as an extended momenta plateau or region.
No one performing any of the diverse Romantic repertoires can claim innocence of high points. They abound in opera arias; as high notes, they are sites of
display, channels for the foregrounding of the very act of performing. As such,
they are thrilling to audiences, whose consumption of these arias may owe not a
little to the anticipated pleasure of experiencing these moments in different voices,
so to speak. The lied singer encounters them frequently, too, often in a more intimate setting in which they are negotiated with nuance. In orchestral music, high
points often provide some of the most memorable experiences for listeners, serving as points of focus or demarcation, places to indulge sheer visceral pleasure.
Indeed, the phenomenon is so basic, and yet so little studied by music theorists,
that one is inclined to think either that it resists explanation or that it raises no
62
PART I
Theory
31. The most comprehensive early study of high points is George Muns, Climax in Music (Ph.D. diss.,
University of North Carolina, 1955). Leonard Meyers Exploiting Limits introduces an important
distinction between statistical climaxes and syntactical ones. See also Agawu, Structural Highpoints in Schumanns Dichterliebe, Music Analysis 3(2) (1984): 159180. Most important among
more recent studies is Zohar Eitans Highpoints: A Study of Melodic Peaks (Philadelphia: University
of Pennsylvania Press, 1997), which may be read in conjunction with David Hurons review in
Music Perception 16(2) (1999): 257264.
CHAPTER 2
63
are many examples to support this theory, but there are counterexamples as well.
It would seem that the nineteenth century evinces a plural set of practices. Some
high points are syntactical while others are statistical.32
The basic model of the dynamic curve may, of course, be subject to variation.
A high point may occur earlier rather than later in the form. It may appear with
relatively little preparation and perhaps be followed by prolonged decline. It may
be known more in retrospect than in prospect; that is, while some high points
are clearly the culmination of explicit preparatory processes, others pass into consciousness only after the fact. These creative manipulations bespeak a simultaneous
interest in natural shapes and the artifice of artistic transformation.
Let us follow the achievement of high points in some well-known moments.
In Schuberts glorious An die Musik, the high point occurs toward the end of
the first strophe on a high F-sharp (Welt) in bar 16. The strophe itself is nearly
20 bars long, so the high point occurs closer to its end, not in the middle or at
the beginning. How does Schubert construct this moment as a turning point?
The structural means are simple, and the timing of their disposition is impeccable. From the beginning, Schubert maintains a relatively consistent distinction among three types of pitch configuration: arpeggio, stepwise diatonic, and
chromatic. If we think of these as modes of utterance, we see that they work in
tandem to create the high point in bar 16. First, the pianist offers the singer an
arpeggiated figuration (lh, bars 12). She accepts (bars 34) but only for a limited period; the imperatives of musical closure favor stepwise melodic motion
(bars 56). The pianist repeats his triadic offer (lh, bars 67) and, while the
singer responds, continues in stepwise mode (lh, bars 89). Meanwhile, the
singers response incorporates the single largest melodic leap in the entire song
(descending minor-seventh in bars 78). But this change of direction is merely
the product of an octave transference; if we rewrite Schuberts melody in these
bars (79) within a single octave, we see that the diatonic stepwise mode is what
regulates this second utterance. Now, the pianist presses forward in chromatic
mode (lh, bars 1011). This is not the first time that chromatic elements have
been used by the pianist (GA in lh bars 45 and AAB in lh bar 8), but
the utterance in bar 10 is more decisive and carries an aura of intensification.
Here, at the start of the singers third vocal phrase (bar 11), she does not respond
directly to what is offered by the pianist but is led by the momentum of her own
previous utterances. The mixture of arpeggiated and stepwise motion regulates
this phrase. Then, in the final sweep of the phrase (bar 14), the pianist gives full
rein to the chromatic mode, yielding only to an implicit triad at the conclusion
of the phrase (AD in lh bars 1819). The singers articulation of the high point
takes the form of an extended stepwise diatonic rise from A to F-sharp (bars
144163). Observe, however, the gap that Schubert introduces in the approach to
the climactic pitch: DF, not EF. The rhetorical effect of this gap of a third is
underlined by the local harmonic situation: a secondary dominant in 6/5 position
32. Meyer, Exploiting Limits. See also his later volume Style and Music: Theory, History, and Ideology
(Philadelphia: University of Pennsylvania Press, 1989).
64
PART I
Theory
Piano
hol - de
hat ein
Kunst,
Seuf
in
zer,
pp
Stun - den,
flos - sen,
Le - bens wil
hei - li - ger
Wo mich des
Ein s - er,
11
Hast du
Den Him
mein Herz
mel be
zu
rer
Hast
Du
mich
hol -
in ei - ne
de Kunst, ich
16
be
dan
re Welt
ke dir
en - trckt!
da - fr!
In ei - ne
Du hol - de
be - re Welt
Kunst, ich dan -
en - trckt!
ke dir!
21
1.
2.
supports the high F-sharp in bar 16. Then comes release in a configuration that
mixes stepwise with triadic motion (bars 1719). Note that the high point in bar
16 is not the only occurrence of that particular F-sharp in the song. We heard
it three bars earlier (bar 13), but without accentual or harmonic markedness.
CHAPTER 2
65
mf
simile
cresc.
15
(ff)
stretto
3
5
22
(dim.)
28
(pp)
66
PART I
Theory
The rhetorical shape of the first of Chopins preludes, op. 28, is perfection itself
(example 2.4). An 8-bar antecedent closes in a half-cadence. (The fact that the harmony in bar 8 is a dominant-seventh rather than a dominant inflects but does not
erase the sense of a half-cadence.) Then, Chopin begins a repetition of those 8 bars.
After the fourth, he intensifies the procedure. Melody now incorporates chromaticism, enlists the cooperation of the bass (parallel movement between bass and treble), adopts a stretto mode so as to intensify the sense of urgency in the moment,
and eventually culminates in a high point on DC (bar 21)the highest melodic
pitch in the prelude. From there, things are gradually brought to a close. The mel
ody returns from on high and approaches 1teasingly
at first, eventually attaining
rest in bar 29. The entire passage after the high point features a diminuendo, and
the last 10 bars sit on a tonic pedal, C. The expression is archetypically Romantic:
the means are clear but subtle, the rhetoric self-evident but never banal, the effect
touching, and there is no unmotivated lingering. To finish, Chopin reminds us that
there is more to come. The attainment of 1 in bar 29 did not do it; a terminal 3 (bar
34) leaves things suspended, adding a touch of poetry to the ending.
It seems likely that the high point in bar 21 shapes the experience of many players and listeners. Bar 21 is a turning point. The intensifying stretto effect is abandoned here; the consistently rising chromatic melody, doubled an octave below
(bars 1620), is overcome by a diatonic moment (bar 21); and the complementary
melodic descent from the high point is entirely diatonic. The only vestige of chromaticism is in the region of the high point (bar 22). The rest is white notes.
Chopin takes time to close. This is no routine deployment of conventional syn 6 and 3
2 which provided the essential
tax to close off a structure. The motifs 5
melodic opposition in bars 13 and 57, respectively, are briefly restored (bars
2526 and 2728) in a gesture laden with reminiscence. We reminisce as the end
nears. When the longed-for 1 finally appears in bar 29, it is cuddled by a fourfold
6/45/3 double suspension (bars 2932).
Chopins op. 28 collection as a whole is a rich site for the study of high points. In
no. 3 in G major, for example, the beginning of the end is marked not by a tensional
high point but by a turn to the subdominant (bars 1619), a reorientation of the
harmonic trajectory. The deeply expressive, minor-mode no. 4 is made up of two
large phrases, an antecedent (bars 112) and its consequent (bars 1325). The high
point occurs in the middle of the consequent (bars 1617), complete with Chopins
stretto marking, forte dynamic, and momentary contact with a low-lying Bthe
lowest note in the piece so far, to be superseded only in the final bar by an E. In no.
6 in B minor, the point of furthest remove is the Neapolitan region in bars 1214,
positioned about halfway through the work. This relatively early turning point is
followed by an especially prolonged period of closure (bars 1526). The little A
Major Prelude, no. 7, marks its high point by a secondary dominant to the supertonic (bar 12). Delivered in two symmetrical phrases (bars 18 and 916), the high
point forms part of the precadential material leading to the final cadence. In no. 9
in E major, an enharmonic reinterpretation of the mediant harmony (A-flat in bar
8) conveys the sense of a high point. In no. 13 in F-sharp major, an E-natural functioning as a flattened-seventh of the tonic chord (bar 29) signifies home-going and
serves as a critical turning point in the form. And in the dramatic Prelude no. 22
CHAPTER 2
67
in G Minor, a modified repeat of the opening, bass-led period (bars 18, 916)
is followed by a still more intense phrase promising closure (bars 1724) and its
immediate repetition (bars 2532). Finally, the cadential gesture of bars 3132 is
repeated as 3334 and overlapped with what appears to be another statement of the
opening theme. The bass gets stuck in bars 3638, however, and it needs the (divine)
intervention of an inverted augmented sixth chord in bar 40 to usher in the final
cadence. Chopins trajectory here is one of increasing intensity until a colossal or
even catastrophic event (bar 39) arrests the motion and closes the structure.33
In the Prelude to Tristan and Isolde, successive waves of motion culminate in
bar 83 with a chord containing the notes A-flat, E-flat, C-flat, and F. This moment
marks the decisive turning point in the prelude. What follows is a return to the
opening, a recapitulation of sorts that completes the larger tripartite shape. Volumes of commentary attest to the fact that this famous work can support a variety of analytical agendas. Our concern here is with the simplest and most direct
apprehension of the overall shape of the prelude. With bar 83 as anchor, we can
understand the preparatory tendencies manifest in the preceding 82 bars as well as
the complementary function of the succeeding 28 bars. Just as Schuberts An die
Musik and Chopins C Major Prelude, op. 28, no. 1, rose to a melodic high point
and resolved from there, so, on a grander scale, Wagners prelude rises in waves to
a high point and resolves from there.
The means are direct and ancient. Bar 83 is the loudest moment in the prelude.
The progress of the dynamics conspires to convey that fact. This bar is also one of
the densest. Earlier points, like bars 55 and 74, prepared this one, but the superlative effect here derives from its terminal position. After the explosion in bar 83,
nothing comparable happens in the prelude, whereas with the previous moments
of intensification, there was always the promise of more. Psychologically, bar 83
denies the possibility of a greater moment of intensity.
These features are on the surface of the surface and are immediately noticeable. But there are others. The chord in bar 83 is known to us from the very first
chord in the prelude, the Tristan chord itself (example 2.5). However one interprets it, its function as a (relative) dissonance within the opening 3-bar phrase is
uncontested. Of course, from a certain point of view, every one of the resulting
sonorities in bars 23 is a dissonance, but there is also a sense that the closing
dominant-seventh (bar 3) provides a measure of resolution, albeit a local and
provisional one. In other words, the Tristan chord marks a point of high tension
which is resolvedat least in partby the dominant-seventh chord. It is true, as
Boretz and others have reminded us, that the Tristan chord and the dominantseventh are equivalent within the systems of relation that assert inversional and
transpositional equivalence.34 But even if we devised a narrative that has the
33. For more on closure in the Chopin preludes, see Agawu, Concepts of Closure and Chopins op. 28,
Music Theory Spectrum 9 (1987): 117.
34. It now emerges, writes Benjamin Boretz, that the notoriously ambiguous Tristan chord, so elusive
or anomalous in most tonal explications of the piece, and the familiar dominant seventh, so crucial
to these same tonal explications, are here just exact, balanced, simple inverses of one another, with
very little local evidence to support their consideration as anything but equivalents in this sense.
See Boretz, Metavariations, Part 4: Analytic Fallout, Perspectives of New Music 11 (1973): 162.
68
PART I
Theory
Tristan chord progressing to another version of itself in bars 23, the actual
path of the progression would be understood in terms of an expressive trajectory that confers a sense of lesser tension on an element by virtue of its terminal
position.
Example 2.5. Wagner, Prelude to Tristan and Isolde, bars 13.
Langsam und schmachtend
pp
The high point in bar 83 therefore reproduces a sound that has been part
of the vocabulary of the work from the beginning. In its local context, however, the chord has a precise harmonic function: it is a half-diminished-seventh
chord on the supertonic in the local key of E-flat minor. The main key of the
prelude is A minor (with an intervening major inflection and excursions to
other keys). E-flat minor is at a significant distance from A. Heard in terms of
the prescribed distances that regulate a construct such as the circle of fifths,
E-flat, prepared mainly by its dominant, B-flat, is the point of greatest harmonic
remove from A. The preludes high point is thus, among other processes noted
earlier, a product of subsurface activity that exploits the conventional property
of harmonic distance.35
Such coincidence between expressive and structural domains is the exception rather than the rule when it comes to the articulation of high points. Subsurface activity, confined by an explicit system of theoretical relations, has to
be domesticated in particular ways in order to do expressive work. Often the
rhythm of the system of relations has little or nothing to do with the works
unfolding rhythm, even at a macro level. Systems are based on atemporal logical relations, while works unfold temporally in simulation of organic life. And
this circumstance may encourage some listeners to doubt the pertinence of the
coincidence we have just identified in the Tristan Prelude, whereby the Tristan
chord and the dominant-seventh chord are held to be equivalent. Another way
of putting this is to say that structural procedures are up for expressive grabs.
One who wishes to argue a difference between bar 2 and bar 83 will point
to differences of notation and destination; one who wishes to argue a sameness will invoke enharmonic synonymity. To admit this openness in interpretation is not to suggest any kind of hopelessness in the analytical endeavor.
35. For a complementary view of the Tristan Prelude, see Robert P. Morgans demonstration that the
formal process consists of repeating units and processes of variation (a semiological reading, in
effect): Circular Form in the Tristan Prelude, Journal of the American Musicological Society 53
(2000): 69103.
CHAPTER 2
69
Example 2.6. Ten-note chord in Mahler, Tenth Symphony, first movement, bar 204.
36. David Lewin broaches this topic in the course of a discussion of two competing Schenkerian readings of the familiar Christmas hymn Joy to the World, set to a tune by Handel, in Music Theory,
Phenomenology, and Modes of Perception, in Lewin, Studies in Music with Text (Oxford: Oxford
University Press, 2006), 8588. One reading renders the tune as an 8 line ( Joy to the world), the
other as a 5 line (Joy to the world). Although Lewin recognizes that the Schenkerian reading does
not claim that the world is more important than joy, he nevertheless proceeds to explore the
metaphorical prospects for either reading. But since the Kopfton as imagined and postulated by
Schenker belongs to a sequence of idealized voices, not necessarily a flesh-and-blood occurrence,
its salience at the foreground (by means of accentual or durational prominence, for example) is not
a defining feature. Thus, to seek to interpret idealized voices hermeneutically is to seek to transfer
values across a systemic border. In our terms, it is to confuse the rhythm of the system with the
actual rhythm of the work.
70
PART I
Theory
hear first an A-flat minor chord (bar 194), then the 10-note chord on C-sharp
(204), whose resolution is delayed until the second half of bar 220. If we read
the A-flat minor chord enharmonically as G-sharp minor, we might hear the
entire passage as a iiVI cadence writ large. This conventional underpinning occurs elsewhere in Mahler (see, for example, the excerpt from Das Lied
von der Erde analyzed later in this book in example 4.34) and reinforces the
grounding of his musical language in the harmonic norms of the eighteenth
century. But the composing out of this progression incorporates numerous
modifications that ultimately take the sound out of an eighteenth-century
environment and place it squarely within a late nineteenth- or early twentiethcentury material realm.
From the point of view of harmonic syntax, the 10-note chord functions as a
dominant on account of its C-sharp grounding. Above it are two dominant-ninth
chords, one a minor ninth, the other a major ninth, on C-sharp and F-natural,
respectively. In other words, the 10-note chord combines the dominant-ninths of
the keys of F-sharp and B-flat. Since these are the two principal keys of the movement, the combination of their expanded dominants at this moment would be a
logical compositional move. Perceiving the separate dominants presents its own
challenges, of course, but the conceptual explanation probably presents no comparable difficulties. As in the Tristan Prelude, a combination of structural and expressive features marks this high point for consciousness.
The aftermath of the high point in the Mahler movement is worth noting
because of the way closurewhich typically follows the high pointis executed
(bars 213end). The charged dominant-functioning chord on C-sharp has set up
an expectation for resolution, which could have come as early as bar 214, allowing
for the 4-bar lead-in (209212) to the thematic return in 213. Mahler maintains
the C-sharp pedal for the first phase of this return (213216). With the tempo and
thematic change at 217, the pitch C-sharp persists, but is now incorporated in very
local VI progressions. It is not until the end of bar 220 that the proper resolution
occurs in the form of an authentic cadence featuring 3 in the top voice. This understated close cannot, it seems, provide the rhetorical weight needed to counter the
effect of the gigantic 10-note dominant, so a network of closing gestures, some of
them harmonic (bars 229230), others more melodic (bars 240243), is dispersed
throughout the closing bars of the movement. Cadential gestures, reminiscences
in the form of fragments, and strategically incomplete melodic utterances transfigure Mahlers ending. (This movement, incidentally, was the most complete in draft
form of all of the movements of the unfinished Tenth.)37
Talk of high points, then, dovetails into talk of closure, for it would seem
that the logical thing after the attainment of a high point is to engineer a close.
And this reinforces the point made earlier that, although the six criteria being
developed in this chapter and in chapter 3 have been chosen in order to focus
attention on specific features and mechanisms, they are not wholly autonomous.
37. For further discussion, see Agawu, Tonal Strategy in the First Movement of Mahlers Tenth Symphony, 19th-Century Music 9(2) (1986): 222233.
CHAPTER 2
71
72
PART I
Theory
[missing]
pp
mp f
ff
fff
mf
pp
Example 2.8. Closing bars of Bartk, Music for Strings, Percussion and Celesta, first
movement.
Vn 1
Vn 2
CHAPTER 2
73
In any case, we must not draw too categorical a distinction between hearing
Romantic music as language and hearing post-Romantic music as system or even
antisystem. Tempting as it is to interpret one as natural and the other as artificial,
or one as intuitionist, the other as constructivist, we might consider the more
likely reality to involve a blurring of boundaries, an interpenetration of the two
modes. Any such comparisons have to be validated analytically. In the brief examples that we have seen, the hierarchic subsumption of scale steps in Wagner and
Mahler contrasts with the contextual centricity of Bartk. But Bartk, too, employs
some of the same secondary parameters used by earlier composers.
The high point, then, is a central feature of Romantic foregrounds and belongs
in any taxonomy of criteria for analysis. Context is everything in analysis, so one
should always look to it for clarification of ambiguous situations. As a quality, the
high point embodies a sense of the supreme, extreme, exaggerated, and superlative,
and these qualities are often distributed across several of a works dimensions. My
comments on passages from Schubert, Chopin, Mahler, Wagner, and Bartk will,
I hope, have confirmed the view that some attention to these ostensibly surface
features might enhance our appreciation of the particularities of Romantic music.
C HA P T E R
Three
Criteria for Analysis II
Periodicity
A period is a regulating framework for organizing musical content. Every largescale musical utterance needs to be broken down into smaller chunks in order to
assure communication and comprehensibility. Like sentences, phrases, or paragraphs in verbal composition, periods serve as midlevel building blocks, markers
of a compositions sense units. Does the subject speak in short or long sentences?
How does the succession of periods define an overall form or structural rhythm
for the work? Are periodic rhythms interchangeable or are they fixed?
The enduring tradition of Formenlehre has devised elaborate sets of terms,
concepts, and modes of symbolic representation for the description of this vital
aspect of music. Some offer general theories of formal organization, some illuminate specific historical styles, some prescribe actions for composition, while others offer models for analytic description. Taxonomies abound in theoretical and
analytical writings by Burmeister, Koch, A. B. Marx, Riemann, Schoenberg, Tovey,
Ratner, Rosen, Rothstein, Caplin, and Hepokoski and Darcyto mention only a
dozen names. The very large number of writings on this topic suggests that, for
many scholars, form as a specifically temporal or periodic experience lies at the
core of musical understanding and enjoyment.
A rapid overview of some of the terms and concepts employed by a few leading theorists to describe the temporal aspects of musical structure will provide
an indication of the range of techniques and effects that originate in notions of
periodicity. According to Ratner, periodicity represents the tendency . . . to move
toward goals, toward points of punctuation. . . . [A] passage is not sensed as being a
period until some sort of conclusive cadence is reached. . . . The length of a period
cannot be prescribed. Among the terms he employs are motion, points of arrival,
symmetry (including disturbances of symmetry), sentence structure, period
extensions, and internal digressions.1 Like Ratner, William Rothstein draws on
1. Ratner, Classic Music, 33.
75
76
PART I
Theory
contemporaneous and more recent theories in his study of eighteenth- and nineteenth-century phrase rhythm. His terms include phrase (including fore-phrase
and after-phrase), phrase rhythm, phrase linkage, phrase expansion, prefix, suffix,
parenthetical insertion, hypermeasure, lead-in, elongated upbeat, and successive
downbeats.2 Caplins theory of form draws on various kinds of cadence (abandoned, authentic, elided, evaded); cadential progression; concluding, initiating,
and medial functions; period; interpolation; and sentence.3 And Christopher
Hastys vocabulary is chosen to capture the temporal aspects of musical experience and to distinguish diverse temporalities: motion, projective process, deferral,
now, instant, timelessness, and denial.4
Every listener to Romantic music possesses an intuitive understanding of periodicity. When we hear a Chopin prelude, a Liszt song, a Brahms intermezzo, a
Bruckner motet, or a Verdi aria, we are aware of its ebbs and flows, its high and low
points, its moments of repose and dynamism. We routinely sense that a thought
has been concluded here, that a process begun earlier has been abandoned, or
that an event of a certain gravity is about to take place. Listeners who also move
(silently) to music and dancers who respond physically are alert to regularities and
irregularities in phrasing and groupings beyond the beat level. Schubert proceeds
in measured groupings throughout the C Major Quintet, but disrupts the periodicity from time to time, deploying unison passages to move the discourse self-consciously from one state of lyric poetry to another. Schumanns Piano Quintet, op.
44, does not disappoint when it comes to 4-bar phrases, but we are aware, too, of
the speech mode that intrudes here and there and projects an alternative periodicity; sometimes, we sense a cranking of gearsas if to break an ongoing periodicity
in order to introduce a new one. And in Mendelssohns Violin Concerto, the manner of delivery is controlled by 4-bar units. This partly facilitates exchange between
(the more restricted) orchestral discourse, on the one hand, and (the freer) soloists
narrative, on the other. It also contributes to the more or less immediate comprehensibility of the message in a genre whose unabashed suasive intent generally
leaves few aspects of outer form to the connoisseurs imagination.
The most important consideration for analysis is the sense of periodicity, by
which I mean the tendency of the sonic material to imply continuation and to
attain a degree of closure. To get at this quality, I will ask the same three questions that were introduced at the end of chapter 1: Where does the motion begin?
Where does it end? How does it get there? These questions are meant to help channel our intuitions about the shape of the compositional dynamic and to guide the
construction of periodicity.
One final, general point needs to be made before we begin the analyses.
Although the large literature dealing with form, rhythm, and periodicity in tonal
music has made available a wealth of insights, one aspect of the literature suggests that we might think a little differently. Too many studies of Romantic music
2. William Rothstein, Phrase Rhythm in Tonal Music (New York: Schirmer, 1989).
3. Caplin, Classical Form.
4. Christopher Hasty, Meter as Rhythm (New York: Oxford University Press, 1997).
CHAPTER 3
77
78
PART I
Theory
The stepwise melody played by second violins starting in the second half of bar
23 leads so directly to the new beginning initiated in bar 25 that one is inclined to
hear an elision of phrases. Bar 24, analogous to bar 16 in one hearing, suggests a
Example 3.1. Mahler, Symphony no. 4, third movement, bars 161.
Ruhevoll (poco adagio)
12
18
16
23
30
27
37
(continued)
CHAPTER 3
79
44
41
51
48
54
58
80
PART I
Theory
(bar 29) onward. Mahler pulls all the usual stops available to the Romantic composera high register that we know to be unsustainable, a rounding-up circle-offifths harmonic progression (EAD[and, eventually]G), chromatic inflection,
and perhaps most significant, arrival on a dominant-functioning 6/4 chord in bar
31, an archetypal sign of impending closure. The sense of dominant will extend
through bars 31 to 36, conferring on the entire 2536 phrase a concluding function. In colloquial terms, it is as if we began the movement singing a song that
we did not finish (116), repeated it in an intensified version without attaining
closure (1724), and then sang it in an even more intensified version, reaching a
longed-for cadence on this third attempt (2537). These qualities of intensification
and repetition reside in the domain of periodicity; we might even say that they
embrace the whole of the music.
Bar 37 marks the onset of yet another beginning in the movementthe fourth,
in the larger scheme of things. The by-now-familiar pizzicato bass (that Schubert
played on the piano to accompany his singer in Wo ist Sylvia?) is heard, and it
recalls the three previous beginnings at 1, 17, and 25, only now doubled an octave
lower. The uppermost melody is now tinged with a sense of resignation, dwarfed
in its ambitions by the melodic achievements of the previous period. By now, we
are beginning to sense a circularity in the overall process. Perhaps the formal
mode here is one of variation. This fourth period, however, is soon led to a decisive
cadence in bars 4445, and the attainment of the cadence is confirmed by a conventional IIVVI progression, complete with a tonicization of IV (bars 4647).
The fact that the music beginning in bar 37 showed no ambitions initially and then
moved to enact a broad and decisive cadence confers on this fourth period a sense
of closing, a codetta-like function, perhaps. After the cadence in bars 3637, we
might have sensed a new, strong beginning. But the simulated strength was shortlived, and the cumulative pressure of closure held sway, hence the big cadence in
bars 4445.
The relative strength of the cadence in bars 4445 sets the character of the
joins between phrases into relief. Every time we locate a musical process as beginning in a certain measure, we are in danger of lying, or at least of undercomplicating a complex situation. Attending to periodicity and the tendency of the material
is a useful way of reminding ourselves of how fluid are phrase boundaries and
how limited are conventional means of analytic representation. Consider the succession in bars 1617. The approach to bar 16 tells the listener that we are about
to make a half-cadence. Indeed, Mahler writes an apostrophe into the score at this
point, registering the separateness of the moment and the musical thought that
it concludes. There is therefore, strictly speaking, no cadential (VI) progression
between bars 16 and 17. Moreover, bar 17 is marked by other signs of beginning (entrance of a new melody, return of the old melody slightly decorated)
thus encouraging us to hear 16 as concluding a processalbeit an incomplete
one. The join at bars 2425, too, is illusory. Here, too, we should, strictly speaking,
not imagine an authentic cadence because the approach to 24 effects the manner
of a conclusion of an incomplete thought, a conclusion prepared by a passionate melodic outburst. What complicates this second join is the rather deliber-
CHAPTER 3
81
ate physical movement led by the dueting voices, second violin and cello. In a
more nuanced representation, we might say that the 2425 join conveys a greater
dependency than the 1617 join, but that neither join approximates a proper
cadence.
The third main join in the movement is at 3637. Here, the sense of cadence
is harder to ignore. I mentioned the big dominant arrival in 31, which harmonic
degree is extended through 36, finding resolution at the beginning of 37. Thus,
while bars 116 and 1724 each end with a half-cadence, bars 2537 conclude
with a full cadence. Notice, however, that the join in 3637 is undermined by the
return of our pizzicato bass, by now a recognizable signifier of beginnings. We
might thus speak of a phrase elision, whereby 37 doubles as the end of the previous
phrase and the beginning of another.
From bar 37 on, the business of closing is given especial prominence. If the
cadence in bars 3637 is authentic but perhaps weakly articulated because of the
phrase elision, the next cadence in bars 4445 is a stronger authentic cadence.
whereas that in
The melodic tendency in bars 4344 sets up a strong desire for 1,
3637, passing as it does from 5 through 4 to 3, forgoes the desire for 1 . In addition,
the precadential subdominant chord in bar 43 strengthens the sense of cadence in
bars 4445. Working against this, however, is the new melody sung by bassoons
and violas beginning in bar 45, which Mahler took over from an earlier symphony.
Again, the elision weakens the cadence and promotes continuity, but not to the
same extent as happened in bars 3637. The intertextual gesture also underlines
the discontinuity between bars 44 and 45.
The next punctuation is the authentic cadence at bars 5051. Some listeners
will hear the pizzicato bass notesreinforced, this time, by harpnot only as a
sign of beginning, as we have come to expect, but, more important, as a sign of
endingthe poetic effect that Brahms, among other composers, uses to signal
ultimate home-going. Since the close in 5051 comes only 7 bars after the one in
4445, our sense that we are in the region of a global close is strengthened. Indeed,
from bar 51 onward, the musical utterance gives priority to elements of closure.
Launching this last closing attempt are bars 5154. Then, bars 5556 make a first
2 melodic progression harmoattempt at closure, complete with an archetypal 3
nized conventionally as IV7 (V7 is literally expressed by V4/2 but the underlying
sense is of V7). A second attempt is made in 5758, also progressing from IV. The
third attempt in 5961 remains trapped on I. It is then stripped of its contents,
reduced to a single pitch class, B, which in turn serves as 5 in the E-minor section
that follows in bar 62.
With the benefit of hindsight, we may summarize the segments or units that
articulate a feeling of periodicity as follows:
116
1724
2537
3745
4551
16 bars
8 bars
13 bars
9 bars
7 bars
5154
5556
5758
5961
4 bars
2 bars
2 bars
3 bars
82
PART I
Theory
That some segments are relatively short (2, 3, or 4 bars) while others are long (8, 9,
13, or 16 bars) may lead some readers to suspect that there has been a confusion
of levels in this reckoning of periodicity. But the heterogeneity in segment length
is a critical attribute of the idea of periodicity being developed here. Periods must
be understood not as fixed or recurring durational units but as constellations that
promote a feeling of closing. If it takes 16 bars to articulate a sense of completion,
we will speak of a 16-bar period. If, on the other hand, it takes only 2 bars to convey the same sense, we will speak of a 2-bar period. Periodicity in this understanding is similar to the function of periods in prose composition; it is intimately tied
to the tendency of the musical material. It is not necessarily based on an external
regulating scheme. Of course, such schemes may coincide with the shapes produced by the inner form, but they need not do so and often do not. The listener
who attends to the specific labor of closing undertaken by individual segments of a
work attends to more of the overall sense of the music than the listener who defers
to the almost automatic impulse of a regulating phrase-structural scheme.
Finally, it is evident that talk of periodicity is implicitly talk of some of the
other features that I am developing in this and the previous chapter. The idea of
beginnings, middles, and endings is germane to the experience of periodicity.
Similarly, high points mark turning points within the form and are likely to convey
the periodic sense of a work.
Schubert, Im Dorfe
Periodicity in song is a complex, emergent quality. The amalgamation of words
and music expands the constituent parameters of a work. The poem comes with its
own periods, its own sense units, and when words are set to music, they develop
different or additional periodic articulations based on their incorporation into a
musical genre. And if it is to remain coherent within the constraints of its own
language, the music must be subject to certain rules of well-formedness. It must, in
other words, work at the dual levels of langue and parole, that is, conform simultaneously to the synchronic state of early nineteenth-century tonal language and to
the peculiarities, mannerisms, and strategies of the composer.
The harmonic trajectory of Schuberts Im Dorfe from his Winterreise cycle
exemplifies such well-formedness. An atmospheric night song, Im Dorfe exemplifies a mode of periodicity based on the statement and elaboration of a simple, closed
harmonic progression. I will have more to say about harmonic models and processes
of generation in coming chapters. Here, I simply want to show how simple transformations of an ordinary progression confer a certain periodicity on the song.5
CHAPTER 3
83
Example 3.2 shows the nine periods of Im Dorfe in the form of chorale-like
harmonic summaries. Ordered chronologically, the periods are as follows:
Period 1
Period 2
Period 3
Period 4
Period 5
bars 18
bars 819
bars 2021
bars 2223
bars 2325
Period 6
Period 7
Period 8
Period 9
bars 2628
bars 2931
bars 3140
bars 4049
84
PART I
Theory
becomes
becomes
truncated to
becomes
or
becomes
bars 3140 (period 8). Expansion of this model begins in bar 36, where the 6/4
is minor rather than major, which then opens up the area around B-flat. B-flat
later supports an augmented-sixth chord that prepares the elaborate hymn-like
cadence of bars 3840. (The similarity between the chorale texture of Schuberts
CHAPTER 3
85
music in these bars and the chorale texture employed in the demonstration of our
harmonic models may provide some justificationif such were neededfor the
exercise represented in example 3.2.) This model is now repeated as period 9 in
bars 4049, with bars 4649 functioning simply as an extension of tonic. In short,
the A' section consists of two longer periods, 8 and 9.
If the sense units of Schuberts Im Dorfe as described here are persuasive, we
can appreciate one aspect of Schuberts craft. In responding to the mimetic and
declamatory opportunities presented by a verbal text, he retains a secure harmonic
vision distributed into nine periods of varying length. Longer periods occur in the
outer sections while shorter ones occur in the more fragmented middle section.
The periodicity story is, of course, only one of several that might be told about the
song, but the strength of Schuberts harmonic articulation may encourage us to
privilege this domain in constructing a more comprehensive account of the songs
overall dynamic.
86
PART I
Theory
4 bars comprise period 1, and this may also be taken as the model for harmonic
motion in the song. Beginning on the tonic, period 1 outlines the subdominant
area, incorporates mixture at the beginning of bar 3 (by means of the note
A-flat), and then closes with a perfect cadence. The second period is twice as
long (bars 412), but it covers the same ground, so to speak. That is, the bass line
descends by step, filling in the gaps left in the model (period 1). And the bass
approaches the final tonic also by step, including a chromatic step. Bars 412 are
therefore a recomposition of 14.
Example 3.3. Periodic structure of Schumanns Ich grolle nicht, from Dichterliebe.
Period 1
(bars 1-4)
6
7
B
4
3
4
3
4
3
G
#
G
#
4
3
4
3
8 - 9 6 - 7 4
Period 2
(bars 4-12)
H
4
3
4
3
7
6
6
5
4
3
7
B
6
#
6
5
7
B
8-7
6-5
Period 3
(bars 12-19)
Period 4
(bars 19-22)
6
7
B
4
3
Period 5
(bars 22-30)
H
4
3
Period 6
(bars 30-36)
4
3
(
6
4
8
6 - 5
4 - 3
The next period, period 3, occupies bars 1219, overlapping with periods on
either side. Here, the IIV6 motion from the beginning of period 1 is expanded
by the incorporation of the dominant of vi, so that instead of IIV6, we have IV/
vivi. And the close of the period, bars 1619, uses the same bass progression as
that at the end of the previous period (912; the notes are GAABC). Given
these affinities, we can say that this third period is a recomposition of the second,
itself an expansion and reconfiguring of the first. Note that periods 2 and 3 are
of roughly the same length in bars, while period 1, the model, is about half their
length. In other words, periods 2 and 3 are (temporally) closer than 2 and 1 or, for
that matter, 3 and 1. Again, the feeling of periodicity is conveyed by punctuation
(including its absence), not by phrase length in bars.
Period 4 is identical to period 1. Period 5 begins and continues in the manner of period 2 but closes with a decisive cadence in bars 2830. This is exactly
the same cadence that concluded periods 1 and 4. Thus, the idea that period 5
recomposes period 4 is enhanced. Thematically speaking, period 5 is a recomposition of period 2, but it incorporates the cadence pattern of periods 1 and 4. Since
CHAPTER 3
87
Stravinsky, The Rakes Progress, act 1, scene 3, Annes aria, Quietly, night
When the intrinsic tendencies of dominant- and diminished-seventh sonorities
no longer form the basis of a composers idiolect, periodicity has to be sought in
other realms. Sometimes, it is conferred in retrospect rather than in prospect, the
88
Theory
PART I
Qui
rt
night,
al - though it be un - kind,
though I weep,
et - ly
al - though I
Guide
me
grief
or shame;
weep,al
o moon,
It
find
Nor
him
and
may
its
- though I weep, it
chaste - ly
can
ca - ress, And
beat
con- fess
Al -
not, can -
not
be
thou a -
How are the two strophes enacted? We begin with a 1-bar orchestral vamp,
then Anne sings her phrases in 2-bar segments. The phrase Although I weep bears
the climactic moment. Stravinsky allows Anne a rest before intoning the F-sharp
in bar 12 to begin this intensified expression. Twice she sings the phrase, ending,
first, with a question mark (bar 15) and, on the second try, with a period (bar 18).
The second try continues the verbal phrase to the end, Although I weep, it knows
CHAPTER 3
89
of loneliness. The close on B minor in bar 18 recalls the opening and, in the more
recent context, answers directly to the dominant of bar 15. Anne also manages
2
1 melodic motion on the second and
to incorporate a tiny but significant 3
third syllables of loneliness. Woodwinds immediately echo the second of Annes
climactic phrases in part as remembrance and in part as a practical interlude (or
time out for the singer) between two strophes.
The listeners ability to form a synoptic impression of this first period (bars
120) is made challenging by the additive phrase construction. There is no underlying periodic framework except that which is conveyed by the pulsation. But pulsation is only the potential for periodicity, not periodicity itself. It is Annes two
climactic phrases that gather the strands together and compel a feeling of closure.
Here, it is difficult to predict the size of individual periods. We simply have to wait
for Stravinsky to say what he wants to say and how.
Guide me, O moon begins the second strophe to the melody of Quietly,
night. For 4 bars, strophe 2 proceeds as an exact repetition of strophe 1, but at the
words And warmly be the same, Stravinsky takes up the material of the climactic phrase Although I weep. The effect is of compression: the preparatory processes in bars 52121 are cut out, bringing the climactic phrase in early. The reason
for this premature entrance in bar 24 is that the climactic region is about to be
expanded. Anne now intensifies her expression by affecting a coloratura manner
on her way to the high point of the aria, the note B-natural lasting a full bar and
a half (bars 3031) and extended further by means of a fermata. This duration is
entirely without precedent in the aria. Indeed, the string of superlatives that mark
this momentincluding the withdrawal of the orchestra at the end of the note so
that the timbre of Annes voice does not compete with any other timbreis such
that little can or need be said in the aftermath of the high point. Anne simply
speaks her last line (A colder moon upon a colder heart) in a jagged, recitativelike melody that spans two octaves from the high B of the climax to the B adjacent
to middle C. The orchestra comments perfunctorily, without commitment.
Two aspects of the periodicity of Annes aria may be highlighted here. First,
the apparent two-stanza division that enabled us to speak of two large periods is,
as previously noted, somewhat limited. The second period (starting in bar 21) is
not merely a repeat of the first, although it begins like it and goes over some of
its ground; it is rather a continuation and intensification of it. We might speak
legitimately here, too, of a Romantic narrative curve beginning at a modest level,
rising to a climax, and then rapidly drawing to a close. A second aspect concerns
the modes of utterance employed by Anne. These modes reflect greater or lesser
fidelity to the sound of sung language. If we locate three moments in the vocal
trajectory, we see that Anne begins in speech mode or perhaps arioso mode (bars
23), reaches song mode at Although I weep, and then exceeds song mode at the
words It cannot, cannot be thou art. The latter is an extravagant vocal gesture
that, while singable, begins to approximate instrumental melody. This moment of
transcendence is followed by withdrawal into speech modea strictly syllabic,
unmelodic rendering of A colder moon upon a colder heart, finishing with a
literal, speech-like muttering of a colder heart on four B-naturals with durations
that approximate intoned speech. In sum, Anne begins in speech mode, reaches
90
Theory
PART I
song mode, then a heightened form of song mode, before collapsing into speech
mode. Again, according to this account of modes of utterance, the periodic sense
cuts across the aria as a whole, forming one large, indivisible gesture.
pp
1
p dolce
Piano
poco rall.
a tempo
poco rall.
a tempo
espr.
3
mp
12
dim.
dim.
pp
(attacca)
Bartk uses a Hungarian folk song that he had collected in 1907 as the basis
for this written-down improvisation. The compositional conception, therefore, is
from song to instrumental music. The idea in the First Improvisationas indeed
in several of the othersis to preserve the folk source, not to transform it. The
melody is 4 bars long, and Bartk presents it three times in direct succession and
then appends a 4-bar codetta. The first presentation borrows the opening majorsecond dyad from the melody (FE) and uses it at two different pitch levels to
CHAPTER 3
91
accompany the song. The pitch material of the accompaniment, although sparse,
is wholly derived from the melody itself. In terms of periodicity, these first 4 bars
retain the intrinsic periodicity of the melody itself. One aspect of that periodicity is evident in the rhythmic pattern: bars 13 have the same pattern while bar
4 relinquishes the dotted note and the following eighth-note. In the tonal realm,
bar 1 presents an idea, bar 2 questions that idea by reversing the direction of the
utterance, bar 3 fuses elements of bars 1 and 2 in the manner of a compromise as
well as a turning point, and bar 4 confers closure by incorporating the subtonic
(B-flat). These 4 bars promote such a strong sense of coherence and completeness
that they may be said to leave little room for further expectations; they carry no
implications and produce no desires. Whatever follows simply follows; it is not
necessitated by what preceded it.
The second statement of the melody (bars 58) replaces the dyads of the first
statement with triads. Triadic succession, though, is organum-like or, perhaps,
Debussy-like, insofar as the triads move in parallel with no obvious functional
purpose. In other words, the melody merely reproduces itself in triadic vein. Thus,
the trajectory of the original melody remains the determinant of the periodic
sense of these second 4 bars. By merely duplicating the melody, this second 4-bar
period is figured as simpler and more consonant than the first; it incorporates
no contrapuntal motion. As before, no internal expectations are generated by the
triadic rendition of the Hungarian folk song. Formal expectations will, however,
begin to emerge from the juxtaposition of two statements of the folk song. We may
well suspect that we will be hearing it in different environments.
The third statement (bars 912) turns out to be the most elaborate. Beginning
each of the first 3 bars with a D-minor triad, the second half uses what may well
come across as nontonal sonorities.7 The melody, now doubled, is placed where it
should be, namely, in the upper register (this contrasts with the first two appearances of the folk song). This third occurrence marks the expressive high point
of the improvisation, not only because Bartk marks it espressivo but because of
the thicker texture, the more intense harmonies, the more salient projection of the
melody, and the full realization of a melody-accompaniment relationship.
This climactic region (bars 912) is alsoand more obviouslyknown in
retrospect. The last 4 bars of the improvisation do not begin by stating the folk
melody as before. Rather, the first of them (bar 13) echoes the last bar of the
folk melody in a middlethat is to say, unmarkedregister; then the next three
present an intervallically augmented version of the same last bar, modifying the
pitches but retaining the contour. The harmony supporting this melodic manipulation in the last 4 bars is perhaps the most telling in conveying a sense of closure.
A succession of descending triads on E-flat minor, D minor, and D-flat minor
seems destined for a concluding C major, but this last is strategically withheld and
represented by a lone C, middle C. Bars 1316 may be heard as a recomposition of
7. Paul Wilson finds instances of pitch-class sets 418 and 516 in this 4-bar period, thus acknowledging the nontriadic nature of the sonorities. See Wilson, Concepts of Prolongation and Bartks opus
20, Music Theory Spectrum 6 (1984): 81.
92
PART I
Theory
bar 8one difference being that the missing steps are filled inand, more broadly,
as a reference to the entire second statement of the folk melody in bars 58.
The feel of periodicity in this improvisation is somewhat more complex. Selfcontained are the first three 4-bar phrases, so they may be understood from a
harmonic, melodic, and phrase-structural point of view as autonomous, as small
worlds in succession. The last 4-bar phrase carries a closing burden: it embodies
a conventional gesture of closureecho what you have heard, slow things down,
and let every listener know that the end is nigh. Indeed, to call it a 4-bar phrase
is to mislead slightly because there are no internal or syntactical necessities to
articulate the 4-bar-ness. The number 4 depicts a default grouping, not a genuine
syntactical unit. (The recomposition in example 3.6 compresses Bartks 4 bars to
2, but their periodic effect is not really different from the original.) By eschewing the dependencies of common-practice harmony, without however dispensing
with gestures of intensification and closure, the compositional palette in this work
becomes diversified. This is not to say that common-practice repertoires are lacking this potential autonomization of parameters. It is rather to draw attention to
their more obvious constructive role in Bartks language.
Example 3.6. Recomposed ending of Bartk, Improvisations for Piano, op. 20, no. 1.
Bartk's original
dim.
pp
(attacca)
Bartk's recomposed
dim.
The foregoing discussion of periodicity should by now have made clear that
periodicity is a complex, broadly distributed quality that does not lie in one parameter. It is an emergent, summarizing feel that enables us to say that something
begun earlier is now over or about to be concluded. Talk of periodicity therefore
necessarily involves us in talk about some of the other criteria for analysis that I
have been developing in chapter 2 and the present chapter. Like form, the notion
of periodicity embraces the whole of music. Focusing on punctuation and closure
and their attendant techniques helps to draw attention to this larger, emergent
CHAPTER 3
93
8. But see Hattens Interpreting Musical Gestures, Topics, and Tropes, 267286.
94
PART I
Theory
Carolyn Abbate describes the onset of the so-called Gesang theme as an interruption
. . . a radically different musical gesture. For her, this moment marks a deep sonic
break; indeed, cracks fissure the music at the entry of the Gesang. 9 These characterizations ring true at an immediate level. This otherworldly moment is clearly
marked and maximally contrasted with what comes before. Difference embodies
discontinuity. Note, however, that this characterization works in part because it
refuses technical designation. If, instead of responding to the aura of the moment,
we seek to understand, say, the motivic logic or the nature of succession in the
realms of harmony, voice leading, or even texture, the moment will seem less radically discontinuous and more equivocal. For one thing, in the bars preceding the
onset of the Gesang theme, a triplet figure introduced in the bass continues past
the ostensible break and confers an element of motivic continuity. Attending to the
voice leading in the bass, too, leads one to a conjunct descent, CCB, the ostensible crack occurring on C-flat. On the other hand, texture and timbre are different,
as are dynamics and the overall affect. Thus, while the action in the primary parameters presents a case for continuity, the action in the secondary parameters presents
a case for discontinuity. Recognizing such conflicting tendencies by crediting the
potential for individual parameters to embody continuity or discontinuity may help
to establish a more secure set of rules for analysis. My task here, however, is a more
modest one: to cite and describe a few instances of discontinuity as an invitation to
students to reflect on its explanatory potential.
Looking back at the classical style as point of reference, we can readily recall
moments in which discontinuity works on certain levels of structure. A good
example is the first movement of Mozarts D Major Sonata, K. 284, which I mentioned in the previous chapter on account of its active topical surface. A change
of figure occurs every 2 bars or so, and listeners drawn to this aspect of Mozart
are more likely to infer difference, contrast, and discontinuity than smooth continuity. Indeed, as many topical analyses reveal and as was implied in discussions
of character in the eighteenth century, the dramatic surface of classic music
sometimes features a rapid succession of frames. There is temporal succession,
but not progression. Things follow each other, but they are not continuous with
each other.
Think also of the legendary contrasts, fissures, and discontinuities often heard
in the late music of Beethoven. In the Heiliger Dankgesang of op. 132, for example, a slow hymn in the Lydian mode alternates with a Baroque-style dance in 3/8,
setting up discontinuity as the premise and procedure for the movement. The very
first page of the first movement of the same quartet is even more marked by items
of textural discontinuity. An alla breve texture in learned style enveloped in an
aura of fantasy is followedinterrupted, some would sayby an outburst in the
form of a cadenza, then a sighing march tune in the cello, then a bit of the sensitive
9. Abbate, Unsung Voices, 150151. See Agawu, Does Music Theory Need Musicology? Current Musicology 53 (1993): 8998, for the context of the remarks that follow. A discussion of discontinuity in
Beethoven can also be found in Lawrence Kramer, Music as Cultural Practice (Berkeley: University
of California Press, 1990), 190203 and in Barbara Barry, In Beethovens Clockshop: Discontinuity
in the Opus 18 Quartets, Musical Quarterly 88 (2005): 320337.
CHAPTER 3
95
96
PART I
Theory
(
Strahlt
Lie - be,
dein
Stern!
)
Dir,
they are syntactically dispensable. Both the opening and closing of a parenthesis
enact a discontinuity with the events that precede and follow, respectively. In the
harmonic realm, for example, a parenthesis may introduce a delay in the approach
to a goal or enable a prolongation or even a sustaining extension for the sake of
play; it may facilitate the achievement of temporal balance or be used in response
to a dramatic need contributed by text. In the formal realm, a parenthesis may
introduce an aside, an insert, a by-the-way remark. Parentheses in verbal composition have a different significance from parentheses in musical composition. In
a verbal text, where grammar and syntax are more or less firmly established, the
status of a parenthetical insertion as a dispensable entity within a well-formed
grammatical situation is easy to grasp. In a musical situation, however, although we
may speak of musical grammar and forms of punctuation, an imagined excision of
the material contained in a so-called parenthesis often seems to deprive the passage in question of something essential, something basic. What is left seems hardly
worthwhile; the remaining music is devoid of interest; it seems banal. This suggests
that musical parentheses are essential rather than inessential. A grammar of music
that does not recognize the essential nature of that which seems inessential is likely
to be impoverished.
Consider a simple chordal example. In the white-note progression shown in
example 3.8, we can distinguish between structural chords and prolonging chords.
The sense of the underlying syntaxthe progressions harmonic meaningcan be
conveyed using the structural chords as framework. In that sense, the intervening
chords may be said to be parenthetical insofar as the structure still makes sense
without them. And yet the prolongational means are so organically attached to
the structural pillars that the deparenthesized progression, while able to convey
something of the big picture by displaying the structural origins of the original
passage, seems to sacrifice rather a lot. Indeed, what is sacrificed in this musical
CHAPTER 3
97
( )(
from
98
PART I
Theory
minor for an actual recapitulation (bar 84). The parenthetical passage is the only
sustained major-mode passage in the movement. Its expressive manner is intense.
I hear a foreshadowing of a passage from one of Richard Strausss Four Last Songs,
September, in bars 7275 of the Beethoven. Locally, the parenthetical material
continues the process of textural intensification begun earlier in the movement. If
the achievement of tonal goals is accorded priority, then interpreting bars 7080
as a parenthesis is defensible. But the material inside the parenthesis is dispensable
only in this limited sense.
Periodicity, then, embraces the whole of music. As a quality, it is distributed
across several dimensions. I have talked about cadences and cadential action, closure, high points, discontinuity, and parenthesis. The overarching quality is closure, including its enabling recessional processes. A theory of musical meaning is
essentially a theory of closure.
12. On corporeality in music, with an emphasis on Chopin, see Eero Tarasti, Signs of Music: A Guide to
Musical Semiotics (Berlin: de Gruyter, 2002), 117154.
CHAPTER 3
99
although it remains the unmarked mode for all Romantic composers. And the
speech mode, although hierarchically differentiated from the song mode, also possesses near-native status for composers; given the deep but ultimately problematic
affinities between natural language and music (discussed in chapter 1) and given
the qualitative intensification of word dependency in nineteenth-century instrumental practice, it is not surprising to find composers exploring and exploiting the
speech mode of enunciation to set the others into relief.
How are these three modes manifested in actual composition? In speech mode,
the instrument speaks, as if in recitative. The manner of articulation is syllabic,
and resulting periodicities are often asymmetrical. Song and dance modes inhabit
the same general corner of our conceptual continuum. Song mode is less syllabic
and more melismatic. Periodicity is based on a cyclical regularity that may be broken from time to time for expressive effect. And, unlike speech mode, which is not
obligated to produce well-formed melody, the song mode puts melody on display
and calls attention to the singing voice, be it an oboe, English horn, violin, flute, or
piano. Song mode departs from the telling characteristic of speech. The impulse
to inform or deliver a conceptually recoverable message is overtaken by an impulse
to affect, to elicit a smile brought on by a beautiful turn of phrase. Accordingly,
where speech mode may be said to exhibit a normative past tense, song mode is
resolutely wedded to the present. While the dance mode often includes song, its
most marked feature is a sharply profiled rhythmic and metric sense. The invitation to danceto dance imaginativelyis issued immediately by instrumental
music in dance mode. This mode is thus deeply invested in the conventional and
the communal. Since dance is normally a form of communal expression, the stimulus to dance must be recognizable without excessive mediation. This also means
that a new dance has to be stabilized over a period of time and given a seal of social
approval. A new song, by contrast, has an easier path to social acceptance.
As always with simplified models like this, the domains of the three modes are
not categorically separate. I have already mentioned the close affinity between song
mode and dance mode. A work whose principal affect is located within the
song mode may incorporate elements of speech. Indeed, the mixture of modes is
an important strategy for composers of concertos, where the rhetorical ambitions
of a leading voice may cause it to shift from one mode to another in the manner
of a narration.
Examples of the three modes abound, but given our modest purposes in this
and the previous chapternamely, to set forth with minimum embroidery certain basic criteria for analysiswe will mention only a few salient examples and
contexts. Late Beethoven is especially rich in its exploitation of speech, song, and
dance modes. Scherzos, for example, are normative sites for playing in dance
mode. A good example is the scherzo movement of the Quartet in B-flat Major,
op. 130. Dance and song go hand in hand from the beginning. They have different trajectories, however. Once the dance rhythm has been established, it maintains an essential posture; we can join in whenever we like. Song mode, on the
other hand, refuses a flat trajectory. The degree of songfulness may be intensified
(as in bars 9ff.) or rendered normatively. Of particular interest in this movement,
however, is Beethovens speculative treatment of the dance. While the enabling
100
PART I
Theory
Example 3.9. The speech mode in Beethoven, String Quartet in B-flat Major, op.
130, third movement, bars 4863.
L'istesso tempo.
dim.
ritar
dan
do
ritar
dan
do
ritar
dan
do
ritar
dan
do
p
56
60
f
64
pp
pp
pp
pp
67
CHAPTER 3
101
listeners persona merges with the composers for a brief moment. Finally, in bar
64, Beethoven reactivates the dance and song modes by shutting the window that
allowed us a peek into his workshop and reengages the listener as dancer for the
remainder of the movement.
Similarly striking is the invocation of speech mode in the transition from
the fourth to the fifth movements of the Quartet in A Minor, op. 132. The fourth
movement, marked alla Marcia, begins as a 24-bar march in two-reprise form.
Marching affects the communality of dance mode. Immediately following is an
invocation of speech mode in the form of a declamatory song, complete with
tremolo effects in the lower strings supporting the first violin. This emergence of a
protagonist with a clear message contrasts with the less stratified stance of the preceding march. In this mode of recitative, meter and periodicity are neutralized, as
if to neutralize the effect of the march, which, although written in four, succumbs
to groupings in three that therefore complicate the metrical situation. (The coming
finale will be in an unequivocal three.) The rhetorical effect of this instantiation of
speech mode is to ask the listener to waitwait for a future telling. But the gesture
is fake, a simulation; there is nothing to be told, no secrets to be unveiled, only the
joy of playing and dancing that will take place in the finale. These games never fail
to delight.
Robert Schumann is one composer in whose music the speech and song
modes of enunciation play a central role. Numerous passages in the favorite Piano
Quintet tell of a telling, stepping outside the automatic periodicity built on 4-bar
phrases to draw attention to the music itself, thus activating the speech mode. The
D Minor Symphony, too, features moments of speech whose effect is made more
poignant by the orchestral medium. His songs and song cycles are rich sources of
this interplay; indeed, they are very usefully approached with a grid based on the
interaction between speech and song modes. In Dichterliebe, for example, song 4
unfolds in the interstice between speech mode and song mode, a kind of declamatory or arioso style; song 9 is in dance mode; song 11 in song mode; and song
13 in speech mode. The postlude to the cycle as a whole begins in song mode by
recalling the postlude to song 12 (composers typically recall song, not speech). As
it prepares to close, the speech mode intrudes (bars 5960). Then, some effort has
to go into reclaiming the song mode, and it is in this mode that the cycle reaches its
final destination. (We will return to this remarkable postlude in connection with
the discussion of narrative below.)
When the poet speaks at the close of the Kinderszenen collection (Der Dichter
spricht), he enlists the participation of a community, perhaps a protestant one. A
chorale, beginning as if in medias res and inflected by tonal ambivalence, starts
things off (bars 18). This is song, sung by the congregation. Then, the poet steps
forward with an introspective meditation on the head of the chorale (bars 912).
He hesitates, stops, and starts. This improvisatory manner moves us out of the earlier song mode toward a speech mode. The height of the poets expression (bar 12,
second half) is reached by means of recitativespeech mode in its most authentic state. Here, we are transported to another world. Our community is now far
behind. We hold our breaths for the next word that the poet will utter. Speech,
not song, makes this possible. Then, as if waking from a dream, the poet joins the
102
PART I
Theory
congregation in beginning the chorale again (bar 18). In song mode, we are led
gradually but securely to a place of rest. The cadence in G major at the end has been
long awaited and long desired. Its attainment spells release for the body of singers.
None of these modes is written into Schumanns score. They are speculative
projections based on affinities between the compositions specific textures and conventional ones. The sequence I have derivedsong mode, speech mode, heightened
speech mode (recitative), and finally song modeseeks to capture the composers
way of proceeding. Of course, the modes are not discrete or discontinuous; rather,
they shade into each other in accordance with the poets modulated utterances.
Chopin, too, often interrupts a normative song mode with passages in speech
mode. The Nocturne in B Major, op. 32, no. 1, proceeds in song mode from the
beginning, until a cadenza-like flourish in bar 60 prepares a grand cadence in bar
61. The resolution is deceptive, however (bar 62), and this opens the door to a
recitative-like passage in which speech is answered in the manner of choral affirmation. In these dying moments of the nocturne, speech mode makes it possible
to enact a dramatic effect.
The three modes of enunciation introduced here are in reality three moments
in a larger continuum. As material modes, they provide a framework for registering
shifts in temporality in a musical work. In song, where words bear meaning and
also serve as practical vehicles for acts of singing, it is sometimes possible to justify
a reading of one mode as speech, another as song, and a third as dance by appealing
to textual meaning and by invoking a putative intentionality on the part of the composer. In nonprogrammatic instrumental music, by contrast, no such corroborative
framework exists; therefore, hearing the modes remains a speculative exercisebut
this says nothing about their credibility or the kinds of insight they can deliver.
Narrative
The idea that music has the capacity to narrate or to embody a narrative, or that
we can impose a narrative account on the collective events of a musical composition, speaks not only to an intrinsic aspect of temporal structuring but to a basic
human need to understand succession coherently. Verbal and musical compositions invite interpretation of any demarcated temporal succession as automatically endowed with narrative potential. Beyond this basic level, musics capacity
to craft a narrative is constantly being undermined by an equally active desirea
natural one, indeedto refuse narration. Accordingly, the most fruitful discussions of musical narrative are ones that accept the imperatives of an aporia, of a
foundational impossibility that allows us to seek to understand narrative in terms
of nonnarration. When Adorno says of a work of Mahlers that it narrates without
being narrative,13 he conveys, on the one hand, the irresistible urge to make sense
13. Theodor Adorno, Mahler: A Musical Physiognomy, trans. Edmund Jephcott (Chicago: University of
Chicago Press, 1992), 76.
CHAPTER 3
103
of a temporal sequence by recounting it, and, on the other hand, the difficulty of
locating an empirical narrating voice, guiding line, or thread. Similarly, when Carl
Dahlhaus explains that music narrates only intermittentlyakin, in our terms, to
the intrusion of speech mode in a discourse in song or dance modehe reminds
us of the difficulty of postulating a consistent and unitary narrative voice across
the span of a composition.14 Using different metalanguages, Carolyn Abbate, JeanJacques Nattiez, Anthony Newcomb, Vera Micznik, Eero Tarasti, Mrta Grabcz,
Fred Maus, and Lawrence Kramer have likewise demonstrated that it is at once
impossible to totally resist the temptation to attribute narrative qualities to a musical composition and, at the same time, challenging to demonstrate narratives
musical manifestation in a form that overcomes the imprecision of metaphorical
language.15
Ideas of narrative are always already implicit in traditional music analysis. When
an analyst asks, What is going on in this passage? or What happens next? or Is
there a precedent for this event? the assumption is often that musical events are
organized hierarchically and that the processes identified as predominant exhibit
some kind of narrative coherence either on an immediate level or in a deferred
sense. The actual musical dimensions in which such narratives are manifest vary
from work to work. A favorite dimension is the thematic or motivic process, where
an initial motive, figured as a sound term, is repeated again and again, guiding the
listener from moment to moment, thus embodying the works narrative. Another
ready analogy lies in tonal process, specifically in the idea of departure and return.
If I begin my speech in C major and then move to G major, I have moved away
from home and created a tension that demands resolution. The process of moving from one tonal area to another depends on the logic of narrative. If I continue
my tonal narrative by postponing the moment of return, I enhance the feeling of
narrative by setting up an expectation for return and resolution. The listener must
wait to be led to an appropriate destination, as if following the plot of a novel. And
when I return to C major, the sense of arrival, the sense that a temporal trajectory
has been completed, the sense that a promise has been fulfilledthis is akin to the
experience of narration.
On the deficit side, however, is the fact that, because of the high degree of
redundancy in tonal music, because of the abundant repetition which we as listeners enjoy and bathe in, a representation of narration in, say, the first movement of
Beethovens Fifth Symphony, comes off as impoverished and uninspiring insofar as
it is compelled, within certain dimensions, to assert the same thing throughout
the movement. The famous four-note motif (understood as rhythmic pattern as
104
PART I
Theory
CHAPTER 3
105
Example 3.10. Song mode and speech mode at the close of Schumanns Dichterliebe.
Adagio
50
Lie - be und
Andante espressivo
53 Song mode
56
Song mode
59
Speech mode
62
ritard.
65
At the start of example 3.10, the job of unveiling the ultimate destination of
the last song (and, for that matter, the cycle) is entrusted to the pianist. The singer
dropped off on a predominant sonority, leaving the pianist to carry the thought
106
PART I
Theory
Conclusion
Chapter 2 and the present chapter have introduced six criteria for the analysis
of Romantic music: topics; beginnings, middles, and endings; high points; periodicity (including discontinuity and parentheses); modes of enunciation (speech
mode, song mode, dance mode); and narrative. The specific aspects of this repertoire that the criteria seek to model are, I believe, familiar to most musicians. So,
16. For an imaginative, thorough, and incisive account of this postlude, see Beate Julia Perrey,
Schumanns Dichterliebe and Early Romantic Poetics: Fragmentation of Desire (Cambridge: Cambridge
University Press, 2003), 208255.
CHAPTER 3
107
although they are given different degrees of emphasis within individual analytical
systems, and although there are still features that have not been discussed yet (as
indeed will become obvious in the following two chapters), I believe that these six,
pursued with commitment, have the potential to illuminate aspects of meaning in
the Romantic repertoire. Readers are invited to plug in their favorite pieces and
see what comes out.
Is it possible to put the concerns of our criteria together into a single, comprehensive model? And if so, what would the ideological underpinning of such
a gesture be? The criteria offered here seek an account of music as meaningful
discourse, as language with its own peculiarities. They are not mutually exclusive,
as we have seen, but necessarily overlapping; some may even lead to the same
end, as is easily imagined when one student focuses on periodicity, another on
the high-point scheme, and a third on narrative. A certain amount of redundancy
would therefore result from treating the criteria as primitives in an axiomatic or
generative system. Nor are they meant to replace the processes by which musicians
develop intuitions about a piece of music through performance and composition;
on the contrary, they may function at a metalinguistic level to channel description
and analysis formed from a more intuitive engagement.
Does this imply that the more perspectives one has at ones disposal, the better?
If putting it all together were a statistical claim, then the more perspectives that
one could bring to bear on a work, the better the analysis. But this kind of control
is not my concern here. Making a good analysis is not about piling on perspectives
in an effort to outdo ones competitors; it has rather to do with producing good
and interesting insights that other musicians can incorporate into their own subsequent encounters with a work. The institutional burdensmarked during the
heyday of structuralist methods in the 1980sof having to deal with wholes rather
than parts and of publicizing only those insights that could be given a theoretical underpinning may have delayed the development of certain kinds of analytical insight. If, thereforeand respectfullyI decline the invitation to try and put
it all together here, I hope nonetheless that the partial and provisional nature of
these outcomes will not detract from the reader/listener enjoying such moments
of illumination as there may have been.
C HA P T E R
Four
Bridges to Free Composition
Tonal Tendency
Let us begin with the assumption that a closed harmonic progression constitutes
the norm of coherent and meaningful tonal order. Example 4.1 exemplifies such a
progression. Hearing it initially not as an abstraction but as a real and immediate
progression allows us to identify a number of tendencies fundamental to tonal
behavior and crucial to the development of a poetics of tonal procedure.
110
PART I
Theory
CHAPTER 4
111
1. Schenker, Der Tonwille: Pamphlets in Witness of the Immutable Laws of Music, vol. 1, ed. William
Drabkin, trans. Ian Bent et al. (Oxford: Oxford University Press, 2004), 66, 13.
2. Heinrich Schenker, Counterpoint: A Translation of Kontrapunkt, trans. John Rothgeb and Jrgen
Thym (New York: Schirmer, 1987), 175.
3. Schenker, Der Tonwille, 21.
112
PART I
Theory
not a method of composition but a way of training the ear, so in one sense it is
beside the point what (superficial) stylistic forms a particular structural procedure
takes. An 858585 intervallic pattern between treble and bass, an extensive
prolongation of the dominant via the flattened-sixth, or a delay in the arrival of
CHAPTER 4
113
4. There are exceptions, of course. Already in 1981, Jonathan Dunsby and John Stopford announced
a program for a Schenkerian semiotics that would take up questions of musical meaning directly.
See Dunsby and Stopford, The Case for a Schenkerian Semiotic, Music Theory Spectrum 3 (1981):
4953. More recently, Naomi Cumming has drawn on Schenker in developing a theory of musical subjectivity. See her The Sonic Self: Musical Subjectivity and Signification (Bloomington: Indiana
University Press, 2000). See also David Lidovs discussion of segmental hierarchies in Is Language
a Music? 104121. And there are other names (e.g., Alan Keiler, William Dougherty) that could be
added to this list. Nevertheless, it would be hard to support the contentionjudging from the writings of leading semioticians like Nattiez, Monelle, Tarasti, and Hattenthat a Schenkerian approach
is central to the current configuration of the field of musical semiotics.
114
PART I
Theory
to separate the study of (Fuxian) species counterpoint from the study of the music
itself. But although convenient in concept, the dichotomy proved to be hard to
sustain at a practical level. Schenker, no doubt in possession of a huge supplement
of information pertaining to free composition, drew regularly on this supplement
in making his analyses, but he did not always make explicit the source of this other
knowledge. Instead, he held fast to the more immediate theoretical challenge.
Strict counterpoint is a closed world, a world built on rules and prescriptions
designed to train students in the art of voice leading and therefore to prepare them
for better understanding of the music of the masters. In strict counterpoint, there
are, in principle, no Stufen; there is no harmonic motivation, no framework for
making big plans or thinking in large trajectories. All we have are consonances
and dissonances, voice leading, and specific linear and vertical dispositions of
intervals. There is no repetition, no motivic life, no danceonly idealized voices
following very local impulses and caring little for phraseology, outer form, or the
referential potency of tonal material. Free composition, by contrast, deals with the
actual work of art; it is open and promiscuous and admits all sorts of forces and
licenses. Unlike strict counterpoint, it relies on scale steps, possesses genuine harmonic content, incorporates repetition at many levels, and perpetuates diversity at
the foreground. The essential nature of strict counterpoint is its strictness, that of
free composition its freedom.5 This is why counterpoint must somehow be thoroughly separated from composition if the ideal and practical verities of both are to
be fully developed.6 Indeed, according to Schenker, the original and fundamental error made by previous theorists of counterpointincluding Bellerman and
Richter and even Fux, Albrechtsberger, and othersis the absolute and invariable
identification of counterpoint and theory of composition. We must never forget
that a huge chasm gapes between the exercises of counterpoint and the demands
of true composition.7
So much for the fanfare announcing the separation between strict counterpoint and free composition. If we now ask what the connection between the two
might be, distinctions become less categorical, their formulations more qualified
and poetic. Free composition is essentially a continuation of strict counterpoint,
writes Schenker in Tonwille.8 The phrase essentially a continuation implies that
these are separate but related or relatable domains. In Kontrapunkt, Schenker says
that, despite its so extensively altered appearances, free composition is mysteriously bound . . . as though by an umbilical cord, to strict counterpoint.9 Thus, at
a practical or analytical level, the dividing line between them is porous, perhaps
nonexistent. Their separation is a matter of principle.
Schenker used the suggestive metaphor bridges to free composition to suggest a
relationship between subsurface and surface, between background and foreground,
and ultimately between strict counterpoint and free composition. The discussion of
5.
6.
7.
8.
9.
CHAPTER 4
115
10. See also Eytan Agmon, The Bridges That Never Were: Schenker on the Contrapuntal Origin of the
Triad and the Seventh Chord, Music Theory Online 3 (1997).
116
PART I
Theory
While all of this sounds logical, there has been a gap in the analysis. How did we
get from level b to level c? Obviously, we did this by knowing the design of level c in
advance and inflecting the derivational process in level b to lead to it. But how do we
know what stylistic resources to use so that c comes out sounding like Handel and
not Couperin or Rameau? How did we invent the design of the musical surface?
Schenker does not dwell on these sorts of questions; indeed, he seems to discourage us from dwelling on these aspects of the foreground. We are enjoined,
instead, to grasp the coherence that is made possible by the background. But if the
possibilities for activating the progression shown at level a are not spelled out, if
they are consigned to the category of unspecified supplement, and if the analyst of
Handels suite is not already in possession of knowledge of a whole bunch of allemandes from the early eighteenth century, how is it possible to generate a specific
surface from a familiar and common background? Without, I hope, overstating the
point, I suggest that the journey from strict counterpoint (level a) to free composition (level c) makes an illicit orbettera mysterious leap as it approaches its
destination. I draw attention to this enticing mystery not to suggest a shortcoming
but to illustrate one consequence of this particular setting of theoretical limits.
11. Schenker, Free Composition, 3.
12. Schenker, Counterpoint, book 1, 59.
CHAPTER 4
117
In the 2 bars from Bachs C-sharp Minor Prelude from book 1 of the WellTempered Clavier in example 4.4, we hear a familiar progression in which the bass
moves by descending fifths while the upper voices enrich the progression with 76
suspensions. This model of counterpoint ostensibly enables Bachs free composition (level b). But here, too, there are no rules that would enable us to generate the
specific dance-like material that is Bachs actual music.
Example 4.4. J. S. Bach, Well-Tempered Clavier, book 1, Prelude in C-sharp Minor,
bars 2628 (cited in Schenker, Counterpoint, 337).
C# minor: (V-) I
VI
II
(I)
Level a of example 4.5 looks at first like a second species exercise, although its
incorporation of mixture (G-flat) takes it out of the realm of strict Fuxian species.
Whereas the demonstrations in the two previous examples approximate . . . form[s]
of strict counterpoint, thus placing the emphasis on a generative impulse, this
Example 4.5. Brahms, Handel Variations, op. 24, var. 23 (cited in Schenker,
Counterpoint, 192).
10
118
PART I
Theory
passage from Brahms is reduced to a clear two-voice counterpoint; the emphasis rests on a reductive impulse. Schenker points out that the real connection
between strict counterpoint and free composition can in general be discovered
only in reductions similar to [example 4.5].13 In other words, in the case of certain complex textures, the contrapuntal underpinning may lie further in the
background, requiring the analyst to postulate additional levels of explanatory
reduction. (Constructing the additional levels could be a valuable student exercise
in the case of example 4.5.) Whether the degree of reducibility is reflected in a
larger historical-chronological narrative or whether it conveys qualitative differences among compositions are issues left open by Schenker.
The mode of thinking enshrined in examples 4.3, 4.4, and 4.5 of hearing complex textures through simpler structures makes possible several valuable projects,
some of them historical, others systematic. We might envisage, for example, a history of musical composition based strictly on musical technique. This project was
already implicit in Felix Salzers 1952 book, Structural Hearing, but it has yet to
engender many follow-up studies.14 Imagine a version of the history of composition based on the function of a particular diminution, such as the passing note,
including leaping passing notes; or imagine a history of musical technique based
on neighbor-note configurations, or arpeggiations. Granted, these are not exactly
the sexiest research topics to which students are drawn nowadays, but they have
the potential to illuminate the internal dynamics of individual compositions and
to set into relief different composers manners. Without attempting to be comprehensive, I can nevertheless hint at the kinds of insights that might accrue from
such an approach by looking at a few examples of a single diminution: the neighbor-note.
CHAPTER 4
119
Example 4.6. Schubert, String Quintet in C Major, first movement, bars 16.
N
die
Hh
ne
krh
N
ten
f
(*)
(*)
Example 4.8 cites two similar 2-bar passages from the opening movement of
Mahlers Tenth. In the first bar of each, the content of the opening tonic chord (Fsharp major) is expanded through neighbor-note motion. Note that while the bass
is stationary in the first excerpt (as in the Schubert quintet cited in example 4.6), it
acquires its own lower neighbor in the second.
Example 4.8. Mahler, Symphony no. 10, first movement, (a) bars 1617, (b) bars
4950.
N
16
49
120
PART I
Theory
out Strauss as a composer who could compose neighboring notes conceived even
in four voices in a most masterful way18a rare compliment from a theorist who
was usually railing against Strauss and his contemporaries Mahler, Reger, and
Debussy.
Example 4.9. Richard Strauss, Till Eulenspiegels lustige Streiche (cited in Schenker,
Counterpoint, 192).
N
a
Example 4.10, also from Till, is a little more complex, so I have included a
speculative derivation to make explicit its origins from strict counterpoint. Start
at level a with a simple, diatonic neighbor-note progression; alter it chromatically while adding inner voices (level b); thenand here comes a more radical
stepdisplace the first element up an octave so that the entire neighbor-note
Example 4.10. Richard Strauss, Till Eulenspiegels lustige Streiche (level d cited in
Schenker, Counterpoint, 192).
N
a
N
b
N
c
d
mf
CHAPTER 4
121
configuration unfolds across two different registers (level c). Level d shows the
outcome. Note, again, that while one can connect Strausss theme to a diatonic
model as its umbilical cord, nothing in the generative process allows us to infer the
specific play of motive, rhythm, and articulation in the foreground.
Staying with Strauss for a moment longer, example 4.11 summarizes the chordal
motion in the first 6 bars of his beautiful Wiegenlied. Over a stationary bass (recall
the Schubert excerpt in example 4.6 and the first of the Mahler excerpts in example
4.8), the upper voices move to and from a common-tone (neighboring) diminishedseventh chord. Two other details add to the interest here: the expansion of the neighboring chord in bar 4 by means of an accented passing note (see C# in rh), the effect
of which is to enhance the dissonance value of the moment; and the similarity of
melodic configuration involving the notes ADCBA in both the accompaniment and the vocal melody, which produces a sort of motivic parallelism.
Example 4.11. Richard Strauss, Wiegenlied, bars 16.
N
a
Tru
me,
tru
me
Finally, in example 4.12, I quote two brief passages from the Credo of Stravinskys Mass, where, in spite of the extension of ideas of consonance and dissonance,
the morphology of neighbor-note formation is still evident.19
A history of musical technique based on the neighbor-note would not be confined to the very local levels just shown; it would encompass larger expanses of
music as well. Think, for example, of the slow movement of Schuberts String Quintet, whose F minor middle section neighbors the E major outer sections; or of his
Der Lindenbaum from Winterreise, where the agitated middle section prolongs
C-natural as an upper chromatic neighbor to the dominant, B, intensifying our
19. See Harald Krebs, The Unifying Function of Neighboring Motion in Stravinskys Sacre du
Printemps, Indiana Theory Review 8 (Spring 1987): 313; and Agawu, Stravinskys Mass and
Stravinsky Analysis, Music Theory Spectrum 11 (1989): 139163, for more on Stravinskys use of
neighbor-notes.
122
PART I
Theory
Example 4.12. Stravinsky, Mass, Credo, (a) bars 13, (b) bars 0000.
a
Tempo q = 72 (e = 144)
b
N
Discanti
Pa- trem om- ni - po- ten - tem,
Et in u - num
Chris - tum,
Et in u - num
Chris - tum,
Et in u - num
Chris - tum,
Et in u - num
Chris - tum,
Alti
Tenori
Bassi
Piano
desire for the tonic. Or think of Debussys prelude Bruyres, whose contrapuntal
structure, based on the succession of centers ABA, features an expanded
neighbor-note progression. Readers will have their own examples to add to the few
mentioned here. A comprehensive study would be illuminating.
Generative Analysis
Returning now to the white-note progression whose tonal tendencies we mentioned earlier, let us recast its elements as a set of ideal voices, an abstract model
that is subject to a variety of enactments (example 4.13). A compositional orientation allows us to imagine how this progression might be embellished or expanded
in order to enhance musical content. The act of embellishing, which is affined with
prolongation, is better conceptualized not as an additive process but as a divisive
one. An event is prolonged by means of certain techniques. How to delay reaching
CHAPTER 4
123
that final dominant? How to enhance the phenomenal feel of an initial tonic? How
to intensify desire for that cadence? This bottom-up mode of thinking casts the
analyst into a composerly role and urges a discovery of the world of tonal phenomena from the inside, so to speak. Analysis, in this understanding, is not a spectator sport.
Let us join in with the most elementary of moves. The progression in example
4.14 responds to a desire to embellish sonority 2 from example 4.13. This strengthens the sonority by means of a retroactive prolongation using a lower neighbornote, the bass note F. While the essence of the prolongation is that given in example
4.13, the form given in example 4.14 acquires greater content. Similarly, example
4.15 responds to the challenge of extending the functional domain of that same
middle element by arpeggiating down from the tonic to the predominant chord.
This represents an embellishment of a previous embellishment. Alternatively, we
may hear example 4.15 in terms of two neighbor-notes to the G, an upper (A) and
a lower (F), both prefixes. But if we think in terms of the ambitions of the initial
C, then it could be argued that the bass arpeggiation (CAF) embellishes C on
its way to the dominant G. These explanations begin to seem confused, but that is
precisely the point. That is, the domains of both a prospective prolongation of C
(by means of a suffix) and a retroactive prolongation of G (by means of a prefix)
overlap. Such is the nature of the continuity and internal dependence of the elements of tonal-functional material.
Example 4.14. Same with predominant sonority.
Alternative bass:
124
PART I
Theory
arpeggiation. This allows us to link up the first and second sonorities. This kind of
logic can be operationalized as pedagogy and taught to students. Indeed, it is what
happens in some sectors of jazz pedagogy. While it is not unheard of in the pedagogy associated with classical music, its centrality is not yet complete. Yet there
is clearly an advantage to forging cooperation between student and composer,
encouraging students to take responsibility as co-composers. Although such cooperation could blossom into bigger and more original acts of creativity, the modest
purpose here is simply to find ways of inhabiting a composition by speculatively
recreating some aspects of it.
Example 4.16 is yet another recomposition of our basic model. The steps
involved may be stated as follows:
a. State the basic progression.
b. Expand the middle element by means of a predominant sonority.
c. Extend the first element by means of voice exchange between treble and
bass in order to obtain a smooth, stepwise bass line.
d. Further expand the first sonority of the voice exchange by means of a
neighbor-note prolongation.
Example 4.16. Prolonging the archetypal progression.
a
CHAPTER 4
125
occasionally coincide with the compositional process, its validity does not rest
on such corroboration. Indeed, unlike the compositional process, which traces
an essentially biographical/diachronic/historical process, the logical procedure
advances a systematic fictional explanation. Music analysis is centrally concerned with such fictional procedures. As analysts, we trade in fictions. The better the fictional narrative, the more successful is the analysis. The more musical
the rules, the better is the analysis; the more musically plausible the generative
bases, the better is the analysis.
20. Simon Sechter, Analysis of the Finale of Mozarts Symphony no. [41] in C [K. 551 (Jupiter)],
in Music Analysis in the Nineteenth Century, vol. 1: Fugue, Form and Style, ed. Ian D. Bent (Cambridge: Cambridge University Press, 1994), 85.
126
PART I
Theory
Example 4.17. Sechters generative analysis of bars 5662 of the finale of Mozarts
Symphony in C (Jupiter).
or:
d
56
Fl.
Ob.
Fg.
Cor.
(C)
Trbe.
(C)
Timp.
Vl.
Vla.
Vc.
e B.
CHAPTER 4
127
Example 4.18. Beethovens Piano Sonata in C Major, op. 53 (Waldstein), bars 113,
with Czernys harmonic groundwork.
pp
10
21. Carl Czerny, Harmonic Groundwork of Beethovens Sonata [no. 21 in C] op. 53 (Waldstein),
quoted in Music Analysis in the Nineteenth Century, vol. 2, ed. Ian D. Bent (Cambridge: Cambridge
University Press, 1994), 188196.
128
PART I
Theory
groundwork with the original and thus learn something about harmonic construction andin the context of the groundwork for the entire movementthe
way in which ideas are ordered.
The progression quoted in example 4.19 is Erwin Ratzs summary of the harmonic basis of an entire compositionand a contrapuntal one at that: the first of
J. S. Bachs two-part inventions.22 As a synopsis, this progression lies sufficiently
close to the surface of the composition to be appreciated by even a first-time
listener. It can also serve as a horizon for appreciating the tonal tendency conveyed
by Bachs sixteenth-note figures. Beginning in the tonic, the invention tonicizes V,
then vi, before returning home via a circle of fifths.
Example 4.19. Ratzs harmonic summary of J. S. Bach, Two-Part Invention in C
Major.
1
I-V
ii - vi
circle of fifths
10
11
12
cadence
In generative terms, the models of tonal motion used by Bach include two
kinds of cadence (a perfect cadence and an imperfect cadence) and a circle-offifths progression. If we number the sonorities in Ratzs synopsis as 112, we can
define their functions as follows. The 1112 sequence is a perfect cadence in the
home key, 46 is also a perfect cadence but on vi (4 being the predominant sonority, 5 the dominant, and 6 the concluding tonic), 12 forms a half cadence (an
open gesture), and 710 constitutes a circle-of-fifths progression, ADGC.
The journey from the white-note level to a black-note one may be illustrated
with respect to bars 1518 of Bachs invention (example 4.20). At level a is the bare
linear intervallic pattern of descending bass fifths in a two-voice representation. At
level b, passing notes at the half-note level provide melodic continuity. Rhythmic
interest is introduced at level c with the 43 suspensions in the second and fourth
bars. And from here to Bachs music (level d) seems inevitable, even without us
being able to predict the exact nature of the figuration.
At an even more remote level of structure lies Toveys harmonic summary
of the first movement of Schuberts C Major Quintet (example 4.21).23 He is not
concerned with the generative steps leading from this postulated background to
Schuberts multifaceted surface, but with a synopsis that incorporates a hierarchy
reflected in the durations of individual triads. The longer notes are the focal points,
the shorter ones are connexion links. Although Tovey elsewhere understands and
employs notions akin to Schenkerian prolongation, he is not, it appears, concerned
with establishing the prolongational basis of the movement as such, nor with
22. Erwin Ratz, Einfhrung in die musikalische Formenlehre, 3rd ed. (Vienna: Universal, 1973), 55.
23. Donald Francis Tovey, Essays and Lectures on Music (Oxford: Oxford University Press, 1949), 150.
CHAPTER 4
129
exploring the prolongational potential of this progression. Still, the idea is suggestive and shares with notions of generation the same procreative potential.24
c
4
- 3
15
Recapitulation
bIII
bVI
Prolonged Counterpoint
The larger enterprise in which Sechter, Czerny, Ratz, Tovey, and numerous other
theorists were engaged is the speculative construction of tonal meaning drawing on the fundamental idea that understanding always entails understanding in
terms of, and that those terms are themselves musical. Widespread and diffuse,
these collective practices have been given different names, pursued in the context
of different genres of theory making, and illustrated by different musical styles and
composers. Already in this chapter, we have spoken of diminutions, prolongation,
24. In Schenker and the Theoretical Tradition, College Music Symposium 18 (1978): 7296, Robert
Morgan traces aspects of Schenkerian thinking in musical treatises from the Renaissance on. Finding such traces or pointing to affinities with other theoretical traditions is not meant to mute the
force of Schenkers originality.
130
PART I
Theory
the relationship between strict counterpoint and free composition, harmonic summaries and the expansion of musical content, and generating a complex texture
from simpler premises. Can all of these analytical adventures be brought together
under a single umbrella? Although it is obviously desirable to stabilize terminology
in order to increase efficiency in communication, the fact, first, that the core idea
of this chapter is shared by many musicians and music theorists, and second, that
it can be and has been pursued from a variety of angles, is a sign of the potency of
the idea. We should welcome and even celebrate this kind of plurality, not retreat
from it as a sign of confusion.
For our purposes, then, the choice of a single rubric is in part an arbitrary
and convenient gesture. I do so to organize the remaining analyses in this chapter, which, like previous analyses, will involve the construction of bridges from
background to foreground within the limitations noted earlier. The term prolonged
counterpoint is borrowed directly from Felix Salzer and Carl Schachters Counterpoint in Composition.25 Distinguishing between elementary counterpoint and
prolonged counterpoint, they understand the latter in terms of the development
and expansion of fundamental principles, specifically, as the significant and fascinating artistic elaboration of basic ideas of musical continuity and coherence.
Salzer and Schachter devote several chapters to the direct application of species
counterpoint in composition and then conclude by studying counterpoint in composition in a historical framework, going from Binchois to Scriabin.
More formally, we say that an element is prolonged when it extends its functional domain across a specified temporal unit. The prolonged entity controls,
stands for, is the origin of, or represents other entities. (The historically rooted
idea of diminution is relevant here.) Prolongation makes motion possible, and the
prolonged entity emergesnecessarilyas the hierarchically superior member of
a specific structural segment. And by counterpoint, we mean a musical procedure
by which two (or more) interdependent lines are coordinated (within the conventions of consonance-dissonance and rhythm) in a way that produces a third,
meaningful musical idea.
One important departure from Salzer and Schachter concerns the place of harmony in the generative process. Although the proto-structures we have isolated
so far are well-formed from a contrapuntal point of view, they are regarded as
harmonic structures as well. The harmonic impetus is regarded here as fundamental, and especially so in relation to the main repertoires studied here. To say
this is to admit that we have conflated ideas of counterpoint and harmony in these
analyses. Prolonged harmony/counterpoint would be a more accurate rubric, but
because counterpoint always entails harmony (at least in the repertoires studied in
this book), and harmony always entails counterpoint, this more literal designation
would carry some redundancy.
The basic generative method involves the construction of an underlying structure as a supplement or potential replacement (Derridas sense of supplement)
25. Felix Salzer and Carl Schachter, Counterpoint in Composition (New York: Columbia University
Press, 1989), xiv.
CHAPTER 4
131
for the more fully elaborated target surface. We might speak of logically prior
structures, of surface and subsurface elements, of immediate as opposed to remote
structures, and of body as distinct from dress. Analysis involves the reconstruction of prototypes, underlying structures, or contrapuntal origins of a given composition or passage. In some of the examples, I have been concerned to reveal
the generative steps explicitly. Of course, these subsurface structures are fictional
structures invented for a specific heuristic purpose, namely, to set the ruling surface into relief by giving us a speculative glimpse into its putative origins; these
rational reconstructions act as a foil against which we can begin to understand the
individual features of the composition. The aim of a generative analysis is not to
reproduce a known method of composition (based on historical or biographical
reconstruction) but to draw on fabricated structures in order to enable the analyst
to make imaginative projections about a works conditions of possibility.
Finally, let me rehearse just three of the advantages of the approach. First, by
engaging in acts of summary, synopsis, or paraphrase, we are brought into close
encounter with a composition; we are compelled to, as it were, speak music as a
language. Second, the reduced structures will encourage a fresh conceptualization
of form. (This will become clearer in the larger analyses in part 2 of this book.)
How do the little (white-note) progressions, contrapuntal structures, or building
blocks succeed one another? I believe that answers to this question will lead us to a
more complex view of form than the jelly-mold theories canonized in any number
of textbooks. Third, by comparing treatments of the same or similar contrapuntal
procedures or figures across pieces, we become even more aware of the specific
elements of design that distinguish one composer from another, one work from
another, or even one passage from another.
The purpose of an analysis is to establish the conditions of possibility for a
given composition. Although other dimensions can support such an exercise, harmony and voice leading seem to be the most important. The analytical method
consists of inspecting all of the harmonic events and explaining them as instances
of cadential or prolongational motion (prolongation here includes linear intervallic patterns). Cadences and prolongations are subject to varying degrees of disguise, so an essential part of the analysis is to show how a simple, diatonic model
is creatively embellished by the composer. The possible models are relatively few
and are postulated by the analyst for a given passage. Then follows the speculative
task of demonstrating progressive variations of those models. Varying or enriching these simple models encourages the analyst to play with simple harmonic
and contrapuntal procedures, procedures that are grammatically consistent with
the style in question. While the analysis aims at explaining the whole composition from this perspective, it is not committed to the unique ordering of models
within a particular whole. (This last point becomes an issue at a further stage of the
analysis.) The whole here is succession, not progression; the whole is a composite
assembled additively. Analytical labor is devoted to identifying those elements
cadences and prolongational spansthat constitute the composite. By focusing
on the things that went into the compositions, the arsenal of devices, we prepare
for a fuller exploration of the work as a musical work, not as a musical work. We
establish what made it possible, leaving individual listeners to tell whatever story
132
PART I
Theory
they wish to tell about the finished work. Following this method is akin to navigating the work in search of its enabling prolongations and cadences. Once these are
discovered, the analytical task is fulfilled. Obviously, there will always be more to
say about the work. Works endure, and as along as there are listeners and institutions, there will be additional insights about the most familiar works. But shifting
attention from the work as such to its grammatical constituents may reward analysts, who are not passive consumers of scores but active musicians who wish to
engage with musical works from the inside. This kind of analysis rewrites the work
as a series of speculative projections; it establishes the conditions of possibility for
a given work.
(3)
Between these two poles of beginning (bars 14) and ending (bars 1316) is
a middle comprising a dominant prolongationour third technique.26 The first
phase of this prolongation is heard in bars 58, where the dominant is prolonged
retroactively by upper and lower neighbors in the bass (E and C, supporting vi and
ii6 chords), as shown at level a. Level b expands this progression by employing a
secondary dominant to enhance the move to vi and incorporating an appoggiatura
to ii6. Finally, level c incorporates this progression into Strausss 4-bar passage.
Bars 912 are essentially a continuation of the dominant prolongation of bars
58. They are harmonically sequential, as suggested in the two-voice representation at level a. Level b enriches this progression with the usual passing notes and
appoggiaturas, and level c restores the metrical context.
26. Although the literal span of the V prolongation is bars 515, my interest here is in the rhetoric of
prolongational expression, so I will maintain reference to the 4-bar segments previously isolated.
CHAPTER 4
133
(continued)
134
PART I
Theory
13
of the text in a kind of declamatory or speech mode, the first violins memorable
song-mode melody, the orchestration, and the willful playing with time.) By establishing some connection with tonal norms, we can, I believe, appreciate better the
nature of Strausss creativity.
CHAPTER 4
135
Schubert, Dass sie hier gewesen, op. 59, no. 2, bars 118
Example 4.23 develops a similar generative account of bars 118 of Schuberts
song Dass sie hier gewesen. We start at level a with a simple auxiliary cadence,
ii6VI. An idiomatic progression, this guiding model comprises a predominant,
dominant, tonic succession. At level b, the predominant is prefaced by its own
dominant-functioning chord, a diminished-seventh in 6/5 position, introduced to
intensify the move to the predominant. At level c, this same progression is enriched
by neighbor-notes and passing notes and then expanded: it is disposed first incompletely (bars 18), then completely (bars 916). Schubert (or the compositional
persona) in turn extends the temporal reach of the opening dissonance across 4
Example 4.23. Bridges to free composition in Schuberts Dass sie hier gewesen,
op. 59, no. 2, bars 118.
a
5 - 6
1-4
7 - 8
9-11
12
13 - 14 15-16
Sehr langsam
Da der
Ost- wind
Df - te
hau
chet in die
Lf
pp
pp
10
tut
er
kund
da du hier ge - we -
sen,
da du hier ge - we - sen.
te,
da - durch
136
PART I
Theory
bars, incorporates appoggiaturas to the dissonance, and places the initial statements in a high register on the piano.
The chronology favored by Wintle privileges a compositional rather than an analytic or synthetic approach. He concentrates on the workbench methods of the
composer by isolating models and showing how they are composed out. These
fictional texts are meaningful units that exist in a dialectical relationship with the
segments of actual music that they model. Each is syntactically coherent but has
minimum rhetorical content. In Corelli (unlike in the Strauss and Schubert works
discussed previously), both the model and its variants may occur in the work.
The opening Grave movement of the Church Sonata, op. 3, no. 1 (shown in its
entirety in example 4.24), will serve as our demonstration piece. Example 4.25 displays the generating model at level a as a straightforward, closed progression. Following the model are a number of variants that are referable to the model. At level
b, a I6 chord substitutes for the initial root-position chord and effectively increases
27. Christopher Wintle,), 31. Methodologically similar is William Rothsteins article Transformations of Cadential Formulae in Music by Corelli and His Successors, in Studies from the Third
International Schenker Symposium, ed. Allen Cadwallader (Hildersheim, Germany: Olms, 2006).
CHAPTER 4
137
the mobility in the approach to the cadence. (Cadential groups originating from
Violino II.
Violone,
e Organo.
6 6
65
8 6
6
5
5
4
6
5
6 9
5
6
5
86
6
5
5
4
43 6
6
5
5
4
6
5
6
5
86
6
5
5
4
13
5 3
4
6 5
7 5
5
4
6 6
5 6 6
5
5
4 3
7 6 5
3 4 4 3
I have divided the movement into 13 units or building blocks, some of them
overlapping:
1.
2.
3.
4.
5.
6.
7.
Bars 122
Bars 2344
Bars 564
Bars 6473
Bars 7483
Bars 8494
Bars 94104
8.
9.
10.
11.
12.
13.
Bars 104114
Bars 114123
Bars 13141
Bars 142152
Bars 152171
Bars 172194
138
PART I
Theory
or
CHAPTER 4
139
6 5
6
5
4 3
truncated versions; units 5 and 8 and 9, also truncated, are heard in the dominant
(5) and the relative minor (8 and 9). Unit 11 substitutes a beginning on V for the
models I, while unit 4 closes deceptively, substituting a local vi for I (in C). These
units express the basic model in the following order of conceptual complexity:
2
12
13
6
7
5
9
8
11
4
Fully 10 of the works 13 units are variants of this basic model. What about the
rest? The remaining three are based on a tonally open progression shown at level
140
Theory
PART I
e of example 4.25. That model is almost identical to the basic model, except that
instead of closing, it reaches only the penultimate dominantit is interrupted, in
2 span, not the 5
1 of the
other words. In structural-melodic terms, it unfolds a 5
unit 2
from
6 5
86
6
5
4 3
16
from
unit 12
6 6
5 6 6
5
5
4 3
18
from
unit 13
7
3
6
4
5
4 3
from
unit 6
6
5
(continued)
10
unit 7
from
6
5
unit 5
from
6
5
5
4
or
from
6
5
5
4
12
unit 9
from
6
5
5
4
or
12
from
6
5
5
4
(continued)
11
from
unit 8
6
5
6
5
or
11
from
6
5
6
5
from
unit 4
6
5
5
4
or
from
6
5
5
4
15
from
unit 11
5
4
(continued)
CHAPTER 4
143
from
unit 1
13
from
unit 10
5
4
from
unit 3
5
4
6
5
basic model. This second model is heard as unit 1, that is, right at the outset of the
work. It is also heard as unit 10 and finally as unit 3 (in conceptual order).
With this demonstration of the affinities and affiliations between the two models and all of the segments of Corellis Trio Sonata, op. 3, no. 1/i, the purpose of this
restricted analysisto establish the conditions of possibility for the movement
has been served. This does not mean that there is nothing more to say about the
work. Indeed, as we will see when we turn to the paradigmatic approach in the next
chapter, several interesting questions and issues are raised by this kind of analysis.
For example, what kind of narrative is enshrined in the piece-specific succession of
units? I have largely ignored this issue, concentrating instead on conceptual order
rather than chronology. But if we think back to the conceptual succession of units
2, 12, and 13, the units that lie closest to the basic model, then it is clear that the
strongest expressions of that model lie near the beginning of the work and at the
end. And the fact that the ending features a twofold reiteration of the model (units
12 and 13) may reinforce some of our intuitions about the function of closure.
We may also wish to pursue the matter of dispositio (form), stimulated in part
by Laurence Dreyfuss analysis of the first of Bachs two-part inventions (whose
144
PART I
Theory
28. Laurence Dreyfus, Bach and the Patterns of Invention (Cambridge, MA: Harvard University Press,
1996), 132.
CHAPTER 4
145
then a two-voice version, then a version enriched with passing notes but missing
two steps of the model (EA), and finally Bachs music (1722).
The third pattern used by Bach is a bass pattern proceeding from I to V in
7
6
5 motion. The first two lines of example 4.30 display the pattern in
stepwise 8
6 or 6
5
becomes
or
13
becomes
or
expressed by Bach as
22
146
PART I
Theory
thirds and tenths, respectively. Then, the straight tenths of line 2 are enlivened by
a pair of 76 suspensions in the middle 2 bars (line 3). From here, it is but a short
step to Bachs first 4 bars, which include a 43 suspension in the fourth bar (line 4).
The 4-bar passage is repeated immediately (line 5).
These three patterns are, of course, ordinary patterns in eighteenth-century
7
6
5 bass pattern, familiar to many from Bachs Goldberg Variamusic. The 8
tions, reaches back into the seventeenth century, during which it functioned
as an emblem of lament.29 It was also subject to various forms of enrichment,
Example 4.29. Circle of fifths as model.
A circle-of-fifths progression
etc
may be expressed as
or as
and by Bach as
A circle-of-fifths progression
may be rendered as
and by Bach as
17
29. Ellen Rosand, The Descending Tetrachord: An Emblem of Lament, Musical Quarterly 65 (1979):
346359.
CHAPTER 4
147
including the incorporation of chromatic steps. It functions here as a beginning, an opening out. Bach claims this space, this trajectory, not by inventing a
new bass pattern, but by expressing the familiar within a refreshed framework.
For example, he treats the medium of solo cello as both melodic and harmonic,
and thus incorporates within a compound melodic texture both conjunct and
disjunct lines. Apparent disjunction on the musical surface is rationalized by
the deeper-lying harmonic/voice-leading patterns revealed here. Bachs ingenious designs owe not a little to the security of his harmonic thinking. In bars
14, for example, the first and third notes of the GFED bass motion appear
as eighth-notes in metrically weak positions, but this in no way alters the harmonic meaning of the phrase. Similarly, the B-natural at the beginning of bar 17
resolves to a C an octave higher in the middle of the next bar, but the registral
7
6
5 bass pattern as model.
Example 4.30. The 8
^ ^ ^ ^
8 - 7 - 6 - 5 bass pattern
expressed as
enriched as
composed by Bach as
1
and repeated as
148
PART I
Theory
a speculative play with their elements. Again, the matter of final chronology
how these three models are ordered in this particular pieceis, at this stage
of the analysis, less important than simply identifying the model. If we think
of Bach as improviser, then part of our task is to understand the language of
improvisation, and this in turn consists in identifying tricks, licks, clichs, and
conventional moves. How these are ordered on a specific occasion may not ultimately matter to those who view compositions as frozen improvisations, and
to those who often allow themselves to imagine alternatives to what Bach does
here or there. On the other hand, those who are fixated on scores, who cling
to the absolute identity of a composition, who interpret its ontology literally
and strictly, and who refuse the idea of open texts will find the compositional
approach unsatisfactory or intimidating. Indeed, emphasis on the formulaic
places Bach in some great company: that of African dirge and epic singers who
similarly depend on clichs and, inevitably, of jazz musicians like Art Tatum
and Charlie Parker.
A few preliminary comments about style need to be entered here. Obviously,
Corelli and Bach utilize similarly simple models in the two compositions at which
we have looked. For example, both invest in the cadential approach from I6. Yet
there is a distinct difference between the Corelli sound and the Bach sound. How
might we specify this? One source of difference lies in the distance between model
and composition. Simply put, in Corelli, the models lie relatively close to the surface; sometimes, they constitute that surface, while at other times they can be modified by the merest of touchesan embellishment here and thereto produce that
surface. In Bach, the relationship between model (as a historical object) and composition is more varied. Some models are highly disguised while a few are hardly
hidden. The more disguised ones evince a contrapuntal depth that is not normally
found in Corelli. Bachs music is therefore heterogeneous in the way that it negotiates the surface-depth dialectic, whereas Corellis is relatively homogeneous. It is
possible that this distinction lies behind conventional perceptions of Bach as the
greater of the two composers.
CHAPTER 4
149
30. Joel Lester, J. S. Bach Teaches Us How to Compose: Four Pattern Preludes of the Well-Tempered
Clavier, College Music Symposium 38 (1998): 3346.
reinterpreted as
expressed by Bach as
and as
32
33
34
35
and as
15
16
17
18
19
10
11
10
11
and as
or
(continued)
CHAPTER 4
151
expanded into
transformed into
expressed by Bach as
12
13
14
15
(continued)
31. Allen Forte and Steven Gilbert, Introduction to Schenkerian Analysis (New York: Norton, 1982),
191192.
152
PART I
Theory
I - V Model
a'
enriched as
b'
further as
c'
enlivened by Bach as
19
20
21
22
23
24
CHAPTER 4
153
expressed by Bach as
24
25
26
27
revoiced as
enriched by Bach as
27
28
29
30
31
It should be immediately obvious that the six models, while idiomatically different, are structurally related. Indeed, models 1, 3, 4, 5, and 6 express the same kind of
harmonic sense. Only model 2 differs in its harmonic gesture. From this perspective,
the prelude goes over the same harmonic ground five out of six times. And yet, the
dynamic trajectory of the prelude does not suggest circularity; indeed, the melodic
line is shaped linearly in the form of a dynamic curve. Both features are in the prelude, suggesting that its form enshrines contradictory tendencies. We will see other
examples of the interplay between the circular and the linear in the next chapter.
Mahler, Das Lied von der Erde, Der Abschied, bars 8195
The guiding model for this brief excerpt from Das Lied (example 4.33) is the same
basic iiVI progression we encountered in Schuberts Dass sie hier gewesen.
Shown at level a in example 4.34, the progression is end-oriented in the sense that
only at the passages conclusion does clarity emerge. While Schuberts interpretation
Example 4.32. Bridges to free composition in Chopin, Prelude in C Major, op. 28,
no. 1.
Model 1
a
Model 2
a
Model 3
a
10
11
12
(continued)
CHAPTER 4
Model 5
a
Model 6
a
155
156
Theory
PART I
of the model allows the listener to predict an outcome (both immediately and in
the long term) at every moment, Mahlers inscription erases some of the larger
predictive tendency enshrined in the progression while intensifying other, more
local aspects. Of the three functional chords, the predictive capability of ii is the
most limited; only in retrospect are we able to interpret ii as a predominant chord.
The V chord, on the other hand, is highly charged at certain moments (especially
in bars 86 and 92), so it is possible to hear its potential destination as I/I or vi or
VI. And the closing I/i moment attains temporary stability as the resolution of
the previous V, but this stability is quickly dissipated as the movement moves on to
other tonal and thematic goals.
A possible bridge from the guiding model to Mahlers music is indicated at
level b of example 4.34. The white notes in the bassD, G, G, and Care of course
the roots of our iiVI/i progression. The enrichment in the upper voices, however,
Example 4.33. Mahler, Das Lied von der Erde, Der Abschied, bars 8197.
un poco pi mosso
11
sf
sf
etwas drngend
pressing on
cresc.
3
sf
87
r.h.
Pesante
12
sf
3
r.h.
sf
l.h.
sf
poco rit.
sf
92
cresc.
r.h.
96
morendo
a tempo
p3
3
3
CHAPTER 4
157
disguises the progression in more complex ways than we have seen so far, calling for a more deliberate explication. Example 4.35 offers a detailed voice-leading
graph that will enable us to examine in a bit more detail the contrapuntal means
with which Mahler sustains the guiding progression.32
Example 4.34. Bridges to free composition in Mahler, Das Lied von der Erde, Der
Abschied, bars 8195.
81
83
84
86
87
88
89
90
91
93 - 95
87
84
ii (4
3)
b7
V7
10
10
10
b7
vi #6
5
93
91
95
()
#5
b7
9
Vb9
7
#5
4
b7
8
8
(8)
b3
32. For further discussion of techniques of prolonged counterpoint in Mahler, see John Williamson,
Dissonance and Middleground Prolongation in Mahlers Later Music, in Mahler Studies, ed.
Stephen Hefling (Cambridge: Cambridge University Press, 1997), 248270; and Agawu, Prolonged
Counterpoint in Mahler, also in Mahler Studies, 217247.
158
PART I
Theory
N
2
4
3
4
4
4
CHAPTER 4
159
160
PART I
Theory
Conclusion
We have been exploring the idea of bridges to free composition through several
stylistic contexts, including Corelli, J. S. Bach, Schubert, Chopin, Mahler, and
Richard Strauss. These bridges connect the structures of an actual composition
33. Donald Mitchell, Gustav Mahler, vol. 3: Songs and Symphonies of Life and Death (London: Faber
and Faber, 1985), 344.
CHAPTER 4
161
with a set of models or proto-structures. In Schenkers formulation, these protostructures stem from the world of strict counterpoint. In pursuing the Schenkerian
idea, however, I have incorporated harmony into the models in the belief that
harmonic motivation is originary in all of the examples I have discussed. Although
we retained some skepticism about whether the bridges are ultimately secureand
this because they privilege harmony and its contrapuntal expressionwe agreed
that the idea of bridges, an idea that links a complex compositional present to
its reconstructed and simplified past, is a potent and indispensable tool for tonal
understanding.
As always with analysis, value accrues from practice, and so I have encouraged
readers to play through the examples in this chapter and observe the transformational processes. While it is possible to summarize the results of the analysesby,
for example, describing the Ursatz-like guiding ideas, their elaboration by use of
functional predominants, the role of diminutions in bringing proto-structures to
life, and the differences as well as similarities among composerly mannersit is
not necessary. A more desirable outcome would be that, having played through a
number of the constructions presented here, the student is stimulated to reciprocal
acts of reconstruction.
Still, a few issues pertaining to the general approach and its connection to the
subject of this book need to be aired. First, the generative approach, by presenting compositions as prolonged counterpoint, brings us close to speaking music
as a language. That the ability to do so is most desirable for the music analyst is,
to my mind, beyond dispute. In regard to practice, because the generative posture encourages active transformation, it is more productive than the reductive
posture, which maintains the object status of the musical work and succumbs
to instruction, to rules and regulations, and to narrow criteria of correctness.
Second and related, because the generative method is not locked into certain
pathsalternative bridges are conceivablethe analyst is called upon to exercise
improvisatory license in speculating about compositional origins. This flexibility
may not be to everyones taste; it certainly will not be to the taste of students
who take a literal view of the process. But it seems to me that whatever we can
do nowadays to foster a measure of rigorous speculation in and through music
is desirable. What such speculation guarantees may be no more than the kinds
of edification that we associate with performing, but such benefits are a crucial
supplement to word-based analytical systems, which do not always lead us to the
music itself. Third, approaching tonal composition in general and the Romantic
repertoire in particular in this way has the potential to illuminate the style of
individual composers. We glimpsed some of this in the different ways in which
diminutions are manipulated by Corelli and Bach and by Strauss and Mahler.
Fourth and finally, working with notes in this way, embellishing progressions to
yield others and playfully reconstructing a composers work, is an activity that
begins to acquire a hermetic feel. Although it can be aligned morphologically
with other analytical systems, it refuses graceful co-optation into other systems.
The fact that this is a peculiar kind of doingand not a search for facts or for
traces of the socialplaces the rationale in the realm of advantages that accrue
162
PART I
Theory
from hands-on playing. There is, then, a kind of autonomy in this kind of doing
that may not sit well with authorities who demand summarizable, positivistic
results of analysis.
If music is a language, then speaking it (fluently) is essential to understanding its production processes. It has been my task in this chapter to provide some
indication of how this might work. I will continue in this vein in the next chapter,
where I take up more directly matters of repetition.
C HA P T E R
Five
Paradigmatic Analysis
Introduction
We began our exploration of music as discourse by noting similarities and differences between music and language (chapter 1). Six criteria were then put forward
for the analysis of Romantic music based on salient, readily understandable features; these features influence individual conceptualizations of Romantic music as
meaningful, as language (chapters 2 and 3). In the fourth chapter, I took a more
interested route to musical understanding by probing this music from the inside, so
to speak. I hypothesized compositional origins as simple models that lie behind or
in the background of more complex surface configurations. This exercise brought
into view the challenge of speaking music as a language. Although no attempt
was made to establish a set of overarching, stable, context-invariant meanings, the
meaningfulness of the generative activity was noted. Meaning is doing, and doing
in that case entailed the elaboration of models, proto-structures, or prototypes.
In this chapterthe last of our theoretical chapters, the remaining four being
case studieswe will explore an approach that has already been adumbrated in
previous analyses, namely, the paradigmatic approach. Whereas the search for
bridges from strict counterpoint to free composition (chapter 4) depends on the
analysts familiarity with basic idioms of tonal composition, the paradigmatic
approach, in principle, minimizesbut by no means eliminatesdependency on
such knowledge in order to engender a less mediated view of the composition.
Thinking in terms of paradigms and syntagms essentially means thinking in terms
of repetition and succession. Under this regime, a composition is understood as a
succession of events (or units or segments) that are repeated, sometimes exactly,
other times inexactly. The associations between events and the nature of their succession guides our mode of meaning construction.
The terms paradigm and syntagm may feel unwieldy to some readers, but since
they possess some currency in certain corners of music-semiotic researchand
linguistic researchand since their connotations are readily specified, I will retain
163
164
PART I
Theory
them in this context too. A paradigm denotes a class of equivalentand therefore interchangeableobjects. A syntagm denotes a chain, a succession of objects
forming a linear sequence. For example, the harmonic progression Iii6VI constitutes a musical syntagm. Each member of the progression represents a class of
chords, and members of a class may substitute for one another. Instead of ii6, for
example, I may prefer IV or ii6/5, the assumption being that all three chords are
equivalent (in harmonic-functional terms and, presumably, also morphologically);
therefore, from a syntactic point of view, substituting one chord for another member of its class does not alter the meaning of the progression. (One should, however, not underestimate the impact in effect, affect, and semantic meaning that
such substitution engenders.)
Stated so simply, one can readily conclude that theorists and analysts have long
worked with implicit notions of paradigm and syntagm, even while applying different terminology. We have been semioticians all along! For example, the aspect
of Hugo Riemanns harmonic theory that understands harmonic function in terms
of three foundational chordal classesa tonic function, a dominant function, and
a subdominant functionfosters a paradigmatic approach to analysis. Or think of
Roland Jacksons essay on the Prelude to Tristan and Isolde, which includes a summary of the preludes leitmotivic content (see example 5.1). The six categories listed
across the top of the chartgrief and desire, glance, love philter, death, magic casket,
and deliverance-by-deathname thematic classes, while the inclusive bar numbers
listed in each column identify the spread of individual leitmotivs. Thus, glance
occurs in five passages spanning the prelude, while grief and desire occurs at the
beginning, at the climax, and at the end. The occurrences of each leitmotivic class
are directly and materially related, not based on an abstraction. While Jackson does
not describe this as a paradigmatic analysis, it is one for all intents and purposes.1
Example 5.1. Jacksons analysis of leitmotivic content in the Tristan Prelude.
Grief and
Love
Glance
Death
Desire
Philtre
1
17 17
24 25
28 28
32
32
36
36
45
55
63
74
83
(T chd.)
83
89
(& Glance)
48 48
Deliveranceby-Death
44
*A
54
63
74
(& Desire *F)
89
94
101
Magic
Casket
94
*F
100
106
1. Roland Jackson, Leitmotive and Form in the Tristan Prelude, Music Review 36 (1975): 4253.
CHAPTER 5
Paradigmatic Analysis
165
9
2
B
12
Transition
Piano
anticipation
Piano
anticipation
7
4
(+8)
10
(+8)
(+8)
Another example may be cited from Edward T. Cones analysis of the first
movement of Stravinskys Symphony of Psalms (example 5.2). Cone isolates recurring blocks of material and sets them out in the form of strata. This process of
stratification, well supported by what is known of Stravinskys working methods, enables the analyst to capture difference, affinity, continuity, and discontinuity among the works blocks of material. Unlike Johnsons leitmotifs, Cones
paradigms are presented linearly rather than vertically. Thus, stratum A in Cones
diagram, which consists of the recurring E minor Psalms chord, is displayed
horizontally as one of four paradigmatic classes (labeled A, X, B, and C, respectively). Cone explains and justifies the basic criteria for his interpretation. Without entering into the details, we can see at a glance the workings of a paradigmatic
impulse.
The connotations of paradigm and syntagm are numerous, and not all writers
take special care to differentiate them. Paradigm is affiliated with model, exemplar,
archetype, template, typical instance, precedent, and so on, while syntagm is affiliated with ordering, disposing, placing things together, arranging things in sequence,
combining units, and linearity.2 My own intent here is not to narrow the semantic
field down to a specific technical usage, but to retain a broad sense of both terms
in order to convey the considerable extent to which traditional music analysis, by
investing in notions of repetition and the association between repeated units, has
always drawn implicitly on the descriptive domains of paradigm and syntagm.
In the practice of twentieth-century music analysis, the paradigmatic method
is associated with musical semiologists and has been set out didactically in various
writings by Ruwet, Lidov, Nattiez, Dunsby, Monelle, and Ayrey, among others.3 Its
most noted applicationsas a methodhave been to repertoires the premises of
2. See Oxford English Dictionary, 3rd ed. (Oxford: Oxford University Press, 2007).
3. For a helpful orientation to the field of musical semiotics up to the early 1990s, see Monelle, Linguistics and Semiotics in Music. Among more recent writings in English, the following two volumes
provide some indication of the range of activity in the field: Musical Semiotics in Growth, ed. Eero
Tarasti (Bloomington: Indiana University Press, 1996); and Musical Semiotics Revisited, ed. Eero
Tarasti (Helsinki: International Semiotics Institute, 2003).
166
PART I
Theory
whose languages have not been fully stabilized. Ruwet, for example, based one of
his demonstrations on medieval monodies, while Nattiez chose solo flute pieces
by Debussy and Varse for extensive exegesis. Craig Ayrey and Marcel Guerstin
have pursued the Debussy repertoire furthera sign, perhaps, that this particular language or idiolect presents peculiar analytical challenges, being neither
straightforwardly tonal (like the chromatically enriched languages of Brahms,
Mahler, or Wolf) nor decidedly atonal (like Webern). A handful of attempts
aside,4 the paradigmatic method has not been applied extensively to eighteenthand nineteenth-century music. The reason, presumably, is that these collective
repertoires come freighted with so much conventional meaning that analysis that
ignores such freighteven as a foilwould seem impoverished from the start.
By privileging repetition and its associations, the paradigmatic method fosters a less knowing stance in analysis; it encourages us to adopt a strategic navet
and to downplaywithout pretending to be able to eliminate entirelysome of
the a priori concerns that one normally brings to the task. The questions immediately arise: which concerns should we pretend to forget, which understandings should we (temporarily) unlearn, and of which features should we feign
ignorance? Answers to these questions are to some extent a matter of choice
and context and may involve the basic parameters of tonal music: rhythm, timbre, melodic shape, form, and harmonic succession. In seeking to promote an
understanding of music as discourse, I am especially interested in dispensing
temporarilywith aspects of conventional form. I want to place at a distance
notions such as sonata form, rondo form, binary and ternary forms, and reckon
insteador at least initiallywith the traces left by the work of repetition. It is
true that different analysts use different signifiers to establish a works fidelity
to a particular formal template, and so the pertinence of the category form will
vary from one analytical context to the next. Nevertheless, by denying an a priori
privilege to such conventional shapes, the analyst may well hear (familiar) works
freshly. For, despite repeated claims that musical forms are not fixed but flexible,
that they are not molds into which material is poured but shapes resulting from
the tendency of the material (Tovey and Rosen often make these points), many
students still treat sonata and rondo forms as prescribed, as possessing certain
distinctive features that must be unearthed in analysis. When such features are
found, the work is regarded as normal; if the expected features are not there,
or if they are somewhat disguised, a deformation is said to have occurred.5 A
4. See, for example, Patrick McCreless, Syntagmatics and Paradigmatics: Some Implications for the
Analysis of Chromaticism in Tonal Music, Music Theory Spectrum 13 (1991): 147178; and Craig
Ayrey, Universe of Particulars: Subotnik, Deconstruction, and Chopin, Music Analysis 17 (1998):
339381.
5. I use the word deformation advisedly. See the comprehensive new sonata theory by James
Hepokoski and Warren Darcy, Elements of Sonata Theory: Norms, Types, and Deformations in the
Late-Eighteenth-Century Sonata (Oxford: Oxford University Press, 2006). For a good critique, see
Julian Horton, Bruckners Symphonies and Sonata Deformation Theory, Journal of the Society for
Musicology in Ireland 1 (20052006): 517.
CHAPTER 5
Paradigmatic Analysis
167
6. For an early recognition, see Richard Cohn and Douglas Dempster, Hierarchical Unity, Plural
Unities: Toward a Reconciliation, in Disciplining Music: Musicology and Its Canons, ed. Catherine
Bergeron and Philip Bohlman (Chicago: University of Chicago Press, 1992), 156181; see also
Eugene Narmour, The Analysis and Cognition of Basic Melodic Structures: The ImplicationRealization Model (Chicago: University of Chicago Press, 1990).
168
PART I
Theory
Turning now to God Save the King, let us begin by using literal pitch identity as a criterion in associating its elements. Example 5.4 sets out the result
graphically. The 16 attack points are then summarized in a paradigmatic chart to
the right of the graphic presentation. What kinds of insight does this proceeding
make possible?
As unpromising as patterns of literal pitch retention might seem, this exercise
is nevertheless valuable because it displays the works strategy in terms of entities
that are repeated, including when, how often, and the rate at which new events
appear. (Critics who refuse to get their feet wet because they find an analytical
premise intuitively unsatisfying often miss out on certain valuable insights that
7. See Agawu, The Challenge of Musical Semiotics, 138160. My own analysis was preceded by that
of Jonathan Dunsby and Arnold Whittall in Music Analysis in Theory and Practice (London: Faber,
1988), 223225. See also the analysis of pattern and grammar by David Lidov in his Elements of
Semiotics (New York: St. Martins, 1999), 163170.
CHAPTER 5
Paradigmatic Analysis
169
Example 5.4. Paradigmatic structure of God Save the King based on pitch identity.
Units
Summary
1
2
5
4
7
8 9
10
11
12 13
14
15
16
Totals
8
3
6
3 1
10
11
12
14
13
15
16
emerge later; until you have worked through the analytical proceeding, you dont
really know what it can accomplish.) The horizontal succession 234, for example, describes the longest chain of new events in the work. This occurs close to
the beginning of the work. The vertical succession 125 (first column) shows the
predominance of the opening pitch in these opening measures. Strategically, it is
as if we return to the opening pitch to launch a set of departures. First, 1 is presented, then 234 follow, and finally 567 complete this phase of the strategy,
where the initial members of each group (1, 2, and 5) are equivalent. (This interpretation is based strictly on the recurrences of the pitch F and not on its function
nor the structure of the phrase.) A similar strategy links the group of units 17 to
1216. In the latter, units 1213 lead off, followed by 1415, and concluded by 16,
whereagainthe initiating 12, 14, and 16 are identical.
170
PART I
Theory
CHAPTER 5
Paradigmatic Analysis
171
single notes called events, but into groups of notes coinciding with notated bars.
Example 5.5 thus incorporates contour (itself an index of minimal action) as a
criterion. Units 1 and 3 rise by step, while units 4 and 5 descend through a third.
Since these 4 bars account for two-thirds of the work, it is not indefensible to let
these features guide a segmentation. Again, we can develop our narratives of both
paradigm and syntagm on this basis. As example 5.5 suggests, we begin with a pattern, follow it with a contrasting one, return to the first (only now at a higher pitch
level), continue with a new pattern, repeat this down a step, and conclude with a
final stationary unit. The contiguity of units 45 opposes the interruption of units
13 by 2 and leads us to imagine that, in the drive toward closure, saying things
again and again helps to convey the coming end.
Example 5.5. Paradigmatic structure of God Save the King based on melodic
contour.
1
Summary
1 2
3
4
5 6
3
Example 5.6. Paradigmatic structure of God Save the King based on rhythmic
patterns.
1
Summary
1
3
5
3
2
4
6
Listeners for whom rhythmic coherence considered apart from pitch behavior
is more dominant in this work will prefer a slightly different segmentation, the
one given in example 5.6. Here, the three paradigms are determined by a rhythmic
equivalence whereby units 1, 3, and 5 belong together; 2 and 4 also belong together;
172
PART I
Theory
while 6 stands alone. In this perspective, we are immediately struck by the alternation of values, a procedural duality that we might say defines the works syntagmatic strategy. Whatever ones commitments are to the proper way of hearing
this composition, it is obvious from comparing and aligning examples 5.5 and 5.6
that, while they share certain featuressuch as the uniqueness of the concluding
F, which, incidentally, example 5.4 deniesthey also emphasize different features.
Placing ones intuitions in a larger economy of paradigmatic analyses may perform
several critical functions for listeners. It may serve to reassure them of their way of
hearing, challenge that way by pointing to other possibilities, or show how remote
is their way from those revealed in paradigmatic analyses. This exercise may also
sharpen our awareness of the role of agency in listening by contextualizing the
paths we choose to follow when listening to a particular work. We may or may not
hearor choose to hearin the same general ways, but we can understand better
what we choose or choose not to choose while engaged in the complex activity we
call listening.
So far, we have relied on the implicit tonal-harmonic orientation of God Save
the King to determine our construction of patterns. But what if we try to analyze the work in full harmonic dress, as shown in example 5.7? When, some years
ago, David Lidov presented an analysis of a Bach chorale (O Jesulein sss) to
illustrate the paradigmatic method, he labeled the chords using figured bass and
roman numerals and then, discounting modulation, constructed a paradigmatic
scheme according to which the harmonic progressions fell into three paradigms.8
The question of whether that particular chorale represented something of an
exception in terms of its harmonic organization was not definitively answered by
Lidov. Although a certain amount of invariance usually occurs between phrases of
a chorale, the issue of what is norm and what is exception requires a larger comparative sample. For our purposes, a meaningful harmonic analysis must proceed
with idioms of harmonic usage, not with individual chords. Proceeding in this
belief means taking note of harmonic gesture. The harmonic gesture at the largest
level of God Save the King (example 5.7) begins with a 2-bar open phrase (IV in
bars 12) followed by a 4-bar closed phrase (IVI in bars 3end), the latter closing
deceptively at first (in bar 4) before proceeding to a satisfying authentic close (bars
56). Obviously, the initial IV progression is contained within the following
IVI progression, and while it is theoretically possible to detach that IV from the
subsequent IVI succession in order to see an internal parallelism between the
two harmonic phrases, the more palpable motivation is of an incomplete process
brought to completion, the latter unsuccessful at first attempt, and then successful
at the second. The identities of tonic and dominant chords are, in a sense, less pertinent than the hierarchy of closings that they engender, for it is this hierarchy that
conveys the meaning of the work as a harmonic stream. Reading the harmonized
God Save the King in terms of these dynamic forces downplays the role of repetition and so produces less compelling results from a paradigmatic point of view.
8. David Lidov, Nattiezs Semiotics of Music, Canadian Journal of Research in Semiotics 5 (1977):
40. Dunsby cites this same analysis in A Hitch Hikers Guide to Semiotic Music Analysis, Music
Analysis 1 (1982): 237238.
CHAPTER 5
Paradigmatic Analysis
173
vi
ii 6
vi
ii 6
V6
4
7
5
3
vi
ii 6
7
6 5
3
V4
None of this is to suggest that the realm of the harmonic is resistant to paradigmatic structuring, for as we saw in the generative exercises in chapter 4, the existence of differentially composed harmonic idioms makes possible analyses that are
alert to repetition. The point that seems to be emerging here, however, is that the
forces that constrain harmonic expression are often so linearly charged that they
seem to undermine the vertical thinkingthe intertextsnormally conveyed
in paradigmatic analysis. But let us see how the harmonic perspective of example
5.7 can be intensified by use of chromaticism and various auxiliary notes without
erasing the basic harmonic substructure. Example 5.8, based loosely on Brahms
manner, is a reharmonization of God Save the King. For all intents and purposes,
example 5.8 is a version of example 5.7: the tune is decorated here and there in 5.8,
and the structural harmonies are more or less the same. The two versions therefore
belong to the same paradigmatic class in the same way that variations on a theme
belong in principle to a single paradigmatic class. A middleground comparison
of the two harmonized versions reinforces that identity, but what a contrast at
the foreground level. Between various chord substitutions and auxiliary interpolations, this new version (example 5.8) seems to depart in significant ways from the
previous one. It is in connection with situations like this that the paradigmatic
approach to tonal music begins to meet some difficulty. The fact that a literal surface must be understood in terms of underlying motivations means that analysis
based on internal relations without recourse to prior (or outside) texts will likely
miss an important structural and expressive dimension. One cannot, in other
words, approach the kind of musical expression contained in example 5.8 with the
navet of the empiricist because what is heard is always already embedded in what
is functional but unsounded. We will confront this challenge in the coming analyses of Mozart and Beethoven, where some reliance on conventional idioms will
be invoked in order to render the surface accessible. Analysis must find a way, even
174
PART I
Theory
at this fundamental level, to redefine the object of analysis in a way that makes this
background accessible.
Returning to the unharmonized version of God Save the King (example 5.3),
we might explore still other ways of interpreting it as a bundle of repetitions. For
example, a listener struck by the interval of a descending minor third between bars
1 and 2 might take this as an indication of potential structural importance. The gap
is between the notes G and E, the two adjacencies to the tonic, F; in other words,
the gap encompasses the gateways to the tonic. It is also unique in the piece insofar
as all other movement is stepwise. As a gap, it demands in principle to be filled, and
this is precisely what happens in the penultimate bar with the GFE succession.
But we have encountered these notes before, specifically in bar 2, immediately after
the gap was announced, where the fill proceeds in the opposite direction, EFG.
In sum, a descending gap (between bars 1 and 2) is followed by an ascending fill
(bar 2) and complemented by a descending fill (bar 5).
In this light, other relations become apparent. We hear bars 4 and 5 in close
relation because, although rhythmically different, bar 5 is a sequence of bar 4 down
a step. We can thus relate bar 4, a descending major third, to the minor third processes mentioned previously. And, if we look beyond the immediate level, we see
that, taking the first (metrically accented) beats only of bars 4, 5, and 6, we have a
descending AGF progression, the same one that we heard on a more local level
within bar 4. The larger progression in bars 46 therefore has nested within it a
smaller version of its structural self. We might hear a similar expanded progression
across bars 13, this time in ascending order: F at the beginning of bar 1, G at the
end of bar 2, and A at the beginning of bar 3. This mode of thinking, unlike the
ones explored in example 5.4, depends on patterns and diminutions. The literalism that marked early demonstrations of the paradigmatic method by Ruwet and
Nattiez was unavoidable in part because the objects of analytical attention seemed
to be made from less familiar musical languages. But for a heavily freighted tonal
language like that of God Save the King, we need an expanded basis for relating
phenomena.
These remarks about God Save the King will, I hope, have suggested possibilities for the construction of musical meaning based on criteria such as literal pitch
retention, association of pitch-based and rhythm-based patterns, diatonic and
chromatic harmonization, and an intervallic discourse determined by gaps and
fillsor some combination of these. But the monodic context of God Save the
King is relatively restricted, and some may wonder how we might proceed from
it to a more complex musical work. Answers to this question may be found in the
more methodologically oriented studies by Ruwet, Nattiez, Vacarro, and Ayrey.9
Because my own interests here are more directly analytical, I will forgo discussion
9. Nicholas Ruwet, Methods of Analysis in Musicology, trans. Mark Everist, Music Analysis 6 (1987):
1136; Jean-Jacques Nattiez, Varses Density 21.5: A Study in Semiological Analysis, trans. Anna
Barry, Music Analysis 1 (1982): 243340; Jean-Michel Vaccaro, Proposition dun analyse pour une
polyphonie vocale dux vie sicle, Revue de musicology 61 (1975): 3558; and Craig Ayrey, Debussys
Significant Connections: Metaphor and Metonymy in Analytical Method, in Theory, Analysis and
Meaning in Music, ed. Anthony Pople (Cambridge: Cambridge University Press, 1994), 127151.
CHAPTER 5
Paradigmatic Analysis
175
10. A. B. Marx, Die Lehre von der musikalischen Komposition, praktisch-theoretisch (Leipzig: Breitkopf
& Hrtel, 18371847), quoted by Schenker in Der Tonwille, 66.
11. See Schenker, Der Tonwille, 58, figure 2. There are slight differences between my representation and
Schenkers. I have kept note values in treble and bass throughout, retained Mozarts literal registers,
added a continuous figured bass between the two staves, and dispensed with roman numerals.
176
PART I
Theory
of basic motion. The first is an open (IV) progression, such as we have in the first 4
bars of the movement. (See unit 1 and its return as unit 19; see also units 5, 18, and
21. Unit 16 is also open since it expresses a V prolongation.) Column B represents
a closed (IVI) progression, such as we have in bars 58 of the movement (unit
2), although it, too, can be modified to begin on I6, ii, or IV. Column B is by far the
most populated paradigm of the three. Column C, the least populated, expresses a
linear intervallic pattern (10101010) enlivened by 98 suspensions. It occurs
only once, near the end of the so-called development section, the point of furthest
remove (in Ratners terminology).12 If, as stated earlier, the purpose of the analysis
is to establish the conditions of possibility for this particular movement, then once
we have figured out how to improvise these three kinds of tonal expressionan
open one, a closed one, and a sequential, transitional progressionusing a variety of stylistic resources, the essential analytical task has been fulfilled. The rest is
(harmless) interpretation according to the analysts chosen plot.
It is possible to tell many stories about this movement on the basis of the demonstration in examples 5.9 and 5.10. For example, virtually all of the units in the first
reprise except unit 1 are column B units. Because each unit is notionally complete
that is, it attains syntactic closurethe narrative of this first reprise may be characterized as a succession of equivalent states or small worlds. We might say therefore
that there is something circular about this first reprise and that this circular tendency,
operative on a relatively local level, counters the larger, linear dynamic conferred by
the modulatory obligations of what is, after all, a sonata-form movement.
Other stories may be fashioned around parallelism of procedure. For example, the
second reprise begins with two statements of unit 2 (units 13 and 14), now in the dominant. But this same unit 2 was heard at the end of the first reprise (units 11 and 12).
The music after the bar line thus expands the temporal scope of the music before the
bar line. Since, however, units 11 and 12 functioned as an ending (of the first reprise),
while 1314 function as a beginning (of the second reprise), their sameness at this level
reminds us of the reciprocal relationship between endings and beginnings.
We might also note the uniqueness of unit 17, which marks a turning point
in the movement. Heard by itself, it is a classic transitional unit; it denies both
the choreographed incompletion of column A units and the closed nature of the
widespread column B units. It could be argued that strategic turning points as
represented by unit 17 are most effective if they are not duplicated anywhere else
in the movement. This interpretation would thus encourage us to hear the movement as a whole in terms of a single trajectory that reaches a turning point in unit
17. Finally, we might note the prospect of an adumbrated recapitulation in the
succession of units 18 and 19. While the microrhythmic activity on the surface of
18 forms part of the sense of culmination reached in the development, and while
the onset of unit 19 is an unequivocal thematic reprise, the fact that the two units
belong to the same paradigm suggests that they are versions of each other. No
doubt, the thematic power of unit 19 establishes its signifying function within the
form, but we might also hear unit 18 as stealing some of unit 19s thunder.
12. Leonard G. Ratner, The Beethoven String Quartets: Compositional Strategies and Rhetoric (Stanford,
CA: Stanford Bookstore, 1995), 332.
CHAPTER 5
Paradigmatic Analysis
177
Example 5.9. Outer voice reduction (after Schenker) of Mozarts Piano Sonata in
A Minor, K. 310, second movement.
Andante cantabile con espressione
1
6
5
4
3
6
5
4
3
R
2
4
3
33
6 ---- 5
4 ----
8 -- 7
6 -- 5
4 --
8 ------ 7
4 ---
6
4
15
14
R
2
11
5
6 6 -4 --
4
3
6
5
6
4
7 -- 8
4 -- 3
10 --9 -- 8
10 ----- 7
9 -- 8
4 -- 3
56
8 ---- 7
6
5
6 -- 5
4 -- 3
23
4
2
6
4
5
3
4
2
6 ---------------
6
5
6
5
6 -- 5
4 -- 3
27
4 -- 3
25
26
24
78
10 ----- 7
9 -- 8
21
4 -- 3
22
7 -- 8
4 -- 3
19
4 ---- 3
20
6 -- 5
4 --
13
18
10 --9 -- 8
17
7
#
45
12
16
6
5
10
6 -- 5
4 -- 3
6 -- 5
4 -- 3
68
4 -- 3
11
22
8 ------------ U
6
4
M
4
28
178
PART I
Theory
18
21
16
(continued)
Readers will have their own stories to tell about this movement, but I hope
that the paths opened here will prove helpful for other analytical adventures. I
have suggested that, if we agree that the slow movement of Mozarts K. 310 can
be recast as an assembly of little progressionsmostly closed, independently
meaningful expressions of harmonic-contrapuntal orderthen the inner form
of the movement might be characterized as a succession of autonomous or
semiautonomous small worlds. Units follow one another, but they are not necessarily continuous with one another. If anything rules in this Mozart movement, it is discontinuous succession. Paradigmatic analysis helps to convey that
quality.
CHAPTER 5
Paradigmatic Analysis
179
3 , 4 = 22 , 23
7 = 22 , 23
9 = 25
10 = 26
11 , 12 = 27 , 28
13
14
15
24
(continued)
becomes
17
10
10
(10)
10
10
becomes
bars 21-22
bars 23-24
becomes
bars 5-8
bars 24-28
CHAPTER 5
Paradigmatic Analysis
181
The harmonic means are radically simple, and the reader is invited to realize them at the piano using example 5.11 as guide. Start by playing an archetypal
closed progression (1), expand it by incorporating a predominant sonority that
intensifies the motion to the dominant (2), truncate the progression by withholding the closing tonic while tonicizing the dominant (thus creating a desire for resolution; 3, 4), repeat the truncated progression in transposed form (5), and restore
closure using the conventional progression previously used in 2 (6).
With these resources, we are ready to improvise Chopins prelude as a harmonic stream (example 5.12). The prelude as a whole breathes in eight (often overlapping) units or segments. These are summarized below (successive bar numbers
are listed to convey the relative sizes of units):
Segment
Bars
1
2
3
4
5
6
7
8
12345
5678
9 10 11 12
12 13 14 15 16 17 18 19 20
20 21 22
22 23 24
24 25 26 27 28
29 30 31 32 33 34 35 36 37 38
We may call this the chronological order in which events unfold. But what if
we order the segments according to a logical order? Logical order is qualitative; it
is not given, but has to be postulated on the basis of certain criteria. Let us privilege
the harmonic domain and allow the paradigmatic impulse to dictate such logic. We
begin with closed progressions, placing the most expansive ones in front of the less
expansive ones. Units 8 and 4 are the most expansive, while units 1 and 3 are less
expansive. Next is a unit that attains closure but is not bounded by the tonic chord,
as the previous four units are. This is unit 7. Finally, we add units that, like 7, reach
closure but on other degrees of the scale. Two close on the dominant (2 and 5),
and one closes on the subdominant (6). The logical order thus begins with closed,
bounded units in the tonic, continues with closed unbounded units in the tonic, and
finishes with closed unbounded units on other scale degrees (first dominant, then
subdominant). In short, where the chronological form is 1 2 3 4 5 6 7 8, the logical
form is 8 4 1 3 7 2 5 6, which, following precedent, may be written as follows:
Segment
Bars
8
4
1
3
7
2
5
6
29 30 31 32 33 34 35 36 37 38
12 13 14 15 16 17 18 19 20
12345
9 10 11 12
24 25 26 27 28
5678
20 21 22
22 23 24
182
PART I
Theory
Example 5.12. Chopin, Prelude in F-sharp Major, op. 28, no. 13.
5
legato
5
13
17
(p)
(dim)
21
sostenuto
24
(continued)
CHAPTER 5
Paradigmatic Analysis
183
27
30
(
)
(riten.)
34
Many stories can be told about this prelude. First, if we ignore the global tonicizations of dominant and subdominant, then all of the units in the prelude are
closed. In that sense, a paradigmatic analysis shows a single paradigm. This stacking of the vertical dimension speaks to a certain economy of means employed
by Chopin. It also suggests the same kind of aggregative tendency we isolated in
Mozartin colloquial terms, the same thing is said again and again eight times.
Second, the most expansive closed progressions are placedstrategically, well
have to sayat the end of the prelude and in the middle (units 8 and 4, respectively). Unit 8 provides the final culmination while unit 4 serves as a preliminary
point of culmination. Third, the opening unit is in fact only a less elaborate form of
units 8 and 4; this means that the prelude begins with a closed progression of modest dimensions, which it then repeats (3) and expands not once but twice (4 and 8).
This speaks to a cumulative or organic strategy.
Again, it should be acknowledged that we can order the logic differently. For
example, we might start not with the most expansive but simply with a well-formed
cadence, then go to the more expansive ones. Or, we might treat the tonicizations
of V and IV in primary reference to the cadences in the home key. Whatever order
analysts settle on, they are obliged to explain its basis. We might also note the
affinities between generative analysis (as practiced in the previous chapter) and
184
PART I
Theory
Va
Vc
Two-voice
reduction
4
3
8
6
4
5
3
Although some of them may be self-evident, the criteria for dividing up the
movement into meaningful units (sense units, utterances, ideas, phrases, periods)
require comment. The challenge of segmentation remains at the heart of many
analytical endeavors, and while it seems more acute in relation to twentiethcentury works (as Christopher Hasty and others have shown),13 it is by no means
straightforward in Beethoven. Following the precedent set in the Mozart and
13. Christopher Hasty, Segmentation and Process in Post-Tonal Music, Music Theory Spectrum 3
(1981): 5473.
CHAPTER 5
Paradigmatic Analysis
185
Chopin analyses, I have opted for the most basic of conventional models of tonal
motion based on the IVI nexus as the principal criterion. Some support for this
proceeding may be garnered from Adorno:
To understand Beethoven means to understand tonality. It is fundamental to his
music not only as its material but as its principle, its essence: his music utters the
secret of tonality; the limitations set by tonality are his ownand at the same time
the driving force of his productivity.14
Whatever else this might mean, it engenders an idea that seems tautological at first
sight, but actually fuses a historical insight with a systematic one, namely, foundations as essences. The implication for Beethoven analysis is that the most fundamental modes and strategies of tonal definition constitute (part of) the essence of
his music. The analytical task, then, is to discover or uncover ways in which these
essences are thematized.
Based on a normative principle of departure and return, the fundamental
mode of tonal definition may be glossed as a IVI harmonic progression and subject to a variety of modes of expression and transformation.15 I could, for example,
tonicize V, prolong it by introducing a predominant element, or prolong it even
further by tonicizing the predominant. More radically, I might truncate the model
by deleting part of its frame. Thus, instead of the complete IVI chain, I may opt
for an auxiliary VI progression, in which form it still attains closure but relinquishes the security of a beginning tonic. Or, I may prefer a IV progression, in
which form the model is understood as open and incomplete. Modifications are
understood in reference to the larger, complete progression.
Stated so abstractly, these procedures sound obvious, mechanical, and uninspiring. Indeed, they belong at the most elementary level of tonal expression. And
yet, without some sense of what is possible at this level, one cannot properly appreciate the ecology (or economy, or horizon) that sustains a given composition. If
music is language, a language based in conventional codes, then it is trivial to have
to point out that, by 1800, Beethoven the pianist, improviser, composer, student
of counterpoint, and copier of other peoples scores, thoroughly spoke a language
enabled by what might be called the first utterances of the tonal system: IVI
progressions and what they make possible.
What, then, are the specific tokens of these first utterances of the tonal system,
and how are they composed out in the course of the first movement of op. 18, no.
3? Example 5.14 provides a broad orientation to the movement by summarizing
a segmentation of the movement into 40 sense units (left column) and indicating
some of the topical references that might be inferred from the sounding surfaces
14. Theodor Adorno, Beethoven: The Philosophy of Music, trans. Edmund Jephcott, ed. Rolf Tiedemann
(Stanford, CA: Stanford University Press, 1998), 49.
15. On tonal models as determinants of style, see Wintle, Corellis Tonal Models, 2969; and Agawu,.
Example 5.14. Structural units and topical references in Beethoven, op. 18, no. 3/i.
Unit
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
Bars
110
1127
2731
3135
3639
4043
4345
4557
5767
6871
7275
7682
8290
9094
94103
104110
108116
116122
123126
127128
129132
132134
134138
138142
143147
147156
158188
188198
199202
203206
207213
213221
221225
225234
235241
239247
247250
251255
255259
259269
Topical references
alla breve, galant
alla breve, cadenza, messanza figures
alla breve, stretto, galant
bourre
bourre
bourre
bourre
Sturm und Drang, brilliant style, march
brilliant style, fantasia, march
march, alla zoppa
march, alla zoppa
fanfare
fanfare
musette
musette
fantasia
alla breve
alla breve, fantasia
bourre
bourre
bourre
bourre
alla breve, furioso, Sturm und Drang
alla breve, furioso, Sturm und Drang
alla breve, furioso, Sturm und Drang
Sturm und Drang, concitato style
alla breve, ricercar style, march
brilliant style, march
march, alla zoppa
march, alla zoppa
fanfare
fanfare
musette
musette
fantasia
alla breve
march, alla zoppa
march, alla zoppa
alla breve, stretto, messanza figures
alla breve
CHAPTER 5
Paradigmatic Analysis
187
Example 5.15. Paradigmatic display of all 40 units in Beethoven, op. 18, no. 3/i.
Models
1c
1
2
1b
1a
1d
3
Exposition
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Development
19
20
21
22
23
24
25
26
27
Recapitulation
28
29
30
31
32
33
34
35
Coda
36
37
38
39
40
(right column). Example 5.15 lists the same 40 units only now in reference to a
series of tonal models and a conventional sonata-form outline. As will be immediately clear from the examples that follow, each of the 40 units belongs to one of
three models, which I have labeled 1 (with subdivisions 1a, 1b, 1c, 1d), 2, and 3.
188
Theory
PART I
Model 1 expresses a closed IVI progression, while models 2 and 3 express open
and closed IV and VI progressions, respectively. Let us explore the tonal models
in detail.16
Model 1a, shown in abstract in example 5.16 and concretely in example 5.17,
features a straightforward closed progression, Iii6/5VI, perhaps the most basic
of tonal progressions. Example 5.17 aligns all seven units affiliated with the model.
Its first occurrence is in the tonic, D major, as unit 5 in a portion of the movement
that some have labeled a bridge passage (bars 36ff.) The melodic profile of this
unit ending on scale-degree 3 rather than 1confers on it a degree of openness appropriate for a transitional function, this despite the closed harmonic form.
Conflicts like thisbetween harmonic tendency (closed) and melodic tendency
(open)are important sources of expressive effect in this style.
Example 5.16. Origins of model 1a units.
or
6
II 5
6
II 5
Other instantiations of the model are units 6 (in B minor), 19 (in B-flat major),
and 21 (in G minor), all of which display the same thematic profile. Units 7 in A
minor and 22 in G minor abbreviate the progression slightly, beginning on firstinversion rather than root-position chords. And unit 20 in B-flat major withholds
the normative continuation of the unit after the tonic extension of the models first
2 bars.
All seven units5, 6, 7, 19, 20, 21, 22belong to a single paradigmatic class.
They are harmonically equivalent, tonally disparatea factor bracketed at this
levelthematically affiliated, and melodically similar. Of course, they occur at
different moments in this sonata-form movement. Unit 5, for example, begins
the transition to the second key, but it also is imbued with a sense of closing by
virtue of its harmony. Unit 6 signals tonal departure, while unit 7 intensifi es the
sense of departure with a shift from the B minor of the previous unit to A minor.
These units thus perform different syntagmatic functions while sharing a network
of (harmonic) features. Ultimately, it is the tension between their equivalence
16. Alternative segmentations of the movement are, of course, possibleeven desirable. My interest
here, however, is in the plausibility of the units isolated, not (primarily) in the relative merits of
competing segmentations. Whenever my chosen criteria seem especially fragile, however, I offer
some explanation.
CHAPTER 5
Paradigmatic Analysis
189
5
3
6
5
36
40
123
21
127
129
6
5
6
!5
43
20
7
6
19
6
5
3
6
5
6
5
22
132
190
PART I
Theory
6
5
4
2
6
5
27
4
31
15
3
4
2
#6
7
#
94
3
34
4
2
4
2
#6
7
#
4
2
225
14
90
33
221
17. Eduard Hanslick, Vom Musikalisch-Schnen [On the Musically Beautiful], trans. Martin Cooper, in
Music in European Thought 18511912, ed. Bojan Bujic (Cambridge: Cambridge University Press,
1988), 19; Roman Jakobson, Language in Relation to Other Communication Systems, in Jakobson, Selected Writings, vol. 2 (The Hague: Mouton, 1971), 704705, adapted in Agawu, Playing with
Signs, 5179; and Lawrence M. Zbikowski, Musical Communication in the Eighteenth Century,
in Communication in Eighteenth-Century Music, ed. Danuta Mirka and Kofi Agawu (Cambridge:
Cambridge University Press, 2008).
CHAPTER 5
Paradigmatic Analysis
191
authentic cadence. Example 5.19 shows six passages totaling 42 bars that express this
model. First is unit 3, followed immediately by a registral variant, unit 4. Notice how
unit 33, which recapitulates unit 14, incorporates the flattened-seventh within a walking bass pattern. The thematic profile of model 1b is more varied than that of model
1a, all of whose units belong topically to the sphere of bourre. Here, units 3 and 4
are alla breve material (that is to say, they occupy an ecclesiastical register), whereas
the others (15, 34, 14, and 33) invoke the galant style with an initial musette inflection
(this signals a secular register). Note also that units 15 and 34 exceed the normative
5-bar length of the other model 1b units. This is because I have incorporated the reiterated cadential figures that emphasize the dominant key, A major, in the exposition
(unit 15) and its rhyme, D major, in the recapitulation (unit 34). Again, remember
that all model 1b units are harmonically equivalent but thematically differentiated.
With model 1c (whose origins are displayed in example 5.20), we come
again, as it turns outto the central thematic material of the movement, the opening 10-bar alla breve and its subsequent appearances. Like models 1a and 1b, its
units (gathered in example 5.21) might be heard as tonally closed (all except 17
and 36, which end in deceptive cadences that, however, may be understood as
substitutions for authentic cadences), but its journey is a little more protracted.
Moreover, the model begins with a prefix (shown in example 5.20) that does both
thematic and harmonic work. Thematic work is evident in the recurrence of the
rising minor seventh (sometimes in arpeggiated form) throughout the movement;
harmonic work is evident in the tonicization of individual scale degrees that the
seventh facilitates as part of a dominant-seventh sonority.
Example 5.20. Origins of model 1c units.
Prfix
^3
^2
6
II5
^1
192
Theory
PART I
8
6
4
5
3
1
2
#6
5
6
5
6
5
#6
5
20
11
27
4
3
$
5
165
158
#6
5
6
!5
6
!
6- 5
6
5
182
175
17
6
5
6
5
!
8
6
6
5
6
4
4
2
5
4-3
108
36
!5
239
39
255
40
6
4
7
5
3
259
CHAPTER 5
Paradigmatic Analysis
193
erased, by the overlap between each unit and its immediate successor; this also
subtracts from the impression of closure within each unit. Indeed, the mobility of
model 1d units contributes not a little to the movements organicism.
Example 5.22. Origins of model 1d units.
^
3
^
2
^
1
^3
^2
^1
or
4 -
#6
6
#4
#6
5
#6
4 - 3
#6
5
6
!5
!7
5
#
#
76
13
6
4
7
5
3
#6
4
7
5
3
82
31
7
207
32
#6
5
213
18
5
4
8
5
!7
6
5
116
8
#6
5
#6
5
#6
5
7
#
7
#
6
5
7
#
45
The most disguised of the units in example 5.23 is unit 8, a Sturm und Drang
passage within the second key area. In example 5.24, I read it as a IVI progression, the opening I being minor, its closing counterpart being in major, and the
long dominant being prolonged by a German sixth chord. Harmonically, example 5.24 is plausible, but it is the rhetorically marked threefold repetition of the
augmented sixth-to-dominant progression that contributes to the disguise. Note,
also, that in the second half of unit 8, the treble arpeggiates up a minor seventh
before beginning its descent to the tonic. The association with the opening of unit
1 (model 1c) is thus reinforced.
194
PART I
Theory
Ger.6 II
In an important sense, all of the units gathered under models 1a, 1b, 1c, and
1d do more or less the same harmonicbut not tonalwork. A certain degree
of redundancy results, and this in turn contributes a feeling of circularity to the
formal process. It is as if these 26 units, which comprise 196 out of a total 269
bars (72.86% of the movement) offer a consistent succession of small worlds. The
process is additive and circular. The self-containment and potential autonomy of
the building blocks counters the normative goal-oriented dynamic of the sonata
form.
Models 2 and 3 express IV and VI progressions, respectively (see the
abstracts in examples 5.25 and 5.28). These progressions are not syntactically
defective; rather, they are notionally incomplete. Playing through the model 2
units displayed in example 5.26 immediately makes evident a progression from a
local tonic to its dominant (units 10, 11, 29, 30, 37, 26), or from a local tonic to a
nontonic other (units 9 and 28). Unit 10, which heads model 2 units, is a 4-bar
antecedent phrasea question that might have been answered by a 4-bar consequent. The answer, however, is a transposition of this same unit from C major
into its relative minor, A minor. Thus, unit 11 simultaneously embodies contradictory qualities of question and answer at different levels of structure. Units 29 and
30 replay this drama exactly, now in F major and D minor, respectively, while unit
37, initiator of the coda, is answered by a unit that belongs to model 3 (unit 38).
Example 5.25. Origins of model 2 units.
^3
^2
^3
^2
or
Other model 2 units are only tenuously related to the model. Unit 26, for example, whose abstract is given as example 5.27, is the striking passage at the end of the
development that closes on a C-sharp major chord (where C-sharp functions as
V of F-sharp minor); it marks the point of furthest remove. Although it is shown
as a IV progression, its beginning (bars 147148) is less strongly articulated as a
phrase-structural beginning and more a part of an already unfolding process. Nevertheless, it is possible to extract a IV progression from it, the V prolonged by an
augmented-sixth chord. Units 9 and 28 are IV progressions only in a metaphorical sense; essentially, they both resist synopsis. Unit 9 begins in a stable A major
with a bass arpeggiation that dissipates its dominant-seventh over 4 bars and then,
CHAPTER 5
Paradigmatic Analysis
195
6
5
#4
2
4
3
6
4
4
2
#4
2
4
3
6
4
5
3
6
4
!2
6
!
!6
!5
4
3
#2
#4
3
6
5
4
3
#2
#4
3
!5
6
!5
#6
68
11
5
#
72
29
199
30
203
37
!5
247
9
57
28
188
26
#6
#6
#5
147
It. 6th
196
PART I
Theory
its own principles. The seams of Beethovens craft show in these moments; we are
reminded of a speaking subject. (Note, incidentally, that evidence for narrativity in
Beethoven is typically lodged in transitional sections, where the utterance is often
prose-like, as in units 9 and 28, rather than stanzaic or poetic.)
The third and last of our models reverses the process in model 2, progressing from V (sometimes preceded by a predominant sonority) to I. Th e conceptual
origins displayed in example 5.28 show a passing seventh over a dominant and a
chromaticization of that motion. Stated so abstractly, the process sounds straightforward enough, but listening to the transpositionally equivalent units 16 and 35,
for example (included in the display of model 3 units in example 5.29), suggests
that the effect may sometimes be complex. An underlying VI progression is hearable in retrospect, but because the individual chords sound one per bar, followed
in each case by loud rests, the listeners ability to subsume the entire succession
under a single prolongational span becomes difficult. Ratner refers to a series of
peremptory, disembodied chords, a play of cut against flow. These chords represent
total disorientation.18 This may be slightly overstated, but he is surely right to draw
attention to their effect. Unit 23 features a normative predominant-dominant-tonic
progression in A minor, which becomes the model for a sequence encompassing
units 24 and 25. The latter two feature 2 and 3 bars of predominant activity, before
closing on a B minor and an F-sharp minor chord, respectively.
To summarize: the first movement of op. 18, no. 3, is made from a number of
simple two-voice progressions common in the eighteenth century and embodying
the basic utterances of the tonal system. By our segmentation, there are essentially
three of these models: IVI, IV, and VI. For the complete IVI progression, we
identified four variants: model 1a with seven units, model 1b with six units, model
1c with 7 units, and model 1d with six units. For the open or IV model 2, we identified eight units, while the closing but not closed VI model 3 has six units. We
have thus heard the entire first movement of op. 18, no. 3; there are no remainders.
We have heard it, however, not in Beethovens temporal or real-time order but in
a new conceptual order.
If we refer back to example 5.15, we see the succession of models at a glance
and some of the patterns formed by the 40 units. I have also indicated affinities with the sonata form in order to facilitate an assessment of the relationship
between the paradigmatic process conveyed by repetition and the linear or syntagmatic process implicit in the sonata forms normative narrative. These data can be
interpreted in different ways. For example, model 1c, the main alla breve material,
Example 5.28. Origins of model 3 units.
becomes:
V8 - 7
becomes:
CHAPTER 5
Paradigmatic Analysis
197
6
5
!5
!6
4
6
5
6
5
9
7
#
8
7
#
9
7
#
8
7
#
104
35
6
5
235
38
251
23
134
24
138
25
6
4
#6
5
4
3
143
begins and ends the movement and also marks the onset of both the development
and the recapitulation. It acts as a fulcrum; its sevenfold occurrence may even
be read as gesturing toward rondo form. Unit 1a, the little bourre tune, occurs
only in clusters (5, 6, 7 and 19, 20, 21, 22). In this, it resembles unit 2, the opening
out IV progression. Unit 1b, the alla breve in stretto, is totally absent from the
development section. Model 3, an expanded cadence, functions like 1c in that it
occurs roughly equidistantly in the exposition, development, and recapitulation.
On another level, one could argue that the essential procedure of the movement is
198
PART I
Theory
that of variation since, in a deep sense, models 1a, 1b, 1c, and 1d are variants of the
same basic harmonic-contrapuntal progression. This is not a theme and variations
in the sense in which a profiled theme provides the basis for thematic, harmonic,
modal, and figurative exploration. Rather, variation technique is used within the
more evident sonata-form process. Obviously, then, the paradigmatic analysis can
support several different narratives.
CHAPTER 5
Paradigmatic Analysis
199
Strophe endings are less straightforward and altogether more interesting. Strophe 1 ends in E-flat minor, the modal opposite of the E-flat major that began the
song and a direct correlative of the change in sentiment from basking in nature
to admitting sadness. Brahms distributes the elements of closure so as to create a
wonderfully fluid ending which doubles in function as interlude (a pause for the
singer to take a breath and for the listener to reflect just a little on the message of
2
1
this unfolding tone poem) and as prelude to the next strophe. The singers 3
(bars 1213) sounds over a dominant pedal, so the downbeat of bar 13 attains
melodic closure but limited harmonic closure; the actual harmonic cadence comes
a bar later (in the second half of bar 14). This displacement is possible in part
because bars 1314 replay 12, only now in a modal transformation and with a
more decisive ending. In this way, the work of closing is achieved even as Brahms
lets the piano announce a new beginning by using the familiar material of the
songs inaugural motif.
Closure in strophe 2 is achieved in the wake of a melodramatic high point on
Trne (tears; bars 2930). The singer stops on scale-degree 5 (E-flat in bar 31), leaving
the pianist to complete the utterance by domesticating the 6/4 into a conventional
cadential group. The 6/4 chord in bar 31 is duly followed by a dominant-seventh in
32, complete with a 4/3 suspension, but the expected tonic resolution is withheld.
Unlike the close at the end of strophe 1 (bars 1214), this one has a heightened
indexical quality, pointing irresistibly to the beginning of another strophe.
200
PART I
Theory
The last of our closings also functions globally for the song as a whole; not
surprisingly, it is also the most elaborate of the three. The phrase containing the
previous high point on Trne (2731) is repeated (as 3943) and is immediately
superseded by a rhetorically more potent high point on the repeated word heisser
in bar 45, an F-flat chord that functions as a Neapolitan in the key of E-flat major.
And, as in strophe 1, but this time more deliberately, the singers closing line
descends to the tonic (bars 4748), achieving both harmonic and melodic closure
on the downbeat of bar 48. We are assured that this is indeed the global close. Now,
the motif that opened the work rises from the piano part (bar 48) through two
octaves, ending on a high G in the last bar. The effect of this twofold statement of
the motif is itself twofold. First, the motif here sounds like an echo, a remembered
song. Second, in traversing such a vast registral expanse in these closing 4 bars, the
motif may be heard echoing the active (vocal) registers of the song. Since, however,
it reaches a pitch that the voice never managed to attain (the singer got as far as
F-flat in bars 2122 and again in 45), this postlude may also be heard carrying on
and concluding the singers business by placing its destination in the beyond, a
realm in which meaning is pure, direct, and secure because it lacks the worldliness
of words. As always with Brahms, then, there is nothing perfunctory about the
pianists last word.
The fact that the BEFG motif was heard at the beginning of the song,
again in the middle, and finally at both the beginning and the end of the ending, fosters an association among beginnings, middles, and endings and suggests
a circularity in the formal process. It would not be entirely accurate to describe
the form of Die Mainacht as circular, however. More accurate would be to hear
competing tendencies in Brahms material. Strophic song normatively acquires its
dynamic sense from the force of repetition, which is negotiated differently by different listeners and performers. Strophic song is ultimately a paradoxical experience, for the repetition of strophes confers a static quality insofar as it denies the
possibility of change. Some listeners deal with this denial by adopting a teleological mindset and latching on to whatever narratives the song text makes possible.
A modified strophic form, on the other hand, speaks to the complexity of strophic
form by undercomplicating it, building into it a more obvious dynamic process. In
Die Mainacht, the high-point scheme allows the imposition of such a narrative
curve: D-flat in strophe 1, first F-flat and thenmore properlyE-flat in strophe
2, and a frontal F-flat in strophe 3.
I have strayed, of course, into the poetics of song by speculating on the meanings made possible through repetition and strophic organization. Without forcing
the point, I hope nevertheless that some of this digression will have reinforced a
point made earlier, namely, that there is a natural affinity between ordinary music
analysis and so-called paradigmatic analysis insofar as both are concerned on
some primal level with the repetition, variation, or affinity among units. Still, there
is much more to discover about the song from a detailed study of its melodic content. Let us see how a more explicitly paradigmatic approach can illuminate the
melodic discourse of Die Mainacht.
Example 5.31 sets out the melodic content of the entire song in 20 segments (see
the circled units), each belonging to one of two paradigms, A and B. Example 5.32
CHAPTER 5
Paradigmatic Analysis
201
then rearranges the contents of 5.31 to make explicit some of the derivations and,
in the process, to convey a sense of the relative distance between variants. Example
5.33 summarizes the two main generative ideas in two columns, A and B, making
it possible to see at a glance the distribution of the songs units. One clarification is
necessary: the mode of relating material in example 5.32 is internally referential.
That is, the generating motifs are in the piece, not abstractions based on underlying contrapuntal models originating outside the work. (The contrast with the
Beethoven analysis is noteworthy in this regard.) We are concerned entirely with
relations between segments. To say this is not, of course, to deny that some notion
of abstraction enters into the relating of segments. As always with these charts, the
story told is implicit, so these supplementary remarks will be necessarily brief.
Example 5.31. Melodic content of Die Mainacht arranged paradigmatically.
Strophe 1
Strophe 2
10
11
13
12
Strophe 3
14
16
18
15
17
19
20
From the outset, Brahms presents a melodic line that has two separate and
fundamental segments. It is these that have determined our paradigms. The first,
unit 1, the originator of paradigm A units, encompasses the first bar and a half
of the vocal part, itself based on the pianists humming in bars 12. This overall
ascending melody, rising from the depths, so to speak, carries a sense of hope (as
202
PART I
Theory
not
but 1
not
not
but 3
but 4
not
not
not
not
but 5
but 6
(continued)
Deryck Cooke might say). Although the associated harmony makes it a closed
unit, the ending on a poetic third (scale-degree 3) slightly undermines its sense
of closure.
The second or oppositional segment, unit 2 (bars 45), the originator of paradigm B units, outlines a contrasting descending contour, carrying as well a sense
of resolution. Just as the inaugural unit (1) of paradigm A went up (BEF)
and then redoubled its efforts to reach its goal (EFG), so paradigm Bs leading
unit (2) goes down (BAG) before redoubling its efforts (BGE) to reach
its goal. Each gesture is thus twofold, the second initiating the redoubling earlier
than the first.
It could be argued on a yet more abstract level that paradigms A and B units
are variants of each other, or that the initiator of paradigm B (unit 2) is a transformation of the initiator of paradigm A (unit 1). Both carry a sense of closure on
their deepest levels, although the stepwise rise at the end of unit 1 complicates its
sense of ending, just as the triadic descent at the end of unit 2 refuses the most
conventionally satisfying mode of melodic closure. Their background unity, however, makes it possible to argue that the entire song springs from a single seed.
CHAPTER 5
203
Paradigmatic Analysis
not
but 8
but 7
not
not
but 9
but 10
not
but 11
not
not
but 12
not
(
but
13
Indeed, this is a highly organic song, as I have remarked and as will be seen in
the discussion that follows, and this view is supported by a remark of Brahms
concerning his way of composing. In a statement recorded by Georg Henschel,
Brahms refers specifically to the opening of Die Mainacht. According to him,
having discovered this initial idea (unit 1 in 5.30), he could let the song sit for
months before returning to it, the implication being that retrieving it was tantamount to retrieving its potential, which was already inscribed in the myriad variants that the original made possible:
204
PART I
Theory
15
16
17
18
not
but 19
not
but 20
There is no real creating without hard work. That which you would call invention,
that is to say, a thought, an idea, is simply an inspiration from above, for which
I am not responsible, which is no merit of mine. Yes, it is a present, a gift, which
I ought even to despise until I have made it my own by right of hard work. And
there need be no hurry about that, either. It is as with the seed-corn; it germinates
unconsciously and in spite of ourselves. When I, for instance, have found the first
phrase of a song, say [he cites the opening phrase of Die Mainacht], I might shut
the book there and then go for a walk, do some other work, and perhaps not think
of it again for months. Nothing, however, is lost. If afterward I approach the subject
again, it is sure to have taken shape: I can now begin to really work it.20
And so, from the horses own mouth, we have testimony that justifies the study of
melodic progeny, organicism, and, implicitly, the paradigmatic method.
Let us continue with our analysis, referring to example 5.32 and starting with
paradigm A units. The piano melody carries implicitly the rhythmically differentiated unit 1. Unit 3 is a transposition of 1, but what should have been an initial C is
replaced by a repeated F. Unit 5, too, grows out of 1, but in a more complex way, as
shown. It retains the rhythm and overall contour of units 1 and 3 but introduces
a modal change (C-flat and D-flat replace C and D) to effect a tonicization of the
third-related G-flat major. Unit 7 begins as a direct transposition of 1 but changes
course in its last three notes and descends in the manner of paradigm B units. (At
20. George Henschel, Personal Recollections of Johannes Brahms (New York: AMS, 1978; orig. 1907), 111.
CHAPTER 5
Paradigmatic Analysis
205
a more detailed level of analysis, we hear the combination of both paradigm A and
B gestures in unit 7.) Unit 9 resembles 7, especially because of the near-identity of
the rhythm and the initial leap, although the interval of a fourth in unit 7 is augmented to a fifth in unit 9. But there is no doubting the family resemblance. Unit
12, the approach to the first high point, retains the ascending manner of paradigm
A but proceeds by step, in effect, filling in the initial fourth of unit 1, BE. Units
14 and 16, which open the third strophe, are more or less identical to 1 and 3, while
18 is identical to 12. This completes the activity within paradigm A.
The degree of recomposition in paradigm B is a little more extensive but not so
as to obscure the relations among segments. Unit 4 avoids a literal transposition of
2, as shown; in the process, it introduces a stepwise descent after the initial descent
of a third. The next derivation suggests that, while reproducing the overall manner
of units 2 and 1, unit 6 extends the durational and intervallic span of its predecessors. Unit 8 follows 1 quite closely, compressing the overall descent and incorporating the dotted rhythm introduced in unit 4. Unit 10 resembles 8 in terms
of rhythm and the concluding descent; even the dramatic diminished-seventh in
its second bar can be imagined as a continuation of the thirds initiated in unit 2.
Unit 10 may also be heard as incorporating something of the manner of paradigm
A, specifically, the stepwise ascent to the F-flat, which is inflected and transposed
from the last three notes of unit 1.
Unit 11 fills in the gaps in unit 2 (in the manner of units 4 and 6) but introduces another gap of its own at the end. Unit 13 is based on unit 4, but incorporates a key pitch, B-flat, from unit 2. Units 15 and 17 are nearly identical to 2 and
4, but for tiny rhythmic changes. Unit 19, the fallout from the climactic unit 18,
is derived from 13. Finally, unit 20 magnifies the processes in 19, extending the
initial descending arpeggio and following that with a descending stepwise line that
brings the melodic discourse to a full close.
Example 5.33 summarizes the affiliations of the units in Die Mainacht.
The basic duality of the song is evident in the two columns, A and B. The almost
Strophe 1
Column A units
1
3
5
7
9
Strophe 2
Strophe 3
12
14
16
18
Column B units
2
4
6
8
10
11
13
15
17
19
20
206
PART I
Theory
strict alternation between A units and B units is also noteworthy. Only twice
is the pattern brokenonce in the succession of units 10 and 11 (although the
affiliation between unit 10 and paradigm A units should discourage us from
making too much of this exception) and once at the very end of the song, where
the closing quality of paradigm B units is reinforced by the juxtaposition of
units 19 and 20.
Again, I do not claim that Brahms prepared analytical charts like the ones that I
have been discussing and then composed Die Mainacht from them. The challenge
of establishing the precise moments in which a composer conceived an idea and
when he inscribed that ideathe challenge, in effect, of establishing a strict chronology of the compositional process, one that would record both the written and the
unwritten texts that, together, resulted in the creation of the workshould discourage us from venturing in that direction. I claim only that the relations among the
works unitssome clear and explicit, others less clearspeak to a fertile, ever-present
instinct in Brahms to repeat and vary musical ideas and that a paradigmatic display of the outcome can be illuminating. While it is possible to recast the foregoing
analysis into a more abstract framework that can lead to the discovery of the unique
system of a work, this will take me too far afield. I will return to Brahms in a subsequent chapter to admire other aspects of this economy of relations in his work.
Conclusion
My aim in this chapter has been to introduce the paradigmatic method and to
exemplify the workings of a paradigmatic impulse in different stylistic milieus.
I began with God Save the King and explored questions of repetition, identity,
sameness, and difference, as well as harmonic continuity and discontinuity. I then
took up, in turn, discontinuity and form in a Mozart sonata movement, chronological versus logical form in a Chopin prelude, tonal models in a Beethoven quartet movement, and melodic discourse in a Brahms song. While I believe that these
analyses have usefully served their purpose, I hasten to add that there is more to
the paradigmatic method than what has been presented here. In particularand
reflecting some doubt on my part about their practical utilityI have overlooked
some of the abstract aspects of the method, for despite the intellectual arguments
that could be made in justification (including some made in these very pages), I
have not succeeded in overcoming the desire to stay close to the hearable aspects
of music. Thus, certain abstract or on paper relations that might be unveiled in
the Brahms song were overlooked. Similarly, the idea that each work is a unique
system and that a paradigmatic analysis, pursued to its logical end, can unveil the
particular and unique system of a work has not been pursued here. For me, there
is something radically contingent about the creation of tonal works, especially in
historical periods when a common musical language is spoken by many. The
idea that a unique system undergirds each of Chopins preludes, or each of the
movements of Beethovens string quartets, or every one of Brahms songs, states an
uninspiring truth about artworks while chipping away at the communal origins of
CHAPTER 5
Paradigmatic Analysis
207
musical works. But I hope that the retreat from this kind of paper rigor has been
compensated for by the redirecting of attention to the living sound.
I hope also to have shown that, the existence of different analytical plots notwithstanding, the dividing lines between the various approaches pursued in the
first part of this book are not firm but often porous, not fixed but flexible. Professionalism encourages us to put our eggs in one basket, and the desire to be rigorous compels us to set limits. But even after we have satisfied these (institutionally
motivated) intellectual desires, we remain starkly aware of what remains, of the
partiality of our achievements, of gaps between an aspect of music that we claim
to have illuminated by our specialized method and the more complex and larger
totality of lived musical experience.
PA RT I I
Analyses
C HA P T E R
Six
Liszt, Orpheus (18531854)
Although the shadows cast by words and images lie at the core of Liszts musical
imagination, his will to illustration, translation, or even suggestion rarely trumped
the will to musical sense making. For example, in rendering the Orpheus myth as a
symphonic poem or, rather, in accommodating a representation of the myth in symphonic form, Liszts way bears traces of the works poetic origins, but never is the
underlying musical logic incoherent or syntactically problematic. But what exactly is
the nature of that logic, that formal succession of ideas that enacts the discourse we
know as Liszts Orpheus? It is here that a semiotic or paradigmatic approach can prove
revealing. By strategically disinheriting a conventional formal template, a semiotic
analysis forces us to contemplate freshly the logic of sounding forms in Orpheus. The
idea is not to rid ourselves of any and all expectationsthat would be impossible,
of course. The idea, rather, is to be open-minded about the works potential formal
course. Accordingly, I will follow the lead of the previous chapter by first identifying
the works building blocks one after another. Later, I will comment on the discourse of
form and meaning that this particular disposition of blocks makes possible.1
Building Blocks
Unit 1 (bars 17)
A lone G breaks the silence. There are too many implications here to make active
speculation meaningful. We wait. We defer entirely to the composers will. Then,
the harp (our mythical hero) enters with an arpeggiation of an E-flat major chord.
1. In preparing this analysis, I found it convenient to consult a solo piano transcription of Orpheus
made by Liszts student Friedrich Spiro and apparently revised by the composer himself. The transcription was published in 1879. For details of orchestration, one should of course consult the full
score. Students should note that the numbering of bars in the Eulenberg score published in 1950 is
incorrect. Orpheus has a total of 225 bars, not 245 as in the Eulenberg score.
211
212
PART II
Analyses
These sounds seem to emanate from another world. The harp chord rationalizes
the repeated Gs: they are the third of the chord, a chord disposed in an unstable
second inversion. But the functional impulse remains to be activated. Indeed,
nothing is formed here. All is atmosphere and potentiality.
Unit 2 (bars 814)
The lone G sounds again, repeated from bars 13. This repetition invites speculation. Will the G be absorbed into an E-flat major chord as before, or will it find a
new home? We wait, but with a more active expectancy. The chord that rationalizes G is now an A7, duly delivered by the harp. Now G functions as a dissonant
seventh. Our head tone has gone from being relatively stable to being relatively
unstable. What might its fate be? If the harp chords mean more to us than spaceopening gestures, we will wonder whether they are related. Although linked by a
common G (the only common pitch between the successive three-note and fournote chords), the distance traveled in tonal terms is considerable. The chords lie
a tritone apart; in conventional terms, this is the furthest one can travel along the
circle of fifths (assuming this to be the normative regulating construct even in the
1850s). Between the sound of this diabolus in musica, the otherworldly timbre of
the harp, and the ominous knocking represented by the two Gs, we may well feel
ourselves drawn into supernatural surroundings.
Unit 3 (bars 1520)
With this third, fateful knock on the door, we are led to expect some direction,
some clarity, though not necessarily closure. Conventional gestural rhetoric recommends three as an upper limit. The first knock is the inaugural term; it is given
and must be accepted. The second reiterates the idea of the first; by refusing change,
it suggests a pattern, but withholds confirmation of what the succession means.
Finally, the third unveils the true meaning of the repetition; it confirms the intention and assures us that we did not mis-hear. (A fourth knock would risk redundancy and excess.) Clarity at last emerges in the form of a melodic idea. This will
be the main theme led by the note G. We now understand that the protagonist was
attempting to speak but kept getting interrupted. The theme is closed, descending
to 1 and sporting a cadential progression from I6. A relatively short phrase (5 bars
in length), its manner suggests an incremental or additive modus operandi. We
also begin to make sense of the tonal logic: E-flat and A lie equidistant on either
side of the main key (C); in effect, they enclose it. The main key is thus framed
tritonally although the approach to it is somewhat oblique. A certain amount of
insecurity underpins this initial expression of C major.
Unit 4 (bars 2126)
Since the beginnings of the previous unit and this one share the same chord albeit
in different positions (unit 3 opens with the C-seventh chord in 6/5 position, while
unit 4 begins with the chord in 4/2 position), we might wonder whether this unit
CHAPTER 6
Liszt
213
214
PART II
Analyses
CHAPTER 6
Liszt
215
216
PART II
Analyses
CHAPTER 6
Liszt
217
218
PART II
Analyses
CHAPTER 6
Liszt
219
220
PART II
Analyses
Form
With this first pass through Liszts Orpheus, I have identified its units or building blocks on the basis of repetition and equivalence. Each unit is more or less
clearly demarcated, although some units overlap, and while the basis of associating some may change if other criteria are invoked, the segmentation given
here confirms the intuition that Orpheus is an assembly of fragments. If we
now ask what to do with our 50 units, we can answer at two levels. The first,
more general level suggests a mode of utterance that is more speech-like than
song-like. (There is no dance here, or at least no conventional dance, unless
one counts the unpatterned movements that Orpheuss playing solicits.) As
a rule, when units follow one another as predominantly separate units, they
suggest speech mode; when they are connected, they are more likely to be in
song mode. The speech-mode orientation in Orpheus betrays its conception as
a symphonic poem, with obligations that originate outside the narrow sphere
of musical aesthetics. Another way to put this is to suggest that the illustrative,
narrative, or representational impetuswhichever it isconfers on the music
a more language-like character.
At a more detailed level, the foregoing exercise conveys the form of Orpheus
with clarity. Aligning the 50 units according to the criteria of equivalence adumbrated in the verbal description yields the design in figure 6.1.
The main difficulty with this kind of representation is that, by placing individual units in one column or another (and avoiding duplications), it denies
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
25
23
24
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
222
PART II
Analyses
affiliations with other units. But this is only a problem if one reads the material
in a given unit as an unhierarchized network of affiliations. In that case, rhythmic, periodic, harmonic, or other bases for affiliating units will be given free
rein, and each given unit will probably belong to several columns at once. But
the arrangement is not a problem if we take a pragmatic approach and adopt
a decisive view of the identities of units. In other words, if we proceed on the
assumption that each unit has a dominating characteristic, then it is that characteristic that will determine the kinds of equivalences deemed to be pertinent.
The less hierarchic approach seems to promote a more complex view of the
profile of each given unit, thus expanding the network of affiliations that is possible among units. It runs the risk, however, of treating musical dimensions as if
they were equally or at least comparably pertinent and therefore of underplaying the (perceptual or conceptual) significance of certain features. Yet, I believe
that there is often an intuitive sense of what the contextually dominant element
is, not only by virtue of the internal arrangement of musical elements, but on
the basis of what precedes or follows a given unit and its resemblance to more
conventional constructs.
As we have seen in similar analyses, several stories can be told about the
paradigmatic arrangement made above. One might be based on a simple statistical measure. Three ideas occur more frequently than others. The first is
the material based on unit 7, the neighboring figure expressed in a haunting,
implicative rhythm, which registers 15 times in figure 6.1. On this basis, we
may pronounce it the dominant idea of the movement. The second idea is the
codetta-like figure first heard as unit 18; this occurs 11 times. Third is the
main theme, heard initially as unit 3, and subsequently 7 more times. This
frequency of occurrence reflects the number of hits on our paradigmatic chart.
Had we chosen a different segmentation, we might have had different results.
Note, further, that the frequency of appearance is not perfectly matched to the
number of bars of music. Material based on unit 7 occupies 80 bars, that based
on 18 only 27 bars, and that based on 3 equals 39 bars. If we now consider
the character of each of these ideas, we note that the units based on 7 have
an open, implicative quality, serving as preparations, middles, transitions, or
simply as neutral, unsettled music. They are fragmentary in character and
thus possess a functional mobility. This is the material that Liszt uses most
extensively. Units based on the main theme occur half as much. The theme is
closed, of course, although in the segmentation given here, closure is present
at the end of each unit, thus missing out on the question-and-answer sense of
pairs of units. For example, the very first succession, units 34, may be read
not as question followed by answer but as answer followed by question. That
is, 3 closes with a tonic cadence while 4 modulates to the dominant. Had we
taken the 34 succession as an indivisible unit, we would have read the main
theme as open. But by splitting it into two, we have two closed units, although
closure in the second is valid on a local level and undermined on a larger one.
The third most frequently heard idea carries a sense of closure. Even though
it occupies only 27 bars, its presentation is marked in other ways. Then also, if
CHAPTER 6
Liszt
223
we add its occurrences to those of the main theme, we have a total of 66 bars,
which brings the material with an overall closing tendency closer to the 80-bar
mark attained by material with an open tendency.
In whatever way we choose to play with these figures, we will always be
rewarded with a view of the functional tendencies of Liszts material. And it is
these tendencies that should form the basis of any association of form. Of course,
the simple statistical measure will have to be supplemented by other considerations, one of which is placement. The main theme, for example, is introduced
early in the movement (units 36), disappears for a long while, and then returns
toward the end (3839 and 4445). The animating idea introduced in unit 7 enters
after the main theme has completed its initial work. It dominates a sizable portion of the continuation of the beginning (units 714) before being superseded.
It returns to do some prolonging work before the main theme returns (3437)
and stays toward the close of the work (units 4041 and 46). If the main theme
is roughly associated with beginning and end, the animating theme functions
within the middle and the end. The codetta theme (introduced as unit 18) dominates the middle of the work (units 1819, 2122, 2829, and 3132), lending a
strong sense of epilogue to the middle section. It returns toward the very end of
the movement (units 4749) to confer a similar sense of closure nowappropriatelyupon the works end.
The closing unit, 50, also invites different kinds of interpretation. The novelty of its chords places it immediately in a different column. By this reading,
the ending is entirely without precedent or affiliation. But I have pointed to
a sense of affiliation between unit 50, on the one hand, and units 1 and 2, on
the other. By the lights of this alternative reading, unit 50 may be placed in
the column containing units 1 and 2, so that the work ends where it began.
This particular affiliation would be the loosest of all, and yet it is supportable
from a gestural point of view. And since the key is C major, the home tonic,
the expression of tonic harmony in unit 3 comes to mind, for that was the first
composing out of what would turn out to be the main key. Again, these affiliations show that unit 50, despite its obvious novelty, is not entirely without
precedent. In this case, our paradigmatic chart does not do justice to the web
of connections.
The paradigmatic chart also sets units 1533 apart as a self-contained section.
Indeed, the lyrical theme introduced at unit 15 evinces a stability and well-formedness that are not found in the outer sections. Consider the mode of succession
of units 1524. Unit 15 begins the lyrical song, 16 prepares a broad cadence but
denies the concluding syntax (this is only the first try), and 17 achieves the actual
cadence. Unit 18 confirms what we have just heard, while 19 echoes that confirmation. Unit 19 meanwhile modifies its ending to engender another cadential
attempt, albeit in a new key. Unit 20 makes that attempt, succeeds (in bars 9192),
and is followed again by the confirming units 21 and 22. Another shift in key
leads to the third effort to close in unit 23. Its successor, 24, achieves the expected
closure, but now dispenses with the codetta idea that followed the cadences at
the end of units 17 and 20. This little drama across units 1524 unfolds with a
224
PART II
Analyses
sense of assurance and little sense of dependency. The self-containment and relative stasis confer on these units the spirit of an oasis. The idea of repeating such an
interlude could not have been predicted from earlier events, but this is precisely
what Liszt does. Thus, units 1524 are repeated more or less verbatim as 2533.
If the former provided temporary stability within a largely fragmented discourse,
the latter confirm that which demonstrated no inner need for confirmation. Of
course, we become aware of the repetition only gradually and only in retrospect,
and so the sense of redundancy is considerably mediated. At 33, matters are not
closed off as at 2324 but kept open in order to resume what we will come to know
as the process of recapitulation.
The view of form that emerges from a paradigmatic analysis recognizes repetition and return at several different levels, small and large. Some listeners will,
however, remain dissatisfied with this more open view of form, preferring to hear
Orpheus in reference to a standard form. Derek Watson, for example, writes,
Orpheus is akin to the classical slow-movement sonata without development.3
Richard Kaplan repeats this assertion: Orpheus has the sonata without development form common in slow movements, the only development takes place in
what [Charles] Rosen calls the secondary development section following the first
theme area in the recapitulation.4
Kaplan is determined to counter the image of a revolutionary Liszt who
invented an original genre (symphonic poem) that necessarily announces its
difference from existing forms. His evidence for the relevance of a sonata-form
model to Orpheus embraces external as well as internal factors. The fact that this
symphonic poem, like others, began life as an overture (it prefaced a performance
of Glucks Orfeo ed Euridice) and the fact that Liszts models for writing overtures
included works by Beethoven and Mendelssohn that use sonata form (this latter
fact, Kaplan says, is confirmed by Reicha and Czerny, both of whom taught Liszt)
lead Kaplan to search for markers of sonata form. He finds an exposition with two
key areas (C and E) and two corresponding theme groups in each area, no development, and a recapitulation in which theme Ib precedes Ia, IIa is recapitulated
first in B major and then in C major, themes Ia and IIb follow (again) in C major,
and then a closing idea and a coda round off the work.
The argument for a sonata-form interpretation is perhaps strongest in connection with the presence of two clearly articulated keys in the exposition and
the returnnot necessarily recapitulationof the themes unveiled during the
exposition. But in making a case for a sonata-form framework for Orpheus, Kaplan
is forced to enter numerous qualifications or simply contradictory statements. For
example, he says that three-part organization is the most consistent and logical explanation of large-scale form in [Faust Symphony/1, Prometheus, Les Preludes, Tasso, and Orpheus]. But Orpheus lacks one of these three parts, the central
development section. He finds many of [Liszts] usages . . . unconventional; the
CHAPTER 6
Liszt
225
introduction is very brief ; the repetition of the big lyrical theme (Kaplans theme
II) is non-standard; the reordering of themes in the recapitulation is subtle; the
use of themes in dual roles is unusual; there are several departures from classical tradition in the handling of tonality; and recapitulating the second theme
follows an unusual key scheme. These qualifications do not inspire confidence
in the pertinence of a sonata-form model. Granted, Kaplans study is of several
symphonic poems plus the opening movement of the Faust Symphony, and it is
possible that sonata form is more overtly manifested there than in Orpheus. Nevertheless, hearing Orpheus as a single-movement sonata structure is, in my view,
deeply problematic.
Listeners are more likely to be guided by the musical ideas themselves and their
conventional and contextual tendencies. The drama of Orpheus is an immediate
one: ideas sport overt values; return and repetition guarantee their meaningfulness. Attending to this drama means attending to a less directed or less prescribed
formal process; and the temporal feel is less linearly charged. Liszt marks time,
looks backward, even sideways. Succession rather than progression conveys the
pull of the form. Gathering these constituents into a purposeful exposition and
recapitulation obscures the additive view of form that our paradigmatic analysis
promotes.
An analysis altogether more satisfactory than Kaplans is provided by Rainer
Kleinertz.5 Kleinertzs main interest is the possible influence of Liszt on Wagner,
not from the oft-remarked harmonic point of view, but as revealed in formal procedures. Wagner himself had been completely taken with Orpheus, declaring it
in 1856 to be a totally unique masterwork of the highest perfection and one of
the most beautiful, most perfect, indeed most incomparable tone poems, and still
later (in 1875) as a restrained orchestral piece . . . to which I have always accorded a
special place of honor among Liszts compositions.6 Although Wagner appears to
have been especially taken with Liszts approach to form, especially his jettisoning
of traditional form and replacing it with something new, Kleinertzs essay concretizes the earlier intuitions in the form of an analysis.
From the point of view of the analysis presented earlier, the main interest in
Kleinertzs study stems from his interpretation of Orpheus as unfolding a set of
formal units. His chart of the overall form contains 18 units (all of the principal boundaries of his units coincide with those of my units, but his segmentation
takes in a larger hierarchic level than mine does). Noting (in direct contradiction
to Kaplan) that there is no resemblance to sonata form7 and that Orpheus has
no architectonic form,8 he argues instead that the whole piece seems to move
slowly but surely and regularly along a chain of small units, sometimes identical,
5. Rainer Kleinertz,.
6. Quoted in Kleinertz, Liszt, Wagner, and Unfolding Form, 234240.
7. Kleinertz, Liszt, Wagner, and Unfolding Form, 234.
8. Kleinertz, Liszt, Wagner, and Unfolding Form, 237.
226
PART II
Analyses
Meaning
Because they originate in a verbal narrative or plot or are earmarked for illustrative
work, symphonic poems have a twofold task: to make musical sense and to create
the conditions that allow listeners so disposed to associate some musical features
with extramusical ones. Both tasks subtend a belief about musical meaning. The
first is based in the coherence of meanings made possible by musical language and
syntax; the second is based on the prospect of translating that language or drawing
analogies between it and formations in other dynamic systems.
Although Orpheus resists a reading as a continuously illustrative work, certain
features encourage speculation about its illustrative potential. I mentioned some
of these in my survey of its building blocks. The disposition of the opening harp
chords and the lone G that announces them mimic the making of form out of
formlessness; they identify a mythical figure, our musician/protagonist, and they
convey a sense of expectancy. Even the tonal distance in these opening bars could
be interpreted as signifying the remoteness of the world that Liszt seeks to conjure.
The main theme, delivered by strings, carries a sense of the journeys beginning;
we will follow the contours of a changing landscape through its coming transformations. The ominous neighbor-note idea, with its sly, chromatic supplement,
is permanently marked as tendering a promise, pushing the narrative forward to
some unspecified goal. The beautiful lyrical theme in E major announces a new
9.
10.
11.
12.
13.
CHAPTER 6
Liszt
227
character or, rather, a new incarnation of the previous character. Unfolding deliberately, complete in profile, and burdened with closure, it provides an extended
tonal contrast that may well suggest the outdoors. The large-scale repetition of this
passage signifies a desire on the protagonists part to remain within this world, but
the return of the main theme is harder to interpret as an element of plot. Because
the associations are presumably fixed from the beginning and because verbal or
dramatic plots do not typically retrace their steps in the way musical plots do, the
fact of return forces the interpreter into a banal mode: hearing again, refusing to
go forward, recreating a lost world. Finally, the concluding magic chordsmysterious chords, in Kleinertzs descriptionmay well signify Orpheus in the underworld. They connote distance as well as familiarityfamiliarity stemming from
their affiliation with the works opening, with its floating chords marked destination unknown. We are always wiser in retrospect.
Listeners who choose to ignore these connotations, or who reject them on
account of their contingency, will not thereby find themselves bored, for everything from the thematic transformations through the formal accumulation of units
is there to challenge them and guarantee an engaged listening. But if we ask, how
do these competing perspectives promote a view of musical meaning? it becomes
apparent that the interpretive task poses different sorts of challenges. It is in a sense
easy to claim that the magic chords at the end of Orpheus signify something different or otherworldly, or that the big lyrical theme signifies a feminine world, or
that the harp is associated with the heavens, or even that chromaticism engenders
trouble, slyness, or instability. These sorts of readings may be supported by historical and systematic factors. They provide ready access to meaning, especially that
of the associative or extrinsic variety. But they are not thereby lacking a dimension
of intrinsic meaning, for the remoteness of the closing chords, for example, stems
more fundamentally from the absence of the regular sorts of semitonal logic that
we have heard throughout Orpheus. In other wordsand recognizing the fragility
of the distinctionintrinsic meaning is what makes extrinsic meaning possible.
It is within the intrinsic realm that musics language is formed. Its meanings are
therefore both structural and rhetorical at birth. They are, in that sense, prior to
those of extrinsic associationism. They may signify multiply or neutrally, but their
semantic fields are not infinite in the way that unanchored extrinsic meanings can
be. If, therefore, we opt for intrinsic meanings, we are expressing an ideological
bias about their priority, a priority that is not based entirely on origins but ultimately on the practical value of music making. This chapter has explored a mode
of analysis that seeks to capture some of that value.
C HA P T E R
Seven
How might we frame an analysis of music as discourse for works whose thematic
surfaces are not overtly or topically differentiated, the boundaries of whose building blocks seem porous and fluid, and whose tendencies toward continuity override those toward discontinuity? Two works by Brahms will enable us to sketch
some answers to these questions: the second of his op. 119 intermezzi and the
second movement of the First Symphony. Unlike Liszts Orpheus, whose building blocks are well demarcated, Brahms piano piece has a contrapuntally dense
texture and a subtle, continuous periodicity marked by a greater sense of throughcomposition. And in the symphonic movement, although utterances are often set
apart temporally, the material is of a single origin and the overall manner is deeply
organic. Dependency between adjacent units is marked. Nevertheless, each work
must breathe and deliver its message in meaningful chunks; each is thus amenable
to the kind of analysis that I have been developing. In addition to performing the
basic tasks of isolating such chunks and commenting on their affiliations, I hope
to shed light on Brahms procedures in general, as well as on the specific strategies
employed in these two works.
230
PART II
Analyses
A paradigmatic analysis conveys this division of labor by registering a striking difference in population of units: 22 in the A section, 19 in the A' section and a mere
8 in the B section.
Anyone who plays through this intermezzo will be struck by the constant
presence of its main idea. A brief demonstration of the structural origins of this
idea will be helpful in conveying the nature of Brahms harmonically grounded
counterpoint. At level a in example 7.1 is a simple closed progression in E minor,
the sort that functions in a comparable background capacity in works by Corelli,
Bach, Mozart, Beethoven, and Mendelssohnin short, a familiar motivating
progression for tonal expression. The progression may be decorated as shown at
level b. Level c withholds the closing chord, transforming the basic idea into an
incomplete utterance that can then be yoked to adjacent repetitions of itself. Level
d shows how Brahms opening enriches and personalizes the progression using
temporal displacements between treble and bass. This, then, is the kind of thinking that lies behind the material of the work.
In preparing a reference text for analysis (example 7.2), I have essentialized
the entire intermezzo as a two-voice stream in order to simplify matters. (A few
irresistible harmonies are included in the middle section, however.) Example 7.2
Example 7.1. Origins of the main idea in Brahms, Intermezzo in E Minor, op. 119,
no. 2.
p s.v. e dolce
CHAPTER 7
Brahms
231
Bars:
10
10
14
18
16
17
20
22
19
20
26
12
14
15
18
24
11
12
13
16
21
28
22
30
23
24
E - pedal
32
36
34
25
40
26
42
27
E - pedal
44
48
50
28
56
59
68
66
32
70
36
1.
62
31
30
2.
52
29
37
72
39
80
42
93
40
41
44
45
89
86
47
35
81
43
85
34
74
38
76
46
33
91
48
96
97
49
100 E - pedal
should thus be read as a kind of shorthand for the piece, a sketch whose indispensable supplement is the work itself. Units are marked by a broken vertical line and
numbered at the top of each stave. Bar numbers are indicated beneath each stave.
232
PART II
Analyses
Unit 1 (bar 1)
A tentative utterance progresses from tonic to dominant and exposes the main
motif of the work. This idea will not only dominate the outer sections but will
remain in our consciousness in the middle section as well. The intermezzo thus
approaches the condition of a monothematic work. This building block is open,
implyingindeed, demandingimmediate continuation.
Unit 2 (bars 12)
Overlapping with the preceding unit, this one is essentially a repetition, but the
melodic gesture concludes differentlywith an exclamation (BD) that suggests
a mini-crisis. Shall we turn around and start again, or go onand if so, where?
Unit 3 (bars 23)
This is the same as unit 1. Brahms chose to start again.
Unit 4 (bars 37)
Beginning like 1 (and 3), this unit replaces D-sharp with D-natural on the downbeat
of bar 5, hints at G major, but immediately veers off by means of a deceptive move
(bass DD-sharp) toward B major, the home keys major dominant. Arrival on B
major recalls unit 2, but here the utterance is louder and rhetorically heightened.
Unit 5 (bars 79)
Lingering on the dominant, this unit extends the dominant of the dominant just
triumphantly attained, but it effects a modal reorientation toward the minor. The
main motive continues to lead here.
Unit 6 (bar 9)
This is the same as unit 1.
Unit 7 (bars 910)
This repeats the material from unit 2.
Unit 8 (bars 1011)
This is the same as 1 (and 3 and 6).
Unit 9 (bars 1112)
Five chromatic steps (B to E) provide a link to A minor from E minor. In this transitional unit, the E-minor triad is turned into major and, with an added seventh,
functions as V7 of A minor to set up the next unit.
CHAPTER 7
Brahms
233
234
PART II
Analyses
CHAPTER 7
Brahms
235
236
PART II
Analyses
by this last incorporation of G-natural, which recalls the join between the A and B
sections (bars 3335). The energy in the main motive is neutralized somewhat.
Unit 31 (bars 7172)
This unit is the equivalent of unit 1. As typically happens in ternary structures
like this, the reprise (starting with the upbeat to bar 72) reproduces the content
of the first A section with slight modifications. My comments below will mainly
acknowledge the parallels between the two sections.
Unit 32 (bars 7273)
This is the same as unit 2.
Unit 33 (bars 7374)
This is equivalent to unit 3.
Unit 34 (bars 7475)
This unit proceeds as if recapitulating unit 9, but it curtails its upward chromatic
melodic rise after only three steps.
Unit 35 (bars 7576)
This is the proper equivalent of unit 9, differently harmonized, however.
Unit 36 (bars 7677)
This unit is a rhythmic variant of unit 10. The process of rhythmic revision replaces
the earlier triplets with eighths and sixteenths, bringing this material more in line
with the original rhythm of the main theme. We may make an analogy between
this process and the tonic appropriation of tonally other material during a sonataform recapitulation.
Unit 37 (bars 7778)
Equivalent to 11, this unit is also heard as an immediate repeat of 36.
Unit 38 (bars 7981)
This is the equivalent of 12, with rhythmic variation.
Unit 39 (bars 8182)
This unit is equivalent to 13.
CHAPTER 7
Brahms
237
238
Analyses
PART II
Example 7.3. Paradigmatic chart of the units in Brahms, op. 119, no. 2.
1
3
6
10
12
11
13
14
15
17
16
18
19
20
22
21
23
24
25
26
28
31
27
29
30
32
33
34
35
36
38
37
39
41
40
42
43
44
45
46
47
48
49
CHAPTER 7
Brahms
239
gradually while the main idea remains as a constant but variable presence. Novelty
is charted by the following succession: unit 2; then units 45; then 9; then 12; then
14; then 1719; and finally 22. The degree of compositional control is noteworthy.
A similar strategy is evident in the middle section, where 23, 25, and 28 serve as
springboards that enable departures within the span of units encompassing this
section (2330).
A third feature conveyed in the paradigmatic analysis is the pacing of utterances. In the B section, for example, there are only 8 units, compared to 41 in
the combined A sections. This conveys something of the difference in the kinds
and qualities of the utterances. Much is said in the A and A' sections; there is a
greater sense of articulation and rearticulation in these sections. The speech
mode predominates. Fewer words are spoken in the B section, where the song
mode dominates. As narration, the intermezzo advances a self-conscious telling in
the A section, pauses to reflect and sing innerly in the B section, and returns to
the mode of the A section in the A' section, incorporating a touch of reminiscence
at the very end.
The paradigmatic analysis, in short, makes it possible to advance descriptive
narratives that convey the character of the work. In principle, these narratives do
not rely on information from outside the work, except for a generalized sense of
convention and expectation drawn from the psychology of tonal expression. They
are bearers, therefore, of something like purely musical meaning. Some listeners
may choose to invest in other sorts of meaning, of course; the fact, for example,
that this is a late work may engender speculation about late style: conciseness,
minimalism, essence, subtlety, or economy as opposed to flamboyance, extravagance, determination, and explicitness. The title Intermezzo might suggest an
in-betweenness or transience. I am less concerned with these sorts of meanings
than with those that emerge from purely musical considerations. The kinds of
meaning that ostensibly formalist exercises like the foregoing make possible have
not, I feel, been sufficiently acknowledged as what they are: legitimate modes of
meaning formation. They do not represent a retreat from the exploration of meaning. As I have tried to indicate, and as the following analysis of the slow movement
of the First Symphony will further attest, formalist-derived meanings are enabling
precisely because they bring us in touch with the naked musical elements as sites
of possibility. Reticence about crass specification of verbal meaning is not an evasion, nor is it a deficit. On the contrary, it is a strategic attempt to enable a plurality
of inference by postponing early foreclosure. Boundaries, not barriers, are what we
need in order to stimulate inquiry into musical meaning. Indeed, not all such acts
of inferring are appropriate for public consumption.
240
PART II
Analyses
CHAPTER 7
Brahms
241
IV. Crucial to the meaning of this phrase is the retention of the pitch G-sharp (3)
in the melody. Although we hear the phrase as somewhat self-contained, we also
understand that it remains in a suspended state; it remains incomplete. Conventionally, G-sharps ultimate destination should be E (1). We carry this expectation forward. The difference in effect between the two framing tonic chords
(with 3 in the top voice) reminds us of the role of context in shaping musical
meanings. The 3 in bar 1 is a point of departure; the 3 in bar 2 is a point of
arrival. A return to the point from which we embarked on our journey may suggest a turnaroundwe have not gone anywhere yet, not realized our desire for
closure. So, although the progression in unit 1 is closed, its framing moments
carry a differential degree of stability in the work: the second 3 is weaker than
the opening 3.
Unit 2 (bars 3142)
This 2-bar phrase answers the previous one directly. The sense of an answer is
signaled by parallel phrase structure. But to gloss the succession of 2-bar phrases
as question and answer is already to point to some of the complexities of analyzing musical meaning. These 2 bars differ from the preceding 2-bar unit insofar
as they are oriented entirely to the dominant. Unit 1 progressed from I through
V and back to I; this one prolongs V through a secondary-dominant prefix. To say
that unit 2 answers 1, therefore, is too simple. Musical tendencies of question and
answer are complexly distributed and more than a matter of succession. The close
of unit 2 on the dominant tells us that this particular answer is, at best, provisional.
The answer itself closes with a question, a pointer to more business ahead. Unit 2
is thus simultaneously answer (by virtue of phrase isomorphism and placement)
and question (by virtue of tonal tendency).
A number of oppositions are introduced in this succession of units 1 and 2:
diatonic versus chromatic, closed versus open, disjunct versus conjunct motion,
major versus minor (conveyed most poignantly in the contrast between G-sharp
in unit 1 and G-natural in unit 2), and active versus less active rates of harmonic
change. The more we probe this juxtaposition, the more we realize that the overall
procedure of units 1 and 2 is not a causal, responsorial 2 + 2 gesture, but something
less directed, less urgent in its resultant cumulative profile. When we think of classical 4-bar phrases divided into 2 and 2, we think, at one extreme, of clearly demarcated subphrases, the second of which literally answers the first. But the degree to
which the subphrases are independent or autonomous varies from situation to
situation. Nor is this a feature that can always be determined abstractly; often, it
is the force of context that underlines or undermines the autonomy of subunits.
In Brahms opening, the horns enter with a threefold repeated note, B (bar 2), to
link the two phrases. These Bs function first as an echo of what has gone before, as
unobtrusive harmonic filler that enhances the warmth of tonic harmony, and as
elements embedded spatially in the middle of the sonority, not at its extremities,
where they are likely to draw attention to themselves. The three Bs not only point
backward, they point forward as well. They prepare unit 2 by what will emerge
242
PART II
Analyses
CHAPTER 7
Brahms
243
244
PART II
Analyses
Then, revoicing the lower parts of unit 13, Brahms enhances their essential identity. These units are the first two of a threefold gesture that culminates in a high
point on the downbeat of bar 22 (unit 14) with a high B. As mentioned earlier, this
moment of culmination also features a return of the melody from unit 1 as a bass
voice, providing a spectacular sense of textural fusion at a rhetorically superlative
moment.
Units 15 (bars 233251), 16 (bars 252272)
High points invariably bring on the end. The downbeat of bar 22 carries a promise of closure. Unit 15 reclaims the material of unit 2, but instead of advancing to
a half-close as in the comparable gesture in bar 12, it simply abandons the first
attempt at cadence and proceeds to a second, successful attempt (16). The means
are direct: Brahms brings back material we have heard twice previously (bars 34
and 1516), withholds its continuation, and finally allows it. The anacruses that
shaped previous occurrences are present here too, though they now take the form
of a descending triad (bars 23 and 25). The long-awaited cadence in bars 2627 is
engineered by this figure. Looking back, we now see how Brahms has led us gradually but inexorably to this point.
Figure 7.1 Paradigmatic arrangement of units 116 in Brahms Symphony
No.1/ii.
1
4
5
6
7
8
9
10
11
12
13
14
15
16
Let us review the A section from the point of view of paradigmatic affiliation
(figure 7.1). The strategy is immediately apparent. Narrating rather than associating seems to be the process. We begin with a sequence of four sufficiently differentiated ideas (units 14). Then, we dwell on the fourth one for a bit (5, 6), add a new
idea (7), which we play with for a while (8, 9). Yet another new idea is introduced
(10). Its talewhich, in this interpretation, embodies its essential identityis
immediately repeated (11). The last of our new ideas follows (12) and is repeated
CHAPTER 7
Brahms
245
twice in progressively modified form (13 and 14). Finally, by way of conclusion,
we return to an earlier idea, unit 2, for a twofold iteration (15 and 16). Overall,
the process is incremental and gradual. Brahms music unfolds in the manner of
a speech discourse, complete with asymmetrical groupings and subtle periodicity.
The idea of musical prose captures this process perfectly.
246
PART II
Analyses
imitation, this extension of temporal units is Brahms way of meeting the normative need for contrast and development in this portion of the movement.
Units 23 (bars 491501), 24 (bars 501503), 25 (bars 511521), 26 (bars 521532)
Units 20, 21, and 22 were grouped together on account of their morphological similarities. What follows in the next four units is a cadential gesture that leads us to
expect a close in D-flat major, the enharmonic relative of C-sharp. Brahms makes
much of the gesture of announcing and then withholding a cadence. Thus, unit 23
prepares a cadence, but the onset of 24, while syntactically conjunct, dissolves the
desire for a cadence by replaying part of the melody that dominated units 20, 21,
and 22. Again, 25 repeats 23, evoking the same expectation, but 26 avoids the 6/4
of unit 24 and sequences up a step from 25, at the same time extending the unit
length. The cumulative effect is an intensification of the desire for cadence.
Unit 27 (bars 532553)
We reach a new plateau with the arrival on a sforzando G-sharp at 532, the beginning of unit 27. The familiar sequence of featuresa long note followed by a doodling descentis soon overtaken by a fortissimo diminished-seventh chord (bar
553), a chord that (again, in retrospect) marks the beginning of the next unit.
Units 28 (bars 553571), 29 (bars 571573), 30 (bars 581592)
The beginning of the end of the movements middle section is signaled strongly
by the diminished-seventh chord at 553. This is not a moment of culmination as
such; rather, it sounds a distant note and then gradually diminishes that distance.
It carries the aura of a high point by virtue of rhetoric, but it is achieved more by
assertion than by gradual accumulation. Indeed, it is the staged resolution in its
immediate aftermath that confirms the markedness of this moment.
Units 28, 29, and 30 are thematic transformations of each other. Unit 30 is the
most intricate from a harmonic point of view. After 30, the need for a cadence
becomes increasingly urgent, and over the next six units, the obligation to close the
middle section is dramatized by means of Brahms usual avoidance strategy.
Units 31 (bars 592.5601), 32 (bars 601.5611), 33 (bars 611612), 34
(bars 613621), 35 (bars 622631)
Speech mode intrudes here as the units become notably shorter. Unit 31 ends
deceptively, while 32 avoids a proper cadence by dovetailing its ending with the
beginning of 33. Units 33 and 34 are materially identical but are positioned an
octave apart; the connection between them is seamless despite the timbral changes
associated with each group of four sixteenth-notes. And unit 35 is left to pick up
the pieces, echoing the contour of the last three notes of 34 in a durational augmentation that suggests exhaustion.
CHAPTER 7
Brahms
247
19
20
21
22
23
24
25
26
27
28
29
30
31 (truncated)
32
33
34
35 (fragment) 36
We may now summarize the affiliations among the units of the B section (see figure 7.2). Immediately apparent are two features: first, but for units 19 and 36, each
vertical column contains a minimum of two and a maximum of five elements.
This indicates a strategy of use and immediate reuse of material, the extent of
which exceeds what we heard in the A section. If the A section seemed linear in its
overall tendency, the B section incorporates a significant circular tendency into its
linear trajectory. Second, but for the succession 2627, where we return to previous
material, the overall tendency in this section is to move forward, adding new units
and dwelling on them without going back. This, again, promotes a sense of narration. The process is additive and incremental, goal-directed and purposeful.
While the A and B sections share an overall incremental strategy, there
are differences, the most telling being a sense of return in the A section (for
example, units 1516 belong with unit 2 in the same paradigmatic class), which
is lacking in the B section. In other words, a sense of self-containment and
248
PART II
Analyses
46 = (based on) 9
47 = (based on) 10
48 = 10
49 = 47 = 10
50 = 48 = 10
51 = 12
52 = 13
53 = 14
54 = 15
55 = 16
CHAPTER 7
Brahms
249
38
39 (truncated) 40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
is the recasting in unit 51 of the memorable oboe melody from unit 12. Its closing
quality is enhanced by doubling and by the incorporation of a triplet figure in the
accompaniment.
see Jason Stell, The Flat-7th Scale Degree in Tonal Music (Ph.D.
3. For an in-depth study of flat-7,
diss., Princeton University, 2006).
250
PART II
Analyses
section to the A' section, the appearance of flat-7 (D-natural in bar 64) intensifies the progression to the subdominant. Meanwhile, solo cello adds an epigrammatical quality to this moment, while the E pedal ensures the stasis that reeks of
homecoming. Texturally, the music rises from a middle to a high register across 2
bars (101102), then Brahms repeats the gesture (102104) with the slightest of
rhythmic decorations in unit 57.
Units 58 (bars 10431053), 59 (bars 10611063), 60 (bars 10711073), 61 (bars
10811083), 62 (bars 10911113)
One way of enhancing the retrospective glance of a coda is to return to earlier,
familiar material and use it as the basis of a controlled fantasy, as if to signal dissolution. Brahms retrieves the motive from bars 2123 (unit 14, itself affiliated
with the two preceding units and with the opening unit of the work by virtue of its
GAC bass motion) for use in units 5862. The process features varied repetition of 1-bar units in each of bars 105, 106, 107, 108, and 109, this last extended
for another 2 bars. The 3-bar unit 62 functions as the culmination of the process,
as a turning point, and as an adumbration of the return to the opening material.
Indeed, while the last bar of unit 62 (111) is equivalent to the last bar of unit 1 (bar
2), the preceding bars of the two units are different.
Unit 63 (bars 11211142)
Unit 2, with its prolonged dominant, returns here to continue this final phase, the
ending of the ending, so to speak. Dark and lugubrious in bar 112, the material
brightens on a major-mode 6/4 chord (bar 113), reversing the effect of the minor
6/4 coloration that we have come to associate with this material. Again, the longterm effectiveness of this modal transformationa modal fulfillment, we might
sayis hard to underestimate.
Unit 64 (bars 11411161)
Another plateau is reached with this resolution to tonic. As if imitating the beginning of the coda (bars 100101), the melody descends through a flattened-seventh.
We recognize the accompaniments dotted figure from bar 28, where it announced
the beginning of the B section. Here, it is incorporated into a reminiscence of past
events. Brahms puts a little spoke in the wheel to enhance the desire for tonic:
in bar 116, an EA tritone halts the serene, predictable descent and compels a
relaunching of the momentum to close.
Unit 65 (bars 11631181)
With this reuse of the chromatic material from unit 3, we infer that the protagonist
will have to make his peace with this chromatic patch. The effect is one of intrusion, as at the first appearance, but the presence of directed chromatic motion in
CHAPTER 7
Brahms
251
the previous unit mutes the effects of quotation or intrusion. There is a sense that
we have entered a dream worldonly for a moment, of course.4
Unit 66 (bars 11811202)
Only in retrospect are we able to interpret bar 118 as the beginning of this unit.
This is because the link across the bar line in 117118 is conjunct rather than disjunct. Here, we are treated to the same bass descent of fifths that we encountered
in units 10 (CFBE), 48, and 50 (GCFB), bringing us once more
to the tonic (bar 120). Something about the melody of this unit evokes a sense of
pastness, the same sense that we associated with units like 3. Overall, the freight of
retrospection introduced in unit 56 (bar 100) continues to hang here.
Unit 67 (bars 12021222)
This material is a repeat of 64, with slight modifications of texture and registral
placement; it encounters the same tritonal crisis at the end of the unit.
Unit 68 (bars 1223128)
One more intrusion of the chromatic segment finds its final destination in a clean
E major chord, the goal of the movement. The final approach incorporates a strong
plagal element (bars 123124), not unlike the link between the B and A' sections.
Five bars of uninflected E major provide the phenomenal substance for an ending,
inviting us to deposit all existing tensions here and to think of heaven.
Figure 7.4 Paradigmatic arrangement of units 5668 in Brahms Symphony
No.1/ii.
56
57
58
59
60
61
62 (extended) 63
64
65
67
68 (extended)
66
252
PART II
Analyses
A paradigmatic arrangement of the coda taken on its own would look like figure 7.4. Again, the stacking of the column with units 5862 conveys the extensive
use of repetition as the movement nears an end; this curbs the narrative tendency
by withholding novelty. Indeed, the coda uses several prominent materials from
earlier in the movement. Units 5862, for example, are based on the first bar of the
main material of the movement, unit 1. Unit 63 is equivalent to unit 2, while units
65 and 68 are equivalent to unit 3, the latter extended to close the movement. There
is nothing new under the sun.
What, then, has the foregoing semiotic analysis shown? As always with analysis, a verbal summary is not always testimony to its benefits, for what I hope to
have encouraged is hands-on engagement with Brahms materials. Nevertheless,
I can point out a few findings. I began by invoking Walter Frischs remark that
this movement is a supreme example of Brahmsian musical prose. The movement
is indeed segmentable, not according to a fixed, rule-based phrase structure but
on the basis of contextual (some might say ad hoc) criteria, that is, according to
what Brahms wishes to express in the moment, from phrase to phrase and from
section to section. I sought to characterize each bit of material according to its
locally functional tendency and then to see what constructional work it is doing
in the course of the movement. In some cases, the paradigmatic analysis simply
confirmsor gives external representation tolong-held intuitions about musical
structure. For example, the idea that closing sections feature extensive reiteration
of previously heard material is conveyed by the affiliations among units 5862.
The narrative-like sense of the A section is conveyed by the number of new ideas
that Brahms exposes there. The different pacing in utterance between the A and B
sectionsroughly, the prose-like nature of the A section against the initially verselike nature of the contrasting B section, which, however, returns to prose from
about unit 28 onwardis underwritten by the rhythm of units.
Enumerating these structural functions, however, does not adequately convey the sensual pleasure of analyzing a movement like thisplaying through it at
the piano, juxtaposing different units or segments, imagining a different ordering,
writing out some passages on music paper, and listening to different recordings. In
one sense, then, no grand statement is necessary because the process is multifaceted, multiply significant, and dedicated to doing. To have undertaken the journey
is what ultimately matters; the report of sights seen and sounds heard signifies
only imperfectly and incompletely.
C HA P T E R
Eight
Mahler, Symphony no. 9/i (19081909)
253
254
PART II
Analyses
structure, the musical and the extramusical, or even structuralism and hermeneutics have not been rendered totally irrelevant in contemporary musicological
discourse. The differences they promulgate lie at the very root of almost all theorization of musical meaning.
The main intellectual labor in this book has been geared toward explicating the
directly musical qualities while letting the spirit of the music emerge from individual or even personal narratives drawn from these qualities. My reticence may
seem evasive, but is intended to be strategic. It is motivated in part by the recognition that the range of responses provoked by the spirit of the music is irreducibly
plural and unavoidably heterogeneous. Plurality and heterogeneity, however, speak
not to unconstrained speculation butmore pragmaticallyto the nature of our
(metalinguistic and institutional) investments in critical practice. Nor do I mean
to imply that the directly musical qualities finally admit of homogeneous characterization. I believe, however, that the degree of divergence within the domain of
technical characterization is significantly narrower than the diversity within characterizations of spirit. This difference does not in itself carry a recommendation
about what is more meaningful to explore. Since, however, part of the burden of
this book has been to encourage (spiritual) adventures emanating from the observation of technical procedures, I will retain that stance in the analysis that follows.
Directly musical qualities will be constructed from the specific viewpoint of the
use of repetition.
Let us turn, then, to a work that is not exactly lacking in extensive analytical commentary.2 Indeed, some analysessuch as that by Constantin Florosare
implicitly paradigmatic. My own approach differs only to the extent that it is more
explicit in this regard. As before, I will follow a two-step analytical procedure.
First, I will identify the building blocks or units in the entire movement; second,
I will explore some of the affiliations among the building blocks. It is at this latter
stagethe stage of dispositio, we might saythat matters of discourse will come
to the fore.
2. Henry-Louis de La Grange provides a useful synthesis of the major analytical studies of the Ninth
while offering his own original insights. See Gustav Mahler: A New Life Cut Short (19071911)
(Oxford: Oxford University Press, 2008), 14051452. See also Stephen Hefling, The Ninth Symphony, in The Mahler Companion, ed. Donald Mitchell and Andrew Nicholson (Oxford: Oxford
University Press, 2002), 467490. Dniel Bro emphasizes timbre in the course of a holistic appreciation of the movement in Plotting the Instrument: On the Changing Role of Timbre in Mahlers
Ninth Symphony and Weberns op. 21 (unpublished paper).
CHAPTER 8
Mahler
255
of Brahms E Minor Intermezzo, op. 119, no. 2, which we studied in the previous chapter. In terms of gesture, Mahlers movement is perhaps closest to Liszts
Orpheus, but the building blocks there are set apart more distinctly than in Mahler.
Yet the same general principles of segmentation apply. Units must be meaningful and morphologically distinct. Repetition may be exact or varied (with several
stages in between). Where it involves tonal tendencies, voice-leading paradigms, or
thematic identities, repetition must be understood with some flexibility in order to
accommodate looser affiliations. For example, if two units begin in the same way,
or indicate the same narrative intentions, and conclude in the same way (syntactically) without, however, following the same path to closure, they may be deemed
equivalent on one level. This loosening of associative criteria is necessary in analyzing a fully freighted tonal language; it is also necessary in order to accommodate Mahlers intricate textures and to register their narrative tendency. As we will
see, a number of units carry an intrinsic narrative disposition. Narration is often
(though by no means always) melody-led and imbued with tendencies of beginning, continuing, or ending.
Related criteria for segmentation are contrast and discontinuity. Contrast may
be expressed as the juxtaposition of dense and less dense textures, the alternation
and superimposition of distinct tone colors or groups of such colors, opposing or
distantly related tonal tendencies, or differentiated thematic gestures.3 We typically
encounter contrast from the left, that is, prospectivelyas if we walked into it. Not
all apparent gestures of discontinuity sustain the designation of contrast, however.
When the collective elements of difference separating two adjacent units seem to
outnumber or be more forcefully articulated than the collective elements of sameness, we are inclined to speak of discontinuity. Neither continuity nor discontinuity
can be absolute, however.
In short, segmentation is guided by the tendency of the material: its proclivities and its conventional and natural associations. Listening from this point of
view involves attending to the unfolding dynamic in an immediate sense even
while recognizing associations with other moments. We listen forward, but we also
entertain resonances that have us listening sideways and backward.
It should be noted that the boundaries separating adjacent units are not always
as firm as our segmentation might sometimes imply. Processes within one unit
may spill over into the next. Sometimes, newness is known only in retrospect.
And the conflation of beginnings and endings, a procedure that goes back to the
beginnings of tonal thinking, is often evident in Mahler. Units may be linked by a
fluid transitional process whose exact beginning and ending may not be strongly
marked. The boundaries indicated by bar numbers are therefore merely convenient
signpostsprovisional rather than definitive indicators of potential breaks. Listeners should not be denied the opportunity to hear past these boundaries if they so
desire; indeed, such hearing past is well-nigh unavoidable during a regular audition
3. On contrast in Mahler, see Paul Whitworth, Aspects of Mahlers Musical Style: An Analytical Study
(Ph.D. diss., Cornell University, 2002). On the composers manipulation of tone color, see John
Sheinbaum, Timbre, Form and Fin-de-Sicle Refractions in Mahlers Symphonies (Ph.D. diss.,
Cornell University, 2002).
256
PART II
Analyses
of the work. I ask only that listeners accept the plausibility of these boundaries for
the purposes of analysis.
Paradigmatic Analysis
I have divided the movement into 33 units. Let us make a first pass through the
movement by describing their features and tendencies. Later, I will speculate on
form and meaning. (From here on, the reader needs access to a full score of the
movement in order to verify the description that follows.)
Unit 1 (bars 163)
The feeling of emergence that we experience in these opening bars (see the piano
score of these bars in example 8.1) will be transformed when first violins enter
2 melodic gesture that will be
at the end of bar 6 with F-sharp followed by E, a 3
repeated immediately and, in due course, come to embody the narrative voice. The
opening bars are fragmentary and timbrally distinct, and they lack an urgent or
purposeful profile. It will emerge in retrospect that these bars constitute a metaphorical upbeat to the movements beginning proper. Their purpose is to expose
a number of key motifs: a syncopated figure or halting rhythm played by cellos
and horns; a tolling-bell figure played by the harp (which includes a 025 trichord
6
suggesting pentatonic affiliation); a sad phrase played by horns based on a 5
2
4
melodic gesture (56 frames bars 34 and then is stated directly in bars 5 62);
and a rustling or palpitation in the viola (which, although figured functionally as
accompaniment, is nevertheless essential to the movements discourse). The summary effect is atmospheric and descriptive; there is a sense that nothingness is
being replaced.4
Example 8.1. Opening bars of Mahlers Ninth, first movement.
Andante comodo
Unit 1 not only sets out the principal motives of the movement, it will return in
a recomposed guise to begin the so-called development section (unit 10). It will also
be heard at the climax of the movement (unit 24). Nothing in this initial presentation allows us to predict subsequent functions and transformationsnothing, perhaps, except the embryonic manner of the beginning, which suggests a subsequent
4. I have borrowed Deryck Cookes descriptive phrases for unit 1 because they seem particularly apt.
See Cooke, Gustav Mahler: An Introduction to His Music (London: Faber, 1980), 116117.
CHAPTER 8
Mahler
257
presentation of more fully formed ideas. Significant, too, are the relative autonomy
and separateness of the passage (bars 16 were crossed out of Mahlers autograph
score at one point during the compositional process; they were later restored), its
spatial rather than linear manner, and its fascinating and unhierarchic display of
timbres in the manner of a Klangfarbenmelodie. If, in spite of the units spatial tendencies, one is able to attend to its overall tonal tendency, then pitch-class A will
emerge as anchor, as a source of continuity throughout the passage.
Unit 2 (bars 64175)
The main theme (or subject) is exposed here. (Example 8.2 quotes the melody.)
The material is in song mode, unfolds in a leisurely manner, and carries an air of
nostalgia. The unhurried aura comes in part from the grouping of motives: two
notes and a rest, two notes and a rest, threefold articulation of two notes and a
rest, fivefold articulation of four notes followed by a rest, three notes and a rest, the
same three notes and a rest, and finally an expansive gesture in which seven notes
are offered in 13 attack points. The melody seems to go over the same ground even
as it gradually and subtly breaks out of its initial mold.
Example 8.2. Main theme of Mahlers Ninth, first movement, bars 716.
etc
melodic gesture that will dominate the movement. The sound term 32 is a promise, of course, because it is syntactically incomplete. This is not a uniquely Mahler 2 bears over a century of conventional use, most famously in the
ian rendition; 3
first movement of Beethovens Les Adieux Sonata, op. 81a, and in Der Abschied
2 appears first as a beginfrom Mahlers own Das Lied von der Erde. In this unit, 3
ning; then, in bars 1418 (the ending of the unit), it appears in the context of an
ending.
The once-upon-a-time quality conveyed by the string melody and its horn
associates suggests a movement of epic proportions. Among other things, the ostinato bass in bars 913 underlines the largeness of the canvas. Significant, too, is the
muting of leading-tone influence such that the harmonic ambience, pandiatonic
rather than plainly diatonic, acquires an accommodating feel rather than a charged
profile. Among other features, 6 is incorporated into the tonic chord; some sonorities contain unresolved appoggiaturas while others suggest a conflation of tonic
and dominant functions. Unit 2 ends incompletely. The dialogue between second
violins (carrying the main melody) and horns (singing a countermelody in bars
1417) is dominated by gestures promising closure. The listener carries forward an
expectation for eventual fulfillment.
258
PART II
Analyses
CHAPTER 8
Mahler
259
as we will see, continues from where the 23 pair left off, introducing a new level
of narration that, however, is soon truncated. Mahlerian narrative as displayed in
these first five units is based on networks of activity in which leading ideas and
processes vie for attention. While it is of course possible to extract a Hauptstimme,
claims for melodic priority are made by different instrumental parts. What we are
dealing with, then, are degrees of narrativity (as Vera Micznik calls them).5 For
example, the simple act of melodic telling in units 2 and 3 is transformed into a
more communal activity in unit 4. Unit 1, likewise, effected the manner of a constellation, a communality by default rather than by design. (Im talking not about
the composers intentions but about the tendency of the musical material.) There
is, as always in Mahler, a surplus, an excess of content over that which is needed to
establish a narrative line.
Unit 5 (bars 466542)
This appearance of the main theme incorporates motifs from the prelude (unit
1), including the palpitating sextuplet figure introduced in bar 5 by the violas and
entrusted now to double basses and bassoons, and the sad phrase announced by
the horns in bars 45, which is now given to the trumpets (bars 4950). The music
makes a deceptive close in bars 5354 by means of a Vvi motion, thus opening
up the flat side of the tonal spectrum. We recall the juxtaposition of D major and
minor in units 34 and project the thought that similar dualities will carry a fair
amount of the movements dynamic.
The aftermath of the cadence in bars 5354 carries a strong sense of codetta
at first, but a new melodic idea in a different tonal environment (bars 57 onward,
in B-flat major) confers a sense of beginning rather than ending. This conflation
of functions is partly why I have located the beginning of unit 6 in bar 54; the join
between units 5 and 6 is porous.
Unit 6 (bars 543633)
Although some of the motivic elements on display here have been adumbrated
in previous units, the overriding tendency is that of dream or recallas if a lost
song (sung by second violins and flutes) were filtering through. The moment has
the character of a parenthesis, a tributary to the narrative. This feature will emerge
even more forcefully when oboes and violins barge in at bar 63 to resume the
main narration. We may suspect that a certain amount of tonal business is being
transacted here (the key of B-flat lies a third away from D), but we are not yet in
a position to know for sure. The ending of this unit illustrates Mahlers penchant
for problematizing conventional syntax: what begins as a 6/4-induced cadential
gesture in B-flat (bars 6263) is abandoned or cut short. We may with some confidence speak of an interruption or even a disjunction between units 6 and 7. (Ana-
5. Vera Micznik, Music and Narrative Revisited: Degrees of Narrativity in Mahler, Journal of the Royal
Musical Association 126 (2001): 193249.
260
PART II
Analyses
lysts inclined to find continuity will, of course, succeed: the pitch B-flat provides a
link between the two units.)
Unit 7 (bars 6479)
This begins as another version of the main theme, featuring the promise or fare 2.
Continuation is modified, however, to lead to extended closure.
well motif, 3
From bar 71 onward, a network of closing gestures within diatonic polyphony generates expectations for something new. We may well feel that the work of the main
theme (as heard in units 2, 3, 5, and now 7) is nearly done and that something new
needs to happen to counter the pervasive sense of stasis. The neat juxtaposition of
major and minor in bars 77 and 78, respectively, sums up the modal history of the
movement so far without, however, giving the impression that unit 7 is capable of
resolving all of the tensions accumulated.
Unit 8 (bars 8091)
This unit starts on, rather than in, B-flat. Among other previously heard motifs, it
incorporates the movements main contrasting material, the chromatic idea first
introduced as unit 4, where it was grounded on D. Here, the ground shifts to
B-flat, but the melodic pitches remain the samea use of pitch invariance that
is not common in Mahler. A strong dominant sense in 8687 conveys the imminence of closure. All of the signs are that we will close in B-flat, a key that has made
only sporadic appearance so far (most notably in unit 6), but this expectation is
not fulfilled. What seems pertinent here, and is entirely in keeping with Mahlers
metamusical impulses, is not the tonicization of a specific scale degree but a more
primal desire for some sort of cadential articulation. Mosaic-like motivic construction thus combines with cadential suggestiveness to mark this unit as an
on-its-way gesture.
Unit 9 (bars 92107)
The closing gesture introduced at the end of the previous unit is intensified with this
marked off-beat passage (example 8.3), which will return at subsequent moments
of intensification. Reinforced by a cymbal crash and underpinned by a circle-offifths progression (example 8.4), the unit prepares a cadence in B-flat. At bar 98,
a subdominant-functioning chord further signals closure, but once again normative continuation is withheld. In other words, while the spirit of intensification is
kept up, the conventional supporting syntax is denied. Eventually, material marked
allegro (bar 102) rushes the unit to a dramatic conclusion in bar 107. This moment
is marked for consciousness by its 6/3 harmony on B-flat. It is something of a
transgressive gesture, for in place of the longed-for stable cadential close, Mahler
supplies an unstable ending. Indeed, the 6/3 chord points, among other things, to
a possible E-flat cadence (see the hypothetical progression in example 8.5). An
upbeat rather than a downbeat, a precadential harmony rather than a cadential
close, this moment reeks of abandonment. Mahler writes in a double bar at 107 to
CHAPTER 8
Mahler
261
Example 8.3. Intensifying phrase, Mahlers Ninth, first movement, bars 9295.
becomes
mark off a major segment of the work. Were this not also the end of the exposition,
the strategic violence of refusing forward drive would be less intense.
Taking stock: the alternation between the main theme (in D major) and the
subsidiary theme (in D minor) establishes a large-scale structural rhythm that leads
the listener to imagine a work of large proportions. So far, the mosaic-like circulation of motifs together with the absence of purposeful tonal exploration have combined to undermine any expectations we might entertain for clear sonata-form
articulation. The movement in fact forges its own path to understanding. We finish
the exposition with the summary understanding that a diatonic, nostalgic idea
(the main theme), repeated in varied form, alternates with a tormented (Cookes
word) chromatic idea, which retains some pitch invariance in repetition while
adapting to new tonal situations. We are also haunted by a third, subsidiary element, the B-flat major theme (unit 6), which opened the door to the otherworldly.
A paradigmatic arrangement of the units would look like figure 8.1.
262
PART II
Analyses
2
3
5
7
6
8
The arrangement confirms that things are weighted toward the main theme
(a fourfold occurrence, units 2, 3, 5, and 7) and that the contrasting theme makes
a twofold appearance (units 4 and 8). Of course, there is more to the formal process than this external disposition of materials. For example, a teleological process
embodied in the 2357 sequence contributes an accumulative sense, but this is
not readily observable from a simple paradigmatic arrangement. Similarly, affiliations between the relatively autonomous opening unit (1) and subsequent units
(perhaps most notably, units 8 and 9) may not be readily inferred. The experience
of form in Mahler is often a complex business, depending as much on what is not
said as on what is said and how it is said. To take Mahler on his own is to risk an
impoverished experience. Even in a work like the first movement of the Ninth,
where intertextual resonance is less about thematic or topical affiliation, an internally directed hearing will still have to contend with various dialogues. For example, without a horizon of expectations shaped by sonata form, rondo form, and
theme and variations, one might miss some of the subtle aspects of the form. These
categories are not erased in Mahler; rather, they are placed under threat of erasure,
by which I mean that they are simultaneously present and absent, visible but mute.
Mahler demands of his listeners the cultivation of a dialogic imagination.
Unit 10 (bars 1081293)
Immediately noticeable in this unit is the activation of the speech mode. Motivic
development often takes this form since it in effect foregrounds the working
mode, the self-conscious and ongoing manipulation of musical figures without the
constraint of regular periodicity. The unit is marked at the beginning by a strong
motivic association with the opening of the work: the syncopated figure leads off
(bars 108110), followed by the tolling-bell motif in bars 111112 and in the following. Soon, other elements join in this loose recomposition of unit 1. Manipulation, not presentation, is the purpose here. From the sparseness of texture, we
infer that several of the motifs seem to have traveled a considerable expressive
distance. The working mode gives way to a codetta sense around bar 117, where
a new figure in oboes, English horn, violas, and cellos conveys the gestural sense
of closure without, however, supplying the right syntax. This sense of closing will
persist throughout units 10 and 11 before being transformed into an anticipatory
feeling at the start of unit 12 (bar 136). In a sense, units 10, 11, and 12 constitute a
CHAPTER 8
Mahler
263
264
PART II
Analyses
is tonally unstable in spite of the flirtation with G major from bar 182 on. Proceedings intensify from bar 174 onward. Previously heard motives are laboriously
incorporated in a full contrapuntal texture, and this working modea struggle of
sortscontinues through the rest of the unit, reaching something of a local turning point at the beginning of the next unit.
Unit 15 (bars 196210)
As in its previous appearance, this off-beat, syncopated passage, underpinned by
bass motion in fifths, signals intensification, culminating this time in the first high
point of the development (bar 202). Again, the bass note is D, and so the high point
is produced not by the tension of tonal distance but by activity in the secondary
parameters of texture and dynamics. In the aftermath of the high point, sixteenthnote figures derived from the movements contrasting idea (heard also in unit 10,
bars 12124) are incorporated into the accompaniment, preparing its melodic
appearance in the next unit.
Unit 16 (bars 2112461)
The affectively charged material that functions as the main contrasting material in
the movement appears once again. When it was first heard (unit 4), it sported a D
minor home. Later, it appeared with the same pitches over a B-flat pedal (unit 8).
On this third occasion, pitch invariance is maintained, and the B-flat pedal of the
second occurrence is used, but the modal orientation is now minor, not major.
This material signals only the beginning of a unit whose purpose is to advance
the working-through process. It does so not, as before, by juxtaposing different
themes in a mosaic-like configuration, but by milking a single theme for expressive
consequence. Throughout this unit, string-based timbres predominate and lines
are often doubled. (The string-based sound provides a foretaste of the finale, while
also recalling the finale of Mahlers Third Symphony.) In its immediate context,
the materials signal an act of cadencing on a grand scale. The approach in bar 215
is not followed through, however; nor does the local high point at 221 discharge
into a cadence. Finally, at 228, the syntax for a cadence on B-flat is presented in the
first two eighth-notes, but nothing of the durational or rhetorical requirements
for such a cadence accompanies the moment. The goal, it turns out, is none other
than the tonic of the movement, and this cadence occurs at 235236, although the
momentum shoots past this moment and incorporates a series of reminiscences
or postcadential reflection.
Although key relationships are explored from time to time in this movement
(as Christopher Lewis has shown),6 the overall drama does not depend fundamentally on purposeful exploration of alternative tonal centers. The tonicbe it
in a major or minor guiseis never far away; indeed, in a fundamental sense, and
despite the presence of third-related passages in B-flat major and B major, the
6. Christopher Lewis, Tonal Coherence in Mahlers Ninth Symphony (Ann Arbor, MI: UMI Press, 1984).
CHAPTER 8
Mahler
265
movement, we might say, never really leaves the home key. It concentrates its labor
on thematic, textural, and phrase-structural manipulation.
Unit 17 (bars 2454266)
The tremolo passage from unit 12 returns to announce a coming thematic stability.
2 gesture, the augmented triad, and the
A constellation of motifs (including the 3
chromatic descent) accompanies this announcement.
Unit 18 (bars 26642792)
The main theme is given melodramatic inflection in the form of a solo violin utterance (bars 269270). Solo timbre sometimes signals an end, an epilogue perhaps;
sometimes the effect is particularly poignant. This overall sense of transcendence
is conveyed here even as other motifs circulate within this typical Mahlerian constellation.
Unit 19 (bars 2792284)
Previously associated with moments of intensification, this syncopated passage
appears without the full conditions for intensification. This is because the preceding unit was stable and assumed a presentational function. (A continuing or
developmental function would have provided a more natural or conventional
preparation.) Only in its last 2 bars (277278) was a token attempt made to render
the beginning of the next unit nondiscontinuous. In one sense, then, this intensifying unit functions at a larger level, not a local one. It harks back to its sister passages and reminds us that, despite the sweet return of the main theme in bar 269,
the business of development is not yet finished. In retrospect, we might interpret
unit 18 as an interpolation.
Unit 20 (bars 28442951)
An ascending, mostly chromatic bass line in the previous unit (EFAA
A) discharges into the initial B major of this one. Horn and trumpet fanfares
activate the thematic dimension, as does the sad phrase from the opening bars of
the work, now in a decidedly jubilant mood (bar 286).
Unit 21 (bars 2952298)
We single out this 4-bar phrase as a separate unit because we recognize it from previous occurrences. In context, however, it is part of a broad sweep begun in unit 20
that will reach a climax in unit 24. Part of what is compositionally striking about
this moment is that a gesture that seemed marked in its three previous occurrences
(units 11, 15, 19) now appears unmarked as it does its most decisive work. Here, it
is absorbed into the flow, neutralized by name, so to speak, so that we as listeners
can attend to the production processes.
266
PART II
Analyses
CHAPTER 8
Mahler
267
11
12
17
13
14
15
18
19
21
16
20
22
23/1
23/2
24
7. Unit 23 is divided into two because the parts are affiliated with different materials. It is, however,
retained as a single unit because its overall gesture seems continuous and undivided.
268
PART II
Analyses
the temporal and experiential realms. Temporal novelty in turn denies material
sameness. But unmitigated difference is psychologically threatening, for without
a sense of return, without some anchoring in the familiar, music simply loses its
ontological essence. Mahler understood this keenly, following in the spirit of his
classical predecessors. But, like Brahms before him, recapitulation for Mahler was
always a direct stimulus to eloquence, artistic inflection, and creativity. We never
say the same thing twice. To do so would be to lie. Hearing a recapitulation, then,
means attending to sameness in difference or, rather, difference in sameness. While
our scheme of paradigmatic equivalence glosses over numerous details, it nevertheless orients us to gross levels of sameness that in turn facilitate individual acts
of willed differentiation.
Unit 26 (bars 35643652)
Unit 25 is repeated (making the 2526 succession the equivalent of the earlier 23),
beginning in a higher register and with the first violins in the lead. The period ends
with a deceptive cadence on B-flat as flattened-sixth (bars 364365), thus leaving things open. The drive to the cadence incorporates a rising chromatic melody
(bars 363365) reminiscent of bars 4446, but the cadence is deceptive rather than
authentic.
Unit 27 (bars 36523722)
The pattern of bass notes suggests that we hear this unit as an expanded parenthesis, a dominant prolongation. Beginning on B-flat, the music shifts down through
A to G-sharp (bar 370) and then back up to A as V of D. The themes are layered. A
version of the main theme occurs in the violas and cellos, while a subsidiary theme
from bar 54 (cellos) is now elevated to the top of the melodic texture. The last 2
bars of this unit (371372) derive from unit 7 (bars 6970). In short, if unit 26
offered a sense of tonic, unit 27 prolongs that tonic through chromatic neighbors
around its dominant.
An aspect of the production process that this unit reveals is Mahlers attitude
toward recapitulation. In certain contexts, reprise is conceived not as a return to the
first statement of a particular theme but as a return to the paradigm represented
by that theme. In other words, a recapitulation might recall the developmental version of a theme, not its expositional version, or it may recall an unprecedented but
readily recognizable version. In this way, the movements closing section incorporates references to the entire substance of what has transpired. This is Mahlerian
organicism at its most compelling.
Unit 28 (bars 37223762)
The bass note A serves as a link between units 27 and 28, finding resolution to D
in the third bar of this unit. The thematic field being recapitulated is the tormented
idea first heard as unit 4. This lasts only 4 bars, however, before it is interrupted by
a spectacular parenthesis. Meanwhile, the brasses recall the fanfare material.
CHAPTER 8
Mahler
269
270
PART II
Analyses
then minorunstable because, while the underlying syntax is there, the rhetorical
manner is too fragmentary to provide a firm sense of a concluding tonic.
Unit 32 (bars 4063433)
The movement seems fated to end in chamber-music mode! A change of tempo, a
reduction in orchestral forces, and a turning up of the expressivity dial all combine
to suggest closing, dying, finishing. A single horn intones the syncopated idea that
we have associated with moments of intensification (bar 4082), and this is succeeded by fanfares and sighs. Between 406 and 414, the harmony remains on D;
then, it shifts for 2 bars on to its subdominant, a moment that also (conventionally)
signifies closure, before getting lost again in a miniflute cadenza (bars 419433).
An E-flat major chord frames this particular excursion (419432), and although
it may be read as a Neapolitan chord in the home key, hearing it as such would
be challenging in view of the way we come into it. The retention of a single voice
during the closing process is a technique that Mahler will use spectacularly in the
closing moments of the opening movement of his Tenth Symphony.
Unit 33 (bars 434454)
The main theme returns for the last time. This is the stable, foursquare versionor
so it begins, before it is liquidated to convey absolute finality. The most spectacular
feature of this unit is the choreographing of closure through a sustained promise
2 motion will eventually find its 1.
within a single bar (444), then 32 across a bar line with longer note values (4463
2 spread over 6 bars (2 occupies 5 of those bars). And just when
4472), and finally 3
the listener is resigned to accepting a syntactically incomplete gesture as a notional
ending, the long-awaited 1 finally arrives in the penultimate bar of the movement
(453), cut off after a quarter-note in all instruments except clarinet, harp, and high 2
1 gesture for which we have been waiting since the beginning
lying cellos. The 3
of the movement finally arrives. But, as often with Mahler, the attainment of 1 is
problematized by two elements of discontinuity, one timbral, the other registral. A
conventional close might have had the oboe reach the longed-for 1 on D, a major
second above middle C in bar 453. But D arrives in two higher octaves simultaneously, played by flute, harp, pizzicato strings, and cellos. And, as if to emphasize
CHAPTER 8
Mahler
271
the discontinuity, the oboes extend their D into the articulation of 1 by the other
instruments on the downbeat of bar 453, thus creating a momentary dissonance
and encouraging a hearing that accepts 2 as final. Of course, the higher-placed
Ds (in violins and violas) and longer-lasting ones (in flutes and cellos) dwarf the
oboes E, so the ultimate hierarchy privileges 1 as the final resting place. It is hard
to imagine a more creative construction of an equivocal ending.
Listeners who have not forgotten the material of the movements opening unit
may be struck by how it is compressed in the last two units. At the beginning,
a syntactic element in the form of a dominant prolongation provided the background for a free play of timbres and a mosaic-like exhibition of motives. Only
when the narration proper began in the second violin in unit 2 did the various
strands coalesce into a single voice. In these last bars, much is done to deny the
integrity of simple melodic closure; indeed, it may even be that not until we experience the silence that follows the weakly articulated Ds in bars 453454 are we
assured that a certain contrapuntal norm has been satisfied.
Form
By way of summary, and again recognizing the limitation of this mode of representation, we may sketch the larger shape of the movement as in figure 8.3.
Several potential narratives are enshrined in this paradigmatic chart. And this
is an important property of such charts, for although they are not free of interpretive bias, they ideally reveal conditions of possibility for individual interpretation.
To frame the matter this way is to emphasize the willed factor in listening. This is
not to suggest that modes of interpretation are qualitatively equal. For example,
some may disagree about the placement of boundaries for several of the units isolated in the foregoing analysis. Indeed, in a complex work like the first movement
of Mahlers Ninth, giving a single labelas opposed to a multitude of labels in a
network formationmay seem to do violence to thematic interconnectedness and
the numerous allusions that constitute its thematic fabric. The issue is not easily
resolved, however, because segmentation resists cadence-based classical rules. To
say that the movement is one continuous whole, however, while literally true on
some level, overlooks the variations in intensity of the works discourse. It seems
prudent, then, to steer a middle courseto accept the idea of segmentation as
being unavoidable in analysis and to approach the sense units with flexible criteria.
What has been attempted here is a species of labeling that recognizes the potential
autonomy of individual segments that might make possible a series of associations.
In the end, paradigmatic analysis does not tell you what a work means; rather, it
makes possible individual tellings of how it means. Those who do not mind doing
the work will not protest this prospect; those who prefer to be fed a meaning may
well find the approach frustrating.
The most literal narrative sanctioned by the paradigmatic approach may be
rehearsed concisely as follows. Preludial material (1) gives way to a main theme
(2), which is immediately repeated (3) and brought into direct confrontation with
272
PART II
Analyses
a contrasting theme (4). The main theme is heard again (5) followed by a subsidiary theme (6). The main theme appears again (7) and now heads a procession that
includes the contrasting theme (8) and a new idea that functions as an intensifier
(9). The preludial idea returns in a new guise (10), followed by the first subsidiary
theme (11) and yet another new idea (12)all in the manner of development or
working through. The main theme is heard again (13), followed by the expositions
subsidiary and intensifying themes (14, 15), the contrasting idea (16), and the second subsidiary theme (17). Again, the main theme is heard (18), followed, finally,
by its most prolonged absence. Starting with the intensifying theme (19), the narrative is forwarded by materials that seem distinct from the main theme (20, 21,
22, 23/1). Units 23/2 and 24 merge into each other as the preludial material returns
in a rhetorically heightened form (24). This also marks the turning point in the
movements dynamic trajectory. The rest is recall, rhyme, flashback, and the introspection that accompanies reflection, following closely the events in the first part
(25, 26, 27, 28, 29, 30, 31, 32, 33), while incorporating an extended parenthesis in
the form of a cadenza (29).
CHAPTER 8
Mahler
273
274
PART II
Analyses
an intensifier at important junctures. Its first occurrence is at the end of the exposition (9). Then, as often happens in Beethoven, an idea introduced almost casually or offhandedly at the end of the exposition becomes an important agent in
the exploratory business of development. Mahler uses this idea four times in the
course of the development, making it the most significant invariant material of
the development. This is perhaps not surprising since the unit displays an intrinsic
developmental property. It is worth stressing that, unlike the main and contrasting themes, this syncopated idea lacks presentational force; rather, it is an accessory, an intensifier.
One factor that underlines the movements coherence concerns the role of unit
1, a kind of source unit whose components return in increasingly expanded forms
as units 10 and 23/224. Unit 1 exposes the movements key ideas in the manner
of a table of contents. Unit 10 fulfills a climactic function while also initiating a
new set of procedures, specifically, the deliberate manipulation of previously held
(musical) ideas. Finally, unit 23/2 marks the biggest high point of the movement.
The trajectory mapped out by the succession of units 11023/224 is essentially
organic. Unlike the main theme, which in a sense refuses to march forward, or
perhaps accepts that imperative reluctantly, the syncopated rhythm that opens the
work is marked by a restless desire to go somewhere (different).
The paradigmatic chart is also able to convey exceptions at a glance. Columns
that contain only one item are home to unduplicated units. There is only one such
element in this movement: the misterioso cadenza (unit 29) in the recapitulation,
which does not occur anywhere else. This is not to say that the analyst cannot trace
motivic or other connections between unit 29 and others; the augmented triad at
bar 3784, for example, is strongly associated with the tormented material we first
encountered as unit 4; indeed, this material will return at the start of the next unit
in bar 391. It is rather to convey the relative uniqueness of the unit in its overall
profile. Within the development space, four units seem materially and gesturally
distinct from others in the movement. They are 12 and 17 and to a lesser extent
20 and 22. Units 12 and 17 are preparatory, tremolo-laden passages, complete with
rising chromaticism that intrinsically signals transition or sets up an expectation
for a coming announcement or even revelation. Although they incorporate the
brass fanfare from unit 4 (bars 4445), units 20 and 22 feature a marked heroic
statement in B major that, alongside the syncopated intensifying passage (units 19,
21, 23), prepares the movements climax (unit 23).
Also evident in the paradigmatic chart is the nature of community among
themes. The prelude and main theme are associated right at the outset (12); they
are also allied at the start of the recapitulation (2425) but not in the development
section. The main theme and the contrasting idea are strongly associated throughout the exposition, but not as strongly in the development or recapitulation; they
find other associations and affinities.
It is also possible to sense a shift in thematic prioritization. Units 6 and 9
appeared in a subsidiary role in the exposition. During the development unit, 6
assumed a greater role, while unit 9 took on even greater functional significance.
In the recapitulation, they returned to their earlier (subsidiary) role (as 27 and 32),
making room for the 34 pair to conclude the movement.
CHAPTER 8
Mahler
275
Meaning
The ideal meaning of the first movement of Mahlers Ninth is the sum total of
all of the interactions among its constituent elementsa potentially infinite set
of meanings. Although there exists a relatively stable score, implied (and actual)
performances, and historically conditioned performing traditions, there are also
numerous contingent meanings that are produced in the course of individual
interpretation and analysis. Acts of meaning construction would therefore seek a
rapprochement between the stable and the unstable, the fixed and the contingent,
the unchanging and the changing. In effect, they would represent the outcome of
a series of dialogues between the two. Refusing the input of tradition, convention,
and style amounts to denying the contexts of birth and afterlife of the composition,
contexts that shape but do not necessarily determine the specific contours of the
trace that is the composition. At the same time, without an individual appropriation of the work, without a performance by the analyst, and without the speculative acts engendered by such possession, the work remains inaccessible; analysis
ceases to convey what I hear and becomes a redundant report on what someone
else hears.
Of the many approaches to musical meaning, two in particular seem to dominate contemporary debate. The first, which might be dubbed intrinsic, derives from
a close reading of the elements of the work as they relate to each other and as
they enact certain conventions. Analysis focuses on parameters like counterpoint,
harmony, hypermeter, voice leading, and periodicity, and it teases out meaning
directly from the profiles of their internal articulations and interactions. One way
to organize the mass of data produced by such analysis is to adopt an umbrella
category like closure. As we will see, the first movement of Mahlers Ninth provides many instances of closure as meaningful gesture. (Intrinsic is affiliated with
formalist, structuralist, and theory-based approaches.)
The second approach to meaning construction is the extrinsic; it derives from
sources that appear to lie outside the work, narrowly defined. These sources may be
276
PART II
Analyses
CHAPTER 8
Mahler
277
with V as an open unit, then continues and ends with the same tendency. In
the case of units 1516, intensification does lead to resolution; or rather, resolution involves a unit marked by instability. Therefore, while the sense of that
particular succession (1516) is of tension followed by release, the latter is not
the pristine, diatonic world of the main theme but the more troubled, restless,
and highly charged world of the subsidiary theme. In the successions of units
1920 and 2122, closure is attained, but an element of incongruity is set up
in the case of 1920 because the key prepared is E-flat major (bars 281283)
while the key attained lies a third lower, B major (bar 285). Although B major
is reached by means of a chromatic bass line, it is, as it were, approached by the
wrong dominant. This is immediately corrected, however, in the case of units
2122, where the intensifying phrase leads to closure in its own key. Given the
proximity of the occurrences, units 1922 represent a large moment of intensification, a turning point. In other words, the local tension-resolution gestures
I have been describing are agents in a larger tension-creating move within the
macro form.
The most dramatic use of this intensifying phrase is embodied in the succession of units 2324, which parallel 910 in syntactic profile but differ fundamentally from a rhetorical point of view. Unit 23/1 is the third occurrence of the phrase
within a dramatically accelerating passage, the culmination of a stretto effect produced by the rhythm of the phrases temporal placement. This last then discharges
into the movements climax, units 23/224, which, as we have noted, replay the
syncopated rhythm from the opening of the work. There is no more dramatic
moment in the movement.
The intensifying phrase seems spent. Not surprisingly, it appears only once
more in the movement, completely expressively transformed (unit 32). The great
stroke in this ending lies in the conjunction of units 3233. The cadence-promising unit 32 finally finds resolution on the stable main theme of the movement.
Perhaps this is the destination that has been implied from the beginning, from
the first hearing of unit 9. If so, the listener has had to wait a very long time for
the phrase to find its true destinationas ending, as ultimate fulfillment, perhaps
as death.
Listeners who base their understanding of the form of the movement on the
trajectory mapped out by this intensifying phrase will conclude that this is one of
Mahlers most organic compositions. True, the phrase works in conjunction with
other material, so the organicism is not confined to one set of processes. Indeed,
the large-scale dynamic curve that the phrase creates is partly reinforced and
partly undermined by concurrent processes. Reinforcement comes, for example,
from the expanding role of the prelude (units 1, 10, and 24). On the other hand,
the recurrences of the main theme lack a patent dynamic profile. The theme seems
to sit in one place; it returns again and again as if to assure us of its inviolability.
Meaning in Mahler is at its most palpable when dimensional processes produce
this kind of conflict in the overall balance of dimensional tendencies. By focusing
on the production processes, paradigmatic analysis facilitates the construction of
such meanings.
278
PART II
Analyses
Narrative
Mahlerian narrative is melody-led. The leading of melody takes a number of
forms, ranging from a simple tune with accompaniment to a more complex texture in which a Hauptstimme migrates from one part of the orchestra to another.
Melody itself is not necessarily a salient tune but a more diffuse presence that
is understood as embodying the essential line or idea within a given passage.
Melody-led narration occurs on several levels, from the local to the global. What
such tellings amount to may be divined differently and put to different uses. At the
most immediate level, narrative points to the present in an active way; it shows
the way forward. Its meaning is hard to translate satisfactorily out of musical
language, but it can be described in terms of pace and material or rhetorical style
(which includes degrees of emphasis, repetition, and redundancy and a resultant
retrospective or prospective quality).
Mahlerian narrative typically occurs on more than one level, for the leading of
melody cannot in general be understood without reference to other dimensional
activities. Since it would be tedious to describe all of the facets of narrative in
Mahler, let me simply mention a few salient features.
The melody played by first violins as the main theme starting in bar 7 (quoted
in example 8.1) is in song mode, although its little motivic increments, by eschewing the long lines found elsewhere, suggest the halting quality of speech mode.
Notice that the horns are in dialogue with the strings and thus effect a complementary song mode. Coming after a spatially oriented (as distinct from a temporally
oriented) introduction which had no urgent melodic claims (bars 16), this song
signifies a beginning proper. An important feature of narrative phrases is how they
endwhether they conclude firmly by closing off a period or remain open and
thus elicit a desire for continuation.
How might we describe the narrative progress of this melody? An opening
2,
with a closing or downward tendency, is repeated. It continues with
idea, 3
the same rhythmic idea (incorporating an eighth-note) but changes direction and
heads up. This idea, too, is repeated in intensified form, incorporating an appoggiatura, B-natural. The pitch B takes on a life of its own, acquiring its own upbeat.
This gesture is repeated. These two little phrases mark the tensest moments in the
arc generated by the melody so far. Resolution is called for. Next comes an expansive phrase, marked espressivo by Mahler, which fulfills the expectations produced
so far, engendering a high point or superlative moment. This culminating phrase
4
3
2 pattern, the last two scale degrees
ends where the narration began with a 5
literally reclaiming the openness of the melodys point of departure. Whether one
hears a half-cadence, or the shadow of a half-cadence, or a circular motion, or an
abandoned process, it is clear that the process of the phrase is kept open. We hear
2 again, even though it now carries the sense of an echo, as if we had begun a
3
codetta, and it is then repeated in slightly modified form. The entire phrase carries a powerfully unified sense, leaving no doubt about which voice is the leading
one. We could complicate the foregoing description by pointing to the motivic
interplay (among horns, clarinets, bassoons, and English horn) that animates this
more primal string melody. However, these only contribute a sense of narration as
CHAPTER 8
Mahler
279
a more communal affair; they do not undermine the fact of narration in the first
place.
First violins literally take over in bar 18 as the tellers of the tale. We know that
the tale is the same but also that the teller is new. Novelty comes from the change
of register, beginning roughly an octave higher than where the previous period
began. The new teller will not merely repeat the previous telling; she must establish her own style of saying the same thing. The use of embellishments facilitates
this personalization of the narrators role. But the pacing of motivic exposition is
kept the same. Perhaps this phrase will be more expressive on account of its being
2
1 close (bars 2425), which fulfills
a repeat. Its most dramatic feature is the 3
the promise made in the previous phrase. Fulfillment is tinged with equivocation,
however. A structural dissonance at the phrase level arises as we move into an
adjacent higher register. Registral imbalance will need to be resolved eventually.
2 motive is kept alive, underAfter the attainment of 1 (bar 25), the promissory 3
2 in the major is
mining any sense of security brought on by this close. The 3
replaced by 32 in the minor to signal a new thematic impulse. What unit 3 tells is
mostly the same as what was told in unit 2, but the difference lies in the fact that
unit 3 resolves some of the cadential tension exhibited in the previous unit while
introducing its own new tensions. In this way, the process of the music is kept
open and alive. Parallel periods do not merely balance one another; antecedents
and consequents may provide answers on one level, but new questions often arise
when old ones are being laid to rest. The direct pairing of units 2 and 3 draws us
into this comparative exercise.
C HA P T E R
Nine
282
PART II
Analyses
form. But the expectations associated with sonata form are rather complex, for
surely Beethovens understanding of the form was an evolving one, not a fixed
or immutable one. Analysis errs when it fails to hypostatize such understanding, when, relying on a scheme fixed on paper, it fails to distinguish Beethovens
putative understanding of sonata form in, say, 1800 from his understanding in
1823. To the extent that an invariant impulse was ever enshrined in the form, it
resides in part in an initial feeling for a stylized contrast of key (and, to a lesser
extent, thematic material), which is then reconciled in an equally stylized set of
complementary moves. From here to the specifics of op. 130 is a long way, however.
In what follows, I will retain sonata-form options on a distant horizonas place
markers, perhapswhile concentrating on the movements materials and associated
procedures.
As a point of reference for the analysis, examples 9.19.15 provide a sketch
of the main materials of the movement broken into 15 sections and comprising a
total of 79 units, including subdivisions of units. These are mostly melodic ideas,
Example 9.1. Units 111 of Beethoven, String Quartet in B-flat Major, op. 130, first
movement.
1
2
3
2a
2b
3a
10
3b
3c
4
12
16
10
11
CHAPTER 9
283
and they are aligned in order to demonstrate their affiliations. Although several
additional units produced by nesting, recomposition, or motivic expansion could
be incorporated, the segmentation undertaken here should be adequate for a first
pass through the movement.
Exposition
Units 1 (bars 122) and 2 (bars 2242)
The movement opens with a complementary pair of units. The first unit begins
as a unison passage and is transformed after the fourth note into a full-voiced
chorale, ending as a question mark (on V). The second answers the first directly,
retaining the four-part harmonization and finishing with a perfect cadence, albeit
of the feminine rather than masculine variety. This pairing of units is both
closed and open. Within the harmonic and phrase-gestural domain, the succession is closed and balanced; within the registral domain, however, it remains open
because unit 2 lies in a higher register. Posing a question in a lower register and
answering it in a higher one introduces an incongruity or imbalance that provokes registral manipulation later in the movement. Note also that the contrast
between unharmonized (opening of unit 1) and harmonized (unit 2) textures
evokes a parallel contrast in modes of utterance. Something of the speech mode
may be inferred from the forced oneness of unison utterance; the ensuing hymn
brings on communal song.
Units 2a (bars 4352), 2b (bars 5371)
Using the gesture at the end of unit 2 as a point of departure, unit 2a moves the
melodic line up and 2b takes it to F through E-natural, thus tonicizing the dominant. There is something speech-like about these small utterances, all of them set
apart by rests, as if enacting an and-then succession.
Units 3 (bars 7291), 3a (bars 92111), 3b (bars 102111), 3c (bars 112131)
From bar 7 onward, a new idea is presented in imitation, almost like a ricercar.
Voices enter and are absorbed into the ruling texture in an orderly way until we
arrive at a cadence onrather than inthe dominant (bar 14). When first heard,
units 13 (bars 114) seem to function like a slow introduction. We will see later,
however, that their function is somewhat more complex. For one thing, the slow
introduction is repeated when the exposition is heard a second time. Then also,
the material returns elsewhere in the movement, suggesting that what we are hearing here is part of a larger whole. Indeed, Ratner suggests that, if we assemble
all of the slow material (bars 114, 2024, 9395, 98100, 101104, 213220, and
220222), the result is an aria in two-reprise form. It is as if Beethoven cut up a
compact aria and fed the parts into a larger movement to create two interlocking
284
PART II
Analyses
2
2a
2b
3
3a
3b
3c
If we overlook the suffixes, then the essential motion of the units is a 123
successiona linear progression with no sense of return. If we include the suffixes,
we notice that elements of the second and third units are immediately reused. If
we consider the fact, however, that unit 2 is closely based on unit 1, departing only
at its end to make a perfect cadence, then we see that the slow introduction is
essentially binary in its gesture, the first 7 bars based on one idea, the next 7 based
on a different one. The prospects of segmenting these bars differently serve as an
indication of the fluid nature of tonal form and material and might discourage us
from fixing our segments too categorically.
Units 4 (bars 15216), 5 (bars 17218)
A change of tempo from adagio ma non troppo to allegro brings contrasting material. Unit 4 is layered, featuring a virtuosic, descending sixteenth-note figure (first
violin) against a rising-fourth fanfare motive. (I quote the fanfare motive but not
the sixteenth-note figure in example 9.1.) Although the two seem equally functional in this initial appearance, the fanfare will later be endowed with a more
significant thematic function while the sixteenth-note concerto figure will retain
its role as embroidery.
1. Ratner, The Beethoven String Quartets, 217.
2. Here, you see, I cut off the fugue with a pair of scissors. . . . I introduced this short harp phrase, like
two bars of an accompaniment. Then the horns go on with their fugue as if nothing had happened. I
repeat it at regular intervals, here and here again. . . . You can eliminate these harp-solo interruptions,
paste the parts of the fugue together and it will be one whole piece. (Quoted in Edward T. Cone,
Stravinsky: The Progress of a Method, in Perspectives on Schoenberg and Stravinsky, ed. Cone and
Benjamin Boretz [New York: Norton, 1972], 164.)
CHAPTER 9
285
Although units 4 and 5 occur as a pair, they are open; they begin a sequential
pattern that implies continuation. In classic rhetoric, a third occurrence of the fanfare motive would be transformed to bring this particular process to a close and
to initiate another. But there is no third occurrence to speak of; instead, unit 5 is
extended to close on the dominant, thus creating a half-cadence similar to the one
that closed the slow introduction (end of unit 3).
Units 6 (bars 203222), 7 (bars 223242)
It sounds as if we are back to the slow introduction (Beethoven marks Tempo 1
in the score at bar 20), only we are now in V rather than in I. At this point, we might
begin to revise our sense of the emerging form. Oriented toward F as Vunit 7
sits entirely on an F pedalthe 67 pair of units reproduces the material of the
12 pair, but at a different tonal level. The presentation of the 67 pair is however
modified to incorporate stretto in unit 6 and a distinct expansion of register in
unit 7 (first violin).
Units 8 (bars 252271), 9 (bars 272311)
We hear the fanfare motive and its brilliant-style accompaniment as in units 45,
but in keeping with the dominant-key allegiance established in units 6 and 7, units
8 and 9 now sound in V. Like unit 5, unit 9 extends its temporal domain while shifting the tonal orientation of the phrase.
Units 10 (bars 31232), 11 (bars 332371)
The fanfare motif is sung by the bass voice in the tonic, B-flat (unit 10), and is
immediately repeated sequentially up a second (as in units 4 and 5). Then, with a
kind of teleological vengeance, it is extended and modified to culminate decisively
in a cadence at bars 3637. This is the first perfect cadence in the tonic since the
beginning of the allegro. With hindsight, we can see that the fanfare motive from
bars 1516 held within itself the potential for bass motion. This potential is realized in unit 11.
When dealing with complex textures like that of op. 130, where one often has
to reduce textures in order to pinpoint the essential motion, it is well to state the
obvious: discriminatory choices have to be made by the analyst regarding the location of a Hauptstimme. The sense of fulfillment represented in the bass voice in
unit 11 bears witness to such choosing.
Let us now pause to take stock of the activity within the first key area (bars 138,
units 111, figure 9.2). A clear hierarchy emerges in the concentrations of activity
within the thematic fields. The paradigm containing the fanfare motif leads (units
4, 5, 8, 9, 10, 11), followed by the imitative passage (units 3, 3a, 3b, 3c), then the
cadential motif (units 2, 2a, 2b, 7), and finally the inaugurating motif (units 1 and
6). This particular scale of importance comes strictly from the relatively abstract
perspective of our mode of paradigmatic representation; it says nothing about the
temporal extent of individual units nor their rhetorical manner.
286
PART II
Analyses
2
2a
2b
3
3a
3b
3c
4
5
8
9
10
11
Example 9.2. Units 1216c of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
12
13
14
15
16
16a
16b
16c
CHAPTER 9
287
18
19
20
288
PART II
Analyses
22
23
24
CHAPTER 9
289
Example 9.5. Units 2527 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
25
26
27
etc
Example 9.6. Units 2832 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
28
29
5-6
5- 6
5- 6
30
(
31
etc
32
etc
290
PART II
Analyses
Development
Beethoven begins the development in the same key in which he ended the exposition, namely, VI. This will be a short development35 bars only, less than half
the length of the preceding exposition.
CHAPTER 9
291
3
3a
3b
3c
4
5
6
7
8
9
10
11
12
13
14
15
16
16a
16b
16c
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
292
PART II
Analyses
Example 9.7. Units 3337 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
33
34
35
36
37
etc
102
34. Often in Beethoven, the freezing of thematic novelty is a way of marking other
processes for consciousness. In this case, the key scheme sports a rather radical
progression of major thirds: B-flat for the first key area, G-flat for the second and
for the start of the development, and now E[double-flat] or, enharmonically, D. The
progression is radical in the sense that it eschews the hierarchy of tonic-dominant
polarity for a more democratic and symmetrical set of major third relations. Each
of these four units is framed by silence, and although I have pointed to a thematic
parallelism in the pairing of 3334 against 3536, the overall effect of their disposition is a strategic aloofness, a refusal to connect. The question posed in unit 33 is
not answered by unit 34; rather, 34 goes about its own business, proposing its own
idea in hopes of getting a response. Similarly, the question posed by unit 35 is not
answered by unit 36. Of course, tonal continuity between 3334 and 3536 mediates the rejection of these opportunities for dialogue, but it is worth registering the
mosaic-like construction and the rereading of familiar tonal gesturesmoves that
we have encountered in Mahler and will encounter again in Stravinsky.
Unit 37 (bars 10131041)
Not for the first time in this movement, Beethoven extracts a cadential figure from
the end of one unitunit 35and uses it to begin a subsequent one (37). In this
case, the figure in question is repeated several times as if revving up the developmental engine. Our attention is arrested; we hold our breaths for something new.
Units 38 (bars 106109), 38a (bars 110115), 38b (bars116122), 38c
(bars 123129), 38d (bars 1301321)
The main thematic substance of the development is a new, lyrical tune that begins
with an octave exclamation and then winds down in a complementary stepwise
gesture. The tune is first sung by the cello (bars 106ff.) to an accompaniment comprising three previously heard motives: the long-short figure isolated in unit 37,
an incipit of the brilliant-style sixteenth-note figure that originated in unit 4, and
its companion fanfare figure. The ethos in these measures is unhurrieda lyrical
oasis, perhaps. Again, Beethovens freezing of thematic accretion allows the listener
CHAPTER 9
293
Example 9.8. Units 3838d of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
38
38a
38b
38c
38d
to contemplate other elements of the discourse, in this case the key scheme, which
begins with D major in unit 38, G major in units 38a and 38b, and C minor in 38c,
and finally, disrupting the pattern that has aligned key and theme, 38d rereads the
C minor melody within a iiVI progression in B-flat major. The attainment of Bflat signals the beginning of the recapitulation.
What a brief and relatively stable development! And what a contrast it presents
to the active exposition, with its numerous and regular changes in design. We may
be tempted to look for an explanation. And yet, any reason we offer will almost
by definition be a lie. To say, for example, that the brevity of the development
compensates for the extended exposition is to say something singularly unilluminating. No, there are no firm causalities in artistic production (that would only
produce critical casualties), no inevitabilities. There is only the artistic product in
its magnificent contingency. If we, burdened with various neuroses, feel a need to
offer an explanation rooted in causes and effects, no one can of course stop us.
Recapitulation
As always, we are immediately forced into comparative mode as we pass through
the recapitulation. To the extent that there exists a normative recapitulation function, it is to bring the nontonic material that was heard in the second part of the
expositionthe dissonant materialinto the orbit of the home key. By dwelling phenomenally on the tonic, the recapitulation meets the desire engendered by
the developmentwhose normative function is to ensure the absence of the tonic
within its spaceto effect a stylized reconciliation of materials previously associated with the tonic and nontonic spheres.
294
PART II
Analyses
Again, this normative scenario exists on a distant horizon for Beethoven. Let
us recall the main developments so far. The work began with a slow introduction that was repeated in the exposition (not like op. 59, no. 3, where the repeat
of the opening movement excludes the slow introduction). The first key area did
not work organically or consistently with one idea but celebrated heterogeneity
in design; it revealed a surplus of design features, we might say. The transition
to the second key was ambivalent, first pointing to the dominant key, but then
denying it as a destination; eventually, the music simply slid into VI as the alternative tonal premise. The VI was amply confirmed in the rest of the exposition
by changes of design and by cadential articulation. The development began with
fragments of material from early in the movement, but instead of working these
out in the manner of a proper Durchfhrung, it settled into a relaxed hurdygurdy tune that was taken through different keys in a kind of solar arrangement,
leading without dramatic or prolonged retransition to the recapitulation.
It is in the recapitulation that we encounter some of the most far-reaching
changes, not so much in the treatment of material but in the ordering of units
and in the key scheme. The first part seems to continue the development process
by bypassing the tonic, B-flat, and reserving the greater rhetorical strength for
the cadence on the subdominant, E-flat major (bar 145).3 Drawing selectively on
earlier material, the music then corrects itself and heads for a new key. Beethoven
chooses D-flat major for the second key material, thus providing a symmetrical
balance to the situation in the exposition (D-flat and G-flat lie a third on either
side of B-flat, although the lower third is major in contrast to the upper third). But
recapitulating material in D-flat is not enough; being a nontonic degree, it lacks
the resolving capacity of the tonic. Beethoven accordingly replays most of the
second key material in the home key, B-flat, to compensate for the additional dissonances incurred in the first part of the recapitulation. Finally, a coda rounds
things off by returning to and recomposing the thematic material associated with
the opening units of the movement. Some of these recompositions involve largescale thematic and voice-leading connections that are only minimally reflected in
a paradigmatic analysis. The details may be set out as in example 9.9.
Unit 39 (bars 1321341)
This is the same as 4.
Unit 40 (bars 13421363)
This is the same as 5.
Unit 41 (bars 13641391)
Unit 41 is an extension of 40, whose short-short-long motif it develops. This unit
will return in the coda.
3. Daniel Chua provides a vivid description of this and other moments in op. 130 in The Galitzin
Quartets of Beethoven (Princeton, NJ: Princeton University Press, 1995), 201225.
Example 9.9. Units 3943 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
39
40
41
etc
137
42
43
Example 9.10. Units 4452a of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
44
145
45
146
46
47
147
148
48
49
49a
50
51
52
52a
296
PART II
Analyses
CHAPTER 9
297
54
55
57
58
59
etc
60
61
62
63
etc
298
PART II
Analyses
The following set of equivalences shows that the second phase of the recapitulation, whose purpose is to transform previously dissonant material into consonance
by offering it in the home key, follows the exact order of the expositions material.
Unit 61 (bars 174178) = 22
Unit 62 (bars 1754178) = 23
Unit 63 (bars 1781821) = 24
Example 9.13. Units 6466 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
64
65
66
etc
5 -6
5-6
68
69
(
70
71
etc
Coda
The last two units of the recapitulation, 70 and 71, both recall and transform
their earlier functions. Unit 70, the equivalent of unit 31, provides the grandest
CHAPTER 9
299
rhetorical elaboration of B-flat, while its successor, 71, the equivalent of 32, adopts
a speech mode in preparing to go somewhere. In the exposition, unit 32 led to a
repeat of the exposition; here, it leads to yet another beginning, this one the beginning of the endthe coda. And it does so by taking up for the last time the material that opened the movement.
The following set of equivalences shows that the coda is essentially a recomposition of the opening of the movement (units 15). The only missing material is
unit 3, the passage of imitative counterpoint, some of whose content has already
appeared in units 1213 and 46.
Example 9.15. Units 7279 of Beethoven, String Quartet in B-flat Major, op. 130,
first movement.
72
73
73a
73b
218
73c
73d
73e
74
218
75
76
77
etc
78
79
300
PART II
Analyses
73
73a
74
73b
73c
75
73d
73e
76
77
78
79
CHAPTER 9
301
carries the process forward, reaching the expressive climax of the coda (bars 222
223) before discharging into a diatonic cadence (227229). In the remaining units,
78 and 79, bass answers trebles fanfare motive call. While unit 78 remains open (the
E-flat in bar 230 is left hanging), unit 79 takes the line to the tonic in bar 233.
The interpenetration of tempi, the play of register, and the juxtaposing of distinctly profiled material collectively endow this coda with a synthesizing function.
For some listeners, therefore, the tensions raised in the course of the movement
are nicely resolved on this final page. Unit 77 emerges as especially important in
this process of synthesis because, despite its allegro tempo, it subtends an adagio
sentiment. Put another way, it gestures toward song while being in speech mode,
the latter evident in the effort to speak words again and again. Song returns in
units 78 and 79.
For other listeners, however, the reification of contrasting materials does not
produce synthesis; rather, it upholds the contrasts. One tiny voice-leading event
at the very end of the work may support the view that things are not necessarily
nicely resolved: the first violins EA tritone in bar 232 is not resolved linearly
in the following bar but absorbed into the dominant-seventh chord. The high
melodic E-flat is a dissonant seventh that does not resolve to an adjacent D; rather,
it is, as it were, taken down two octaves to beat 2 of bar 233 (second violin) from
where it is led to an adjacent D. The movement finishes with a lingering sense of
an unresolved seventh.
These comments about the first movement of op. 130 aimed to identify the
building blocks, note the material affinities among them, and describe their roles
in the movement. The emphasis on building blocks may obscure the larger trajectories that some analysts would prefer to see and hear, but I have argued that
working at this level can be revealing. Perhaps the larger trajectories can take care
of themselves; or perhaps they are our own invention.
Regarding necessary and contingent repetition, the distinction is at once
unavoidable and problematic. Necessary repetition defines structure, perhaps
even ontology; we would not want to leave home without it. But reducing away
the repetitions, transformations, equivalences, and samenesses on account of their
ostensible redundancy amounts to setting aside the peculiar rhetoric that defines a
work; such an act leaves us with an empty shell, with only the potential for content.
Necessary repetition captures a trivial but indispensable quality, namely, the motivating forces that make a work possible; contingent repetition conveys a nontrivial
but dispensable quality, namely, the very lifeblood of a work, the traces left by
acts of composing out. Both are needed. There is no necessary repetition without
its contingencies; at the same time, contingent repetition is grounded in certain
necessities. Paradigmatic analysis, in turn, embodies this paradox by asserting
both the trivial and the nontrivial. By investing in the literalism or iconicity of
repetition, by encouraging the analysts pretense of a nave stance, it embodies the
innocence of a childs view. On the other hand, by displaying patterns that may
be interpreted semiotically as style or strategy, it broaches the mature world of
symbolic and indexical meaning; it leads us to a series of cores and shows us why
music matters.
302
PART II
Analyses
CHAPTER 9
303
that evoke nature, perhaps, and they are subjected to unnatural melodic embellishment. The harmony embodies presence only; it enacts no desire.
Unit 2 (bars 73112)
Stravinsky uses a distinctly constituted and memorably scored sonority as motive.
The chord is repeated, but the speaker appears to be overcome by a stutter.
Although the chord is literally sounded five times, we might group these into a
threefold utterance as a long-short, long-short, long pattern, where the shorts fall
off the longs like immediate echoes. The material gives rise to no real expectations.
It lacks melodic tendency and is therefore quite different from unit 1, which, while
static in terms of an overall progression, nevertheless displayed an incipient linear
tendency in the form of cadence-simulating falling thirds. The fullness of the scoring, including the filling in of the middle registers by brasses, produces a further
contrast between units 2 and 1.
Unit 3 (bars 113130.5)
The close harmony suggests that this might be part of a chorale. We accept the
authenticity of the dissonant harmonies within this particular composers idiolect. The melody, too, is hymn-like, but the relative brevity of the unit suggests that
this might be no more than a fragment. The sense of chorale is only emergent; the
music has a way to go before it can display the full identity of the chorale topos.
Unit 4 (bars 130.5133)
The sonority from unit 2 (the chord) interrupts, as if to say that it had not quite
finished its utterance when the hymn broke in at the end of bar 11. There is only
one sounding of the chord on this occasion.
Unit 5 (bars 14182)
This unit is a near-exact repeat of unit 1. (The first and last bars of unit 1 are suppressed.) The return of the bell motive marks the emerging form for attention. So
far, we have experienced a clearly differentiated succession of ideas, some juxtaposed with no obvious interdependency. Of course, we can begin to connect things
on paper if we so desire. For example, the sequence of melodic pitches in the chorale melody, E-flat, G, A-flat, E-flat (bars 1112), could be extended to the following F (bar 13), so that units 3 and 4 may be heard as connected on one level. And
because units 2 and 4 feature the same chord, they may be heard as one unit, with
unit 3 read as an interpolation. It is as if unit 1 delayed sounding its final member.
The emerging metamusical impulse is, of course, central to Stravinskys aesthetic.
Individual units, of course, might be segmented further. Unit 1, for example,
might be divided in two (bars 13 and 47), the second part being an embellishment and continuation of the first. Or it might be heard in three little segments
comprising a statement (bars 13), a truncated restatement (bars 451), and a
suffix (bars 5272). Although significant, these internal repetitions have not
304
PART II
Analyses
CHAPTER 9
305
4
5
6
7
10
4
5
6
10
306
PART II
Analyses
CHAPTER 9
307
308
PART II
Analyses
CHAPTER 9
309
For some time now, we have been hearing familiar materials in the manner of cinematic flashbacks. Their order reveals no consistency, their individual lengths vary,
but their topical identities are preserved. This is Stravinskys formal strategy, which
I will now render in a paradigmatic chart (figure 9.7).
Figure 9.7 Paradigmatic arrangement of units 135 in Stravinskys Symphonies of
Wind Instruments
1
4
5
6
7
9
13
10
11
12
14
15
16
17
18
20
21
19
22
23
25
24
26
27
28
29
30
31
32
33
35
34
310
PART II
Analyses
The bell motive and chorale serve as anchors; they occur periodically throughout
the movement. Although they are subject to recomposition, they mostly preserve their
essential form. That is, they change, but not in a developmental way. The contrasting
pastorale introduced in unit 16 and repeated as 17 and 18, given a suffix in 19, also
returns (23, 24, 28). While the portion of the movement dominated by these materials provides contrast, it is notable that the bell motive and chorale are not banished
from their domain. The most dramatic reorientation in the form will be registered
as an absence: the bell motive makes its last appearance as unit 27. After this, it cedes
power to the chorale which, in an expanded form, dominates the ending of the work.
Absence and presence in paradigmatic representation are often equally telling.
Unit 36 (bars 217270)
A wild dance deriving from the scherzo material is given full air time here. Its
opening melody has been adumbrated but within different expressive milieus: in
the little wind link of unit 6 and in the jazzy material of unit 30. This unit is longer than most in part because of the consistency of the scherzo expression. There
are, however, reminiscences of other ideas (in bars 258ff., for example, the melody
resembles the two Russian folk melodies). All of this wildness concludes with
shapes of savage simplicity: a five-finger, white-note figure, going up and down in
the bass (bars 267269).
Unit 37 (bars 271274)
The head of the closing chorale appears in a second premonition. (The first was in
bar 201.) On reflectionas distinct from immediately apprehending relations
the chord introduced at the beginning of the work (unit 2) and repeated (without
melodic content, so to speak) is shown to be a foreshadowing of that which begins
the closing chorale (example 9.16). The two recent premonitions (unit 31 and this
one, 37) encourage long-range associations with units 2, 4, 7, and 9. Significant is
the fact that earlier appearances of this form of the chord disappeared after unit
9, although they were figured as potential rather than actualizations.
Example 9.16. Comparison of chords in bars 78 and 271 of Stravinsky, Symphonies of Wind Instruments
bars 7-8
bar 271
Contents
disposed
linearly
[0
9]
[ 0
9]
CHAPTER 9
311
312
PART II
Analyses
37
38
39
Completing our stock taking, we may show the last four units as in figure 9.8.
This shows a linear unfolding broken only by the return of the big chorale at the
end. As far as the overall form, then, Stravinsky goes from juxtaposing blocks of
differentiated materials to suspending an extended chorale as the point of culmination. Some will hear something of a synthesis in the closing chorale while others
will imagine that the discontinuities and stark juxtapositions of earlier moments
have been absorbed in the continuous and serene chorale utterances.
CHAPTER 9
313
314
PART II
Analyses
If the ontology of units is as I have described it, then form in Stravinsky takes
on an additive quality. Succession replaces causal connection, and the distinction
between mere succession and a regulated progression based on a governing
construct is blurred. In Beethovens op. 130, for example, the question raised by
the first 2 bars demands an answer. That answer will be constrained by the 2-bar
lengthwhich it is obliged to accept, or whose rejection it is obliged to justify
either immediately or eventuallyand by the combined melodic and harmonic
progression, which registers incompletion. These causalities are possible because
of a shared language, a common practice. When, however, an aesthetic arises
whose motivating factors include commentary on convention or simple denial of
its principal prescriptions, the props for listening become inferable only from an
individual context. We cede all authority to the composer.
Additive construction and the relative autonomy of units undermine the sense
of music as narrative as distinct from music as order or event succession. Narration in Stravinsky often comes not from the music itself but from its contexts
and associations. The moving dance images in Petrushka, for example, allow us
to infer a plot as well as a sense of narration; stripped of dance, however, the burden of narration falls entirely on the movement of topoi. Alternatively, subsequent
soundings of the chord first heard in bar 7 of Symphonies deliver a sense of return
and progress. But is there a subject that enacts the narrative? If there is a subject
in Stravinsky, it is a split one. The Hauptstimme is often plural. Even in moments
where the texture features a clear melody and its accompaniment (as in the flute
and clarinet exchanges beginning in bar 71 of Symphonies), that which ostensibly
accompanies has strong claims to perceptual priority. Thus, a treble-bass polarity
is placed under the possibility of erasurepresent but at the same time undermined. The tendency in Stravinsky is toward an equalization of parts. (A potential
historical point emanating from this distinction concerns the difference between
Stravinsky and Schoenberg. Stravinsky does not merely assertverbally or precompositionallythis tendency toward overturning the conventional treble-bass
hierarchy. Schoenberg the theoretician, on the other hand, had much to say about
some of these elements of radicalism although the practical evidence in his scores
often leaves the polarity intact. Stravinsky, in this reading, was a far more radical
composer.)
method, draws an analogy between the composers technique of stratification and Bachs polyphonic melody, where strands of melody are begun, suspended, and eventually brought to a satisfactory conclusion. I do not doubt that score analyses can produce such connections in Stravinsky,
but there is a critical difference between Bachs polyphonic melody (or, for that matter, Beethovens)
and Stravinsky. The former operates within specified conventional constraints, so that the syntactic
governors are well understood or readily inferred from their contexts. Stravinskys constraints in
Symphonies (and elsewhere), by contrast, cannot be inferred or predicted; they must simply be
accepted. Indeed, part of the creativity at work in Stravinsky stems from his taking the license to
complete or not to complete something that is open (in conventional language). In Beethoven,
there is a contract between composer and listener; in Stravinsky, there is no a priori contract. Alternatively, we might say that the Stravinskian contract consists precisely in denying the existence of
an a priori contract.
CHAPTER 9
315
On the matter of representation, we might say that paradigmatic representation is more faithful to Stravinskys material than it is to Beethovens. The autonomy asserted by discrete numbers (1, 2, 3, etc.) captures the presumed autonomy
of Stravinskys units more meaningfully than it does Beethovens. For example, if
we recall the disposition of units in the opening of the two works studied in this
chapter as 1, 2, 2a, 2b, 3, 3a, 3b, 3c for op. 130 and as 1, 2, 3, 4 for bars 17 of Symphonies, we would say that missing from the representation of Beethoven are the linear
connections that would convey the dependency of adjacent units, including the
2
3
4
5 that holds the progression as a whole together.
stepwise melodic line 1
Units 2a and 2b in the quartet are in a literal sense caused by unit 2, or at least
made possible by it. In the Stravinsky, by contrast, and local melodic connections
notwithstanding, the sense of causation and dependency is less pertinent, so that
the representation in numbers fairly conveys what is going on.
These presumed oppositions between Beethoven and Stravinsky are presented
starkly in order to dramatize difference and encourage debate. It would be foolish to claim, however, that all of Beethoven can be reduced to the organic while
all of Stravinsky is inorganic, or that Stravinsky is always easier to segment than
Beethoven, or that hierarchic structuring is never elusive in Beethoven. Neither
style system is, in the end, reducible to such simple categories. There is discontinuity aplenty in Beethoven, material is sometimes organized in blocks, and certain
units succeed each other with a logic that is not always obviously causal. In Stravinsky, on the other hand, a local organicism is often at work, producing diminutions
like passing notes and especially neighbor-notes (or clusters of neighboring notes)
as well as conventional cadential gestures that often attract an ironic reading. Adjacent units may depend on each other, too. So the truth in the differences between
the two composers lies in between. For a more nuanced understanding, we will
need to embrace the interstitial wholeheartedly.
Music as discourse is probably indifferent to aesthetic choices. The degree of
meaningfulness may vary from context to context, and the dramatization of that
discourse may assume different forms, but the very possibility of reading a discourse from the ensemble of happenings that is designated as a work always exists.
An aesthetic based on the intentional violation of convention, for example, is just
as amenable to a discourse reading as one marked by the creative enactment of
such convention. Perhaps, in the end, the two approaches are indistinguishable.
Perhaps, the idea that Stravinsky stands as a (poetic) repetition of Beethoven is
not as outlandish as it might have seemed at first. Our task as analysts, in any
case, is not primarily to propagate such opinions (although historical understanding through music analysis remains an attractive option) but to make possible the
kinds of technical exploration that enable a reconstruction of the parameters that
animate each discourse.
Epilogue
At the close of these adventures in music analysis, it is tempting to try and put
everything together in a Procrustean bed, sum up the project neatly as if there
were no rough edges, no deviant parameters, no remainders, no imponderables.
Yet music, as we have seen, is an unwieldy animal; it signifies in divergent and
complex ways. Its meanings are constructed from a wide range of premises and
perspectives. The number and variety of technical approaches to analysis together
with the diversity of ideological leanings should discourage us from attempting
a quick, facile, or premature synthesis. Nevertheless, to stop without concluding,
even when the point of the conclusion is to restate the inconclusiveness of the
project, would be to display bad manners. So, let me briefly rehearse what I set out
to do in this book and why, and then mention some of the implications of what I
have done.
I set out to provide insight into how (Romantic) music works as discoursethe
nature of the material and the kinds of strategies available for shaping it. The aim
was to provide performers, listeners, and analysts with a pretext for playing in and
with (the elements of) musical compositions in order to deepen their appreciation
and understanding. The institutional umbrella for this activity is musical analysis,
and it is under this rubric that we conventionally place the collective actions of getting inside a musical composition in order to identify its elements and to observe
the dynamics of their interactions. There is, of course, nothing new about the curiosity that such actions betray; every analyst from Schenker and Tovey to Dahlhaus,
Ratner, and Adorno has been motivated by a desire to figure things out.
But which paths to understanding do we choose? How do we turn concept into
practice? What concrete steps allow us to establish or at least postulate an ontology for a given composition? What is an appropriate methodology for analysis?
It is here that we encounter striking differences in belief and approach. In this
book, I proceeded from the assumption that (Romantic) music works as a kind of
language that can be spoken (competently or otherwise), that music making is a
meaningful activity (for the participants first and foremost, but also for observers),
that the art of musical composition or poiesis is akin to discoursing in sound, and
317
318
Music as Discourse
that it is the purpose of analysis to convey aspects of that discoursing by drawing on a range of appropriate techniques. Since the ability to create presupposes
a prior ability to speak the relevant language, knowledge of the basic conventions
of organizing sound (as music) is indispensable. To ignore conventions, to turn a
blind eye to the grammatical constraints and stylistic opportunities available to an
individual composer, is to overlook the very ecology that made the work possible.
Indeed, a poor grasp of conventions can lead either to an underappreciation of
individual creativity or to an overvaluing of a particular achievement.
Reconstructing this ecology can be a formidable challenge, however, since it
is liable to involve us in long and arduous investigation (some of it biographical,
some of it social, some of it historical, and some of it musical). Attempting such
reconstructions here would probably have doubled the size of this project without
bringing proportional rewards in the form of conceptual clarity. So, I chose instead
to draw on a number of existing studies.
In the first part of the book, I began by rehearsing some of the ways in which
music is or is not like language (chapter 1). My 10 propositions on this topic were
designed with an interrogative and provocative purpose, not as laws orworse
commandments, but as propositions or hypotheses. Each of them is, of course, subject to further interrogation; indeed, writings by, among others, Nattiez, Adorno,
Schenker, Ratner, and Janklvitch speak directly or indirectly to issues raised by
thinking of music as language and to exploring the nature of musical meaning.
In chapters 2 and 3, I provided six criteria for capturing some of the salient
aspects of Romantic music. Again, my chosen criteria were designed to capture
certain conventions as prerequisites for insightful analysisthe functioning of
topoi or subjects of musical discourse; beginnings, middles, and endings; the use of
high points; periodicity, discontinuity, and parentheses; the exploration of registers
or modes of utterance, including speech mode, dance mode, and song mode; and
the cultivation of a narrative thread. Without claiming that each criterion is pertinent to every musical situation, it is nevertheless hard to imagine any listening to
Romantic music that is not shaped on some level by one or more of these factors.
Chapter 4 took us further into the heart of the musical language, demanding what we might as well call an insiders perspective. Musical insiders are those
individuals and communities who compose and/or perform music; they may also
include others whose perspectives as listeners and analysts are shaped fundamentally by these experiences. While certain features of Romantic musiclike topics or even high pointscan, as it were, be identified by outsiders, speculation
about the harmonic, contrapuntal, or phrase-structural foundations of a given
composition often have to come from the inside, from direct engagement with
the musical code itself. It is precisely this kind of engagement that has produced
some of the most sophisticated and influential views of musical structure (such as
that of Schenker). The generative approach to understanding which I adopted in
the fourth chapter invited participation in the dance of meaning production not
through detached observation and the subsequent spinning of (verbal) tales but
by direct participation through acts of hypothesizing compositional origins. I suggested that this kind of activity is akin to speaking music as a language. Indeed,
although logically obvious, the procedure of postulating a simplified or norma-
Epilogue
319
tive construct in order to set into relief a composers choices can be of profound
significance. The normative and conventional are reconstructed as background,
as foil, as ecology, as a nexus of possibility; the composers choices emerge against
this background of possibility, highlighting paths not taken and sounding a series
of might-have-beens.
My final theoretical task (chapter 5) was to isolate what many believe to be
the most indigenous feature of music, namely, its use of repetition, and to see
what insights flow from focusing on it. Tonal expression is unimaginable without
repetition, but repetition takes many forms and encompasses different levels of
structure. In chapter 5, I followed the lead of semiological analysts (Ruwet, Nattiez,
and Lidov, among others) in exploring a range of repetitions from simple pitch
retention through thematic transformation to harmonic reinterpretation. Rather
than place the emphasis on abstract method, however, the analyses in this chapter
were offered under specific rubrics stemming from intuited qualities that could
be made explicit in paradigmatic analyses: logical form versus chronological in
Chopin, discontinuity and additive construction in Mozart, and developing variation in Brahms. Janklvitchs claim that musics regime par excellence is one of
continuous mutation manifesting in variation and metamorphosis reinforces
the central justification for the paradigmatic method.1
With the theoretical part of my project completed in chapter 5, I turned to
a number of close readings of works by Liszt, Brahms, Mahler, Beethoven, and
Stravinsky (chapters 69). Although each analysis was framed as a semiological
study of units and their patterns of succession, our concerns, adumbrated in earlier analyses, were broader, embracing issues of formal strategy and narrative. The
case studies were designed not as systematic applications of method but as flexible explorations of musical articulation and the kinds of (formal and associative) meanings that are possible to discover. Analysis must always make discovery
possible; if it seems closed, if it provides answers rather than further questions, it
betrays its most potent attribute.
The implications of the books analyses may be drawn according to individual
interest. I have already hinted at a number of them in the course of specific analyses of such features as beginnings, middles, and endings in Mendelssohn; discontinuity in Stravinsky; logical form in Chopin; and tonal modeling in Beethoven.
Exploring modes of utterance by contrasting speech mode with song mode, for
example, may stimulate further speculation about the linguistic nature of music
while making possible a deeper exploration of its temporal dimensions (including
periodicity). A focus on closure likewise encourages further speculation about the
dynamics that shape individual compositions into meaningful discourses.
Attention to high points similarly conveys immediately perceptible aspects of
a work, while narrative trajectories may be experienced by isolating a migratory
voice from beginning to enda voice that may sometimes (choose to) remain
silent according to the rhetorical needs of the moment. Again, the fact that these
features were discussed in isolation does not mean that they are experienced that
320
Music as Discourse
way. On the contrary, they are all connected if not in actuality then very definitely
potentially. For example, high points are typical harbingers of closure; in other
contexts, they may signify specific moments within the narrative trajectory. The
musical experience tends, in principle, toward holism; the analytical procedure,
on the contrary, entails a (provisional) dismantling of that wholeit tends toward
isolation. Ideally, an analysis should unveil the conditions of possibility for a musical experience. Although it may serve to rationalize aspects of that experience,
analysis can never accurately report the full dimensions of that experience. Recognizing the intended partiality of analytical application may thus help us to evaluate
analytical outcomes more reasonably than expecting analysts to work miracles.
In order to begin to capture the work of the imagination as expressed in
Romantic music, we need to get close to it. We need to enter into those real as
well as imaginative spaces and temporalities that allow us to inspect a works elements at close quarters. We enter these spaces, however, not with the (mistaken)
belief that the object of analysis is a tabula rasa, but with the knowledge that it is
freighted with the routines, mannerisms, and meanings of a spoken (musical)
language. We enter these places armed with a feeling for precedent and possibility
and free of the delusion that we are about to recount the way in which a specific
artwork actually came into being. The power of analysis lies precisely in this openended pursuit of understanding through empathy, speculation, and play.
This view of analysis is, I believe, akin to what Adorno had in mind when he
enjoined us to pursue the truth content (Wahrheitsgehalt) of musical composition. It resonates with Schenkers search for (the truth of) the composers vision in
the unfolding of the Urlinie and in the various transformations of the contrapuntal
shapes of strict counterpoint into free composition. It is implicit in the qualities that
Ratner sought to capture with his notion of topics or subjects to be incorporated
into a musical discourse; topics lead us on a path to the discovery of truth in musical style, a discovery that may in turn illuminate the historical or even sociological aspects of a work. And it shares the idealization that led Nattiez to arrange his
Molino-inspired tripartition (consisting of a poeitic pole, a neutral level, and an
esthesic pole) into a mechanism for uniting the (indispensable and complementary)
perspectives of listeners, the production processes, and the work itself as an unmediated trace. This view of analysis may evenand strangely at firstbe affiliated
with Janklvitchs relentless protestations of the suitability of various categories
for music: form, expressivity, development, communicability, and translatability. Of
course, the material expression of this unifying ideologyif that is what it iswill
sooner or later produce differences; these theories cannot ultimately be collapsed
into one another. Their shared motivating impulse remains the same, however:
curiosity about the inner workings of our art. In the end, it is not the analytical
trace that matters most; the trace, in any case, yields too much to the imperatives of
capital accumulation. If, as Anthony Pople imagines, meaning is a journey rather
than a destination,2 then edification will come from doing, from undertaking the
journey. The materiality of analytical proceeding serves as its own reward.
2. Anthony Pople, Preface, in Theory, Analysis and Meaning in Music, ed. Pople (Cambridge: Cambridge University Press, 1994), xi.
B I B L IO G R A P H Y
Abbate, Carolyn. Unsung Voices: Opera and Musical Narrative in the Nineteenth Century.
Princeton, NJ: Princeton University Press, 1991.
. MusicDrastic or Gnostic? Critical Inquiry 30 (2004): 505536.
Adorno, Theodor. Mahler: A Musical Physiognomy, trans. Edmund Jephcott. Chicago: University of Chicago Press, 1992.
. Music and Language: A Fragment, in Quasi una Fantasia: Essays on Modern Music,
trans. Rodney Livingstone. London: Verso, 1992, 16.
. Beethoven: The Philosophy of Music, trans. Edmund Jephcott, ed. Rolf Tiedemann.
Stanford, CA: Stanford University Press, 1998.
. Essays on Music, ed. Richard Leppert. Berkeley: University of California Press, 2002.
. Schubert (1928), trans. Jonathan Dunsby and Beate Perrey. 19th-Century Music 24
(2005): 314.
Agawu, Kofi. Structural Highpoints in Schumanns Dichterliebe. Music Analysis 3 (1984):
159180.
. Tonal Strategy in the First Movement of Mahlers Tenth Symphony. 19th-Century
Music 9 (1986): 222233.
. Concepts of Closure and Chopins op. 28. Music Theory Spectrum 9 (1987): 117.
. Stravinskys Mass and Stravinsky Analysis. Music Theory Spectrum 11 (1989): 139163.
. Playing with Signs: A Semiotic Interpretation of Classic Music. Princeton, NJ: Princeton University Press, 1991.
..
. Does Music Theory Need Musicology? Current Musicology 53 (1993): 8998.
. Prolonged Counterpoint in Mahler, in Mahler Studies, ed. Stephen Hefling. Cambridge:
Cambridge University Press, 1997, 217247.
. The Challenge of Semiotics, in Rethinking Music, ed. Nicholas Cook and Mark
Everist. Oxford: Oxford University Press, 1999, 138160.
. Representing African Music: Postcolonial Notes, Queries, Positions. New York:
Routledge, 2003.
. How We Got Out of Analysis and How to Get Back In Again. Music Analysis 23
(2004): 267286.
Agmon, Eytan. The Bridges That Never Were: Schenker on the Contrapuntal Origin of the
Triad and the Seventh Chord. Music Theory Online 3 (1997).
Albrechtsberger, Johann Georg. Grndliche Anweisung zur Composition. Leipzig: Johann
Immanuel Breitkopf, 1790.
321
322
Bibliography
Allanbrook, Wye J. Rhythmic Gesture in Mozart: Le nozze di Figaro and Don Giovanni.
Chicago: University of Chicago Press, 1983.
..
Stuyvesant, NY: Pendragon, 1992, 125171.
. K331, First Movement: Once More, with Feeling, in Communication in EighteenthCentury Music, ed. Danuta Mirka and Kofi Agawu. Cambridge: Cambridge University
Press, 2008.
Almen, Byron, and Edward Pearsall, eds. Approaches to Meaning in Music. Bloomington:
Indiana University Press, 2006.
Andriessen, Louis, and Elmer Schnberger. Apollonian Clockwork: On Stravinsky, trans. Jeff
Hamburg. Oxford: Oxford University Press, 1989.
Ayrey, Craig. Review of Playing with Signs by K. Agawu. Times Higher Education Supplement 3 (May 1991): 7.
. Debussys Significant Connections: Metaphor and Metonymy in Analytical Method,
in Theory, Analysis and Meaning in Music, ed. Anthony Pople. Cambridge: Cambridge
University Press, 1994, 127151.
. Universe of Particulars: Subotnik, Deconstruction, and Chopin. Music Analysis 17
(1998): 339381.
Barry, Barbara. In Beethovens Clockshop: Discontinuity in the Opus 18 Quartets. Musical
Quarterly 88 (2005): 320337.
Barthes, Roland. Elements of Semiology, trans. Annette Lavers and Colin Smith. New York:
Hill and Wang, 1967.
. Mythologies, trans. Annette Lavers. New York: Hill and Wang, 1972.
Becker, Judith, and Alton Becker. A Grammar of the Musical Genre Srepegan. Journal of
Music Theory 24 (1979): 143.
Bekker, Paul. Beethoven. Berlin and Leipzig: Schuster and Loeffler, 1911.
Bellerman, Heinrich. Der Contrapunct; Oder Anleitung zur Stimmfhrung in der musikalischen Composition. Berlin: Julius Springer, 1862.
Bent, Ian D., ed. Music Analysis in the Nineteenth Century. 2 vols. Cambridge: Cambridge
University Press, 1994.
Bent, Ian, and Anthony Pople. Analysis. The New Grove Dictionary of Music and Musicians,
2nd ed. London: Macmillan, 2001.
Benveniste, mile. The Semiology of Language, in Semiotics: An Introductory Reader, ed.
Robert E. Innis. London: Hutchinson, 1986, 228246.
Berger, Karol. The Form of Chopins Ballade, op. 23. 19th-Century Music 20 (1996): 4671.
Bernhard, Christoph. Ausfhrlicher Bericht vom Gebrauche der Con- und Dissonantien,
Tractatus compositionis augmentatus in Die Kompositionslehre Heinrich Schtzens in der
Fassung seines Schlers Christoh Bernhard, ed. J. Mller-Blattau, 2d ed. Kassel: Brenreiter, 1963. English translation by W. Hilse, The Treatises of Christoph Bernhard. Music
Forum 3 (1973): 1196.
Berry, David Carson. A Topical Guide to Schenkerian Literature: An Annotated Bibliography
with Indices. Hillsdale, NY: Pendragon, 2004.
Bir, Dniel Pter. Plotting the Instrument: On the Changing Role of Timbre in Mahlers
Ninth Symphony and Weberns op. 21. Unpublished paper.
Boils, Charles L. Tepehua Thought-Song: A Case of Semantic Signalling. Ethnomusicology
11 (1967): 267292.
Bonds, Mark Evan. Wordless Discourse: Musical Form and the Metaphor of the Oration.
Cambridge, MA: Harvard University Press, 1991.
Bibliography
323
324
Bibliography
Bibliography
325
Garda, Michela. Lestetica musicale del Novecento: Tendenze e problemi. Rome: Carocci,
2007.
Grabcz, Mrta. Morphologie des oeuvres pour piano de Liszt: Influence du programme sur
lvolution des formes instrumentales, 2nd ed. Paris: Kim, 1996.
. Semiological Terminology in Musical Analysis, in Musical Semiotics in Growth, ed.
Eero Tarasti. Bloomington: Indiana University Press, 1996, 195218.
. Topos et dramaturgie: Analyse des signifis et de la strategie dans deux movements
symphoniques de B. Bartok. Degrs 109110 (2002): j1j18.
. Stylistic Evolution in Mozarts Symphonic Slow Movements: The Discursive-Passionate Schema. Intgral 20 (2006): 105129.
Hanslick, Eduard. Vom Musikalisch-Schnen [On the Musically Beautiful], trans. Martin
Cooper, excerpted in Music in European Thought 18511912, ed. Bojan Bujc. Cambridge: Cambridge University Press, 1988, 1239.
Hasty, Christopher. Segmentation and Process in Post-Tonal Music. Music Theory Spectrum 3 (1981): 5473.
. Meter as Rhythm. New York: Oxford University Press, 1997.
Hatten, Robert. Musical Meaning in Beethoven: Markedness, Correlation, and Interpretation.
Bloomington: Indiana University Press, 1994.
. Interpreting Musical Gestures, Topics, and Tropes: Mozart, Beethoven, Schubert. Bloomington: Indiana University Press, 2004.
Hefling, Stephen E. The Ninth Symphony, in The Mahler Companion, ed. Donald Mitchell
and Andrew Nicholson. Oxford: Oxford University Press, 2002, 467490.
Henrotte, Gayle A. Music as Language: A Semiotic Paradigm? in Semiotics 1984, ed. John
Deely. Lanham, MD: University Press of America, 1985, 163170.
Henschel, George. Personal Recollections of Johannes Brahms: Some of His Letters to and
Pages from a Journal Kept by George Henschel. New York: AMS, 1978.
Hepokoski, James, and Warren Darcy. Elements of Sonata Theory: Norms, Types, and Deformations in the Late-Eighteenth-Century Sonata. Oxford: Oxford University Press, 2006.
Hoeckner, Berthold. Programming the Absolute: Nineteenth-Century German Music and the
Hermeneutics of the Moment. Princeton, NJ: Princeton University Press, 1978.
Horton, Julian. Review of Bruckner Studies, ed. Paul Hawkshaw and Timothy Jackson.
Music Analysis 18 (1999): 155170.
. Bruckners Symphonies and Sonata Deformation Theory. Journal of the Society for
Musicology in Ireland 1 (20052006): 517.
Hughes, David W. Deep Structure and Surface Structure in Javanese Music: A Grammar of
Gendhing Lampah. Ethnomusicology 32(1) (1988): 2374.
Huron, David. Review of Highpoints: A Study of Melodic Peaks by Zohar Eitan. Music Perception 16(2) (1999): 257264.
Ivanovitch, Roman. Mozart and the Environment of Variation. Ph.D. diss., Yale University,
2004.
Jackson, Roland. Leitmotive and Form in the Tristan Prelude. Music Review 36 (1975): 4253.
Jakobson, Roman. Language in Relation to Other Communication Systems, in Jakobson,
Selected Writings, vol. 2. The Hague: Mouton, 1971, 697708.
Janklvitch, Vladimir. Music and the Ineffable [La Musique et lIneffable], trans. Carolyn
Abbate. Princeton, NJ: Princeton University Press, 2003.
Johns, Keith T. The Symphonic Poems of Franz Liszt, rev. ed. Stuyvesant, NY: Pendragon,
1996.
Jonas, Oswald. Introduction to the Theory of Heinrich Schenker: The Nature of the Musical
Work of Art, trans. and ed. John Rothgeb. New York: Longman, 1982 (orig. 1934).
326
Bibliography
Kaplan, Richard. Sonata Form in the Orchestral Works of Liszt: The Revolutionary Reconsidered. 19th-Century Music 8 (1984): 142152.
Katz, Adele. Challenge to Musical Tradition: A New Concept of Tonality. New York: Knopf,
1945.
Keiler, Alan. The Syntax of Prolongation: Part 1, in Theory Only 3 (1977): 327.
. Bernsteins The Unanswered Question and the Problem of Musical Competence.
Musical Quarterly 64 (1978): 195222.
Klein, Michael L. Intertextuality in Western Art Music. Bloomington: Indiana University
Press, 2005.
Kleinertz, Rainer..
Koch, Heinrich Christoph. Versuch einer Anleitung zur Composition, vols. 2 and 3. Leipzig:
Bhme, 1787 and 1793.
Kramer, Jonathan D. The Time of Music: New Meanings, New Temporalities, New Listening
Strategies. New York: Schirmer, 1988.
Kramer, Lawrence. Music and Poetry: The Nineteenth Century and After. Berkeley: University of California Press, 1984.
. Music as Cultural Practice. Berkeley: University of California Press, 1990.
Krebs, Harald. The Unifying Function of Neighboring Motion in Stravinskys Sacre du
Printemps. Indiana Theory Review 8 (1987): 313.
Krumhansl, Carol. Topic in Music: An Empirical Study of Memorability, Openness, and
Emotion in Mozarts String Quintet in C Major and Beethovens String Quartet in A
Minor. Music Perception 16 (1998): 119132.
La Grange, Henry-Louis de. Gustav Mahler: A New Life Cut Short (1907-1911). Oxford:
Oxford University Press, 2008.
Larson, Steve. A Tonal Model of an Atonal Piece: Schoenbergs opus 15, number 2. Perspectives of New Music 25 (1987): 418433.
Leichtentritt, Hugo. Musical Form. Cambridge, MA: Harvard University Press, 1951 (orig.
1911).
Lendvai, Erno. Bela Bartk: An Analysis of His Music. London: Kahn & Averill, 1971.
Lerdahl, Fred, and Ray Jackendoff. A Generative Theory of Tonal Music. Cambridge, MA:
MIT Press, 1983.
Lester, Joel. J. S. Bach Teaches Us How to Compose: Four Pattern Prelude of the WellTempered Clavier. College Music Symposium 38 (1998): 3346.
Lewin, David. Musical Form and Transformation: Four Analytic Essays. New Haven, CT:
Yale University Press, 1993.
. Music Theory, Phenomenology, and Modes of Perception, in Lewin, Studies in
Music with Text. Oxford: Oxford University Press, 2006, 53108.
Lewis, Christopher Orlo. Tonal Coherence in Mahlers Ninth Symphony. Ann Arbor: UMI
Press, 1984.
Lidov, David. On Musical Phrase. Montreal: Faculty of Music, University of Montreal,
1975.
. Nattiezs Semiotics of Music. Canadian Journal of Research in Semiotics 5 (1977):
1354.
. Mind and Body in Music. Semiotica 66 (1987): 6997.
. The Lamento di Tristano, in Models of Music Analysis: Music before 1600, ed. Mark
Everist. Oxford: Blackwell, 1992, 6692.
. Elements of Semiotics. New York: St. Martins Press, 1999.
. Is Language a Music? Writings on Musical Form and Signification. Bloomington: Indiana University Press, 2005.
Bibliography
327
Lowe, Melanie. Pleasure and Meaning in the Classical Symphony. Bloomington: Indiana
University Press, 2007.
Marx, A. B. Die Lehre von der musikalischen Komposition, praktisch-theoretisch. Leipzig:
Breitkopf & Hrtel, 18371847.
Mattheson, Johann. Der vollkommene Capellmeister, trans. Ernest Harriss. Ann Arbor, MI:
UMI Research Press, 1981 (orig. 1739).
Maus, Fred Everett. Narratology, Narrativity, in The New Grove Dictionary of Music and
Musicians, 2nd ed. London: Macmillan, 2001.
McClary, Susan. Conventional Wisdom: The Content of Musical Form. Berkeley: University
of California Press, 2001.
McCreless, Patrick. Syntagmatics and Paradigmatics: Some Implications for the Analysis
of Chromaticism in Tonal Music. Music Theory Spectrum 13 (1991): 147178.
. Music and Rhetoric, in The Cambridge History of Western Music Theory, ed. Thomas
Christensen. Cambridge: Cambridge University Press, 2002, 847879.
. Anatomy of a Gesture: From Davidovsky to Chopin and Back, in Approaches to
Meaning in Music, ed. Byron Almen and Edward Pearsall. Bloomington: Indiana University Press, 2006, 1140.
McDonald, Matthew. Silent Narration: Elements of Narrative in Ivess The Unanswered
Question. 19th-Century Music 27 (2004): 263286.
McKay, Nicholas Peter. On Topics Today. Zeitschrift der Gesellschaft fr Musiktheorie 4 (2007).. Accessed August 12, 2008.
Metzer, David. Quotation and Cultural Meaning in Twentieth-Century Music. Cambridge:
Cambridge University Press, 2003.
Meyer, Leonard B. Explaining Music: Essays and Explorations. Chicago: University of
Chicago Press, 1973.
. Exploiting Limits: Creation, Archetypes and Style Change. Daedalus (1980): 177205.
. Style and Music: Theory, History, and Ideology. Philadelphia: University of Pennsylvania Press, 1989.
Micznik, Vera. Music and Narrative Revisited: Degrees of Narrativity in Mahler. Journal
of the Royal Musical Association 126 (2001): 193249.
Mitchell, Donald. Gustav Mahler, vol. 3: Songs and Symphonies of Life and Death. London:
Faber and Faber, 1985.
Molino, Jean. Musical Fact and the Semiology of Music, trans. J. A. Underwood. Music
Analysis 9 (1990): 104156.
Monelle, Raymond. Linguistics and Semiotics in Music. Chur, Switzerland: Harwood, 1992.
. The Sense of Music: Semiotic Essays. Princeton, NJ: Princeton University Press, 2000.
. The Musical Topic: Hunt, Military and Pastoral. Bloomington: Indiana University
Press, 2006.
Monson, Ingrid. Saying Something: Jazz Improvisation and Interaction. Chicago: University
of Chicago Press, 1996.
Morgan, Robert P. Schenker and the Theoretical Tradition. College Music Symposium 18
(1978): 7296.
. Coda as Culmination: The First Movement of the Eroica Symphony, in Music
Theory and the Exploration of the Past, ed. Christopher Hatch and David W. Bernstein.
Chicago: University of Chicago Press, 1993, 357376.
Morgan, Robert P. Circular Form in the Tristan Prelude. Journal of the American Musicological Society 53 (2000): 69103.
. The Concept of Unity and Musical Analysis. Music Analysis 22 (2003): 750.
Muns, George. Climax in Music. Ph.D. diss., University of North Carolina, 1955.
Narmour, Eugene. The Analysis and Cognition of Basic Melodic Structures: The ImplicationRealization Model. Chicago: University of Chicago Press, 1990.
328
Bibliography
Nattiez, Jean-Jacques. Varses Density 21.5: A Study in Semiological Analysis, trans. Anna
Barry. Music Analysis 1 (1982): 243340.
. Music and Discourse: Toward a Semiology of Music, trans. Carolyn Abbate. Princeton,
NJ: Princeton University Press, 1990.
Neubauer, John. The Emancipation of Music from Language: Departure from Mimesis in
Eighteenth-Century Aesthetics. New Haven, CT: Yale University Press, 1986.
Newcomb, Anthony. Schumann and Late Eighteenth-Century Narrative Strategies. 19thCentury Music 11 (1987): 164174.
Notley, Margaret. Late-Nineteenth-Century Chamber Music and the Cult of the Classical
Adagio. 19th-Century Music 23 (1999): 3361.
Oster, Ernst. The Dramatic Character of the Egmont Overture, in Aspects of Schenkerian
Theory, ed. David Beach. New Haven, CT: Yale University Press, 1983, 209222.
Oxford English Dictionary, 3rd ed. Oxford: Oxford University Press, 2007.
Perrey, Beate Julia. Schumanns Dichterliebe and Early Romantic Poetics: Fragmentation of
Desire. Cambridge: Cambridge University Press, 2003.
Pople, Anthony, ed. Theory, Analysis and Meaning in Music. Cambridge: Cambridge University Press, 1994.
Powers, Harold. Language Models and Music Analysis. Ethnomusicology 24 (1980): 160.
. Reading Mozarts Music: Text and Topic, Sense and Syntax. Current Musicology 57
(1995): 544.
Puffett, Derrick. Bruckners Way: The Adagio of the Ninth Symphony. Music Analysis 18
(1999): 5100.
Ratner, Leonard G. Music: The Listeners Art, 2nd ed. New York: McGraw-Hill, 1966.
. Classic Music: Expression, Form, and Style. New York: Schirmer, 1980.
. Topical Content in Mozarts Keyboard Sonatas. Early Music 19 (1991): 615619.
. Romantic Music: Sound and Syntax. New York: Schirmer, 1992.
. The Beethoven String Quartets: Compositional Strategies and Rhetoric. Stanford, CA:
Stanford Bookstore, 1995.
Ratz, Erwin. Einfhrung in die musikalische Formenlehre, 3rd ed. Vienna: Universal, 1973.
Reed, John. The Schubert Song Companion. Manchester: Manchester University Press, 1985.
Rehding, Alex. Liszts Musical Monuments. 19th-Century Music 26 (2002): 5272.
Rti, Rudolph. The Thematic Process in Music. New York: Macmillan, 1951.
Reynolds, Christopher. Motives for Allusion: Context and Content in Nineteenth-Century
Music. Cambridge, MA: Harvard University Press, 2003.
Richards, Paul. The Emotions at War: Atrocity as Piacular Rite in Sierra Leone, in Public
Emotions, ed. Perri 6, Susannah Radstone, Corrine Squire, and Amal Treacher. London:
Palgrave Macmillan, 2006, 6284.
Richter, Ernst Friedrich. Lehrbuch des einfachen und doppelten Kontrapunkts. Leipzig:
Breitkopf & Hrtel, 1872.
Riemann, Hugo. Vereinfachter Harmonielehre; oder, Die Lehre von den tonalen Funktionen
der Akkorde. London: Augener, 1895.
Riezler, Walter. Beethoven. Translated by G. D. H. Pidcock. New York: Vienna House, 1938.
Rosand, Ellen. The Descending Tetrachord: An Emblem of Lament. Musical Quarterly 65
(1979): 346359.
Rosen, Charles. The Classical Style: Haydn, Mozart, Beethoven. New York: Norton, 1972.
Rothstein, William. Phrase Rhythm in Tonal Music. New York: Schirmer, 1989.
. Transformations of Cadential Formulae in Music by Corelli and His Successors,
in Studies from the Third International Schenker Symposium, ed. Allen Cadwallader.
Hildersheim, Germany: Olms, 2006, 245278.
Bibliography
329
Rowell, Lewis. The Creation of Audible Time, in The Study of Time, vol. 4, ed. J. T. Fraser,
N. Lawrence, and D. Park. New York: Springer, 1981, 198210.
Ruwet, Nicolas. Thorie et mthodes dans les etudes musicales: Quelques remarques rtrospectives et prliminaires. Music en jeu 17 (1975): 1136.
. Methods of Analysis in Musicology, trans. Mark Everist. Music Analysis 6 (1987):
1136.
Salzer, Felix. Structural Hearing: Tonal Coherence in Music. 2 vols. New York: Dover, 1952.
Salzer, Felix, and Carl Schachter. Counterpoint in Composition: The Study of Voice Leading.
New York: Columbia University Press, 1989.
Samson, Jim. Music in Transition: A Study of Tonal Expansion and Atonality 19001920.
London: Dent, 1977.
. Extended Forms: Ballades, Scherzos and Fantasies, in The Cambridge Companion to
Chopin, ed. Samson. Cambridge: Cambridge University Press, 1992, 101123.
. Virtuosity and the Musical Work: The Transcendental Studies of Liszt. Cambridge:
Cambridge University Press, 2007.
Samuels, Robert. Music as Text: Mahler, Schumann and Issues in Analysis, in Theory, Analysis and Meaning in Music, ed. Anthony Pople. Cambridge: Cambridge University Press,
1994, 152163.
. Mahlers Sixth Symphony: A Study in Musical Semiotics. Cambridge: Cambridge University Press, 1995.
Saussure, Ferdinand de. Course in General Linguistics, ed. C. Bally and A. Sechehaye. New
York: McGraw-Hill, 1966 (original 1915).
Schenker, Heinrich. Das Meisterwerk in der Musik, vol. 2. Munich: Drei Masken, 1926.
. Five Graphic Music Analyses, ed. Felix Salzer. New York: Dover, 1969.
. Free Composition, trans. Ernst Oster. New York: Longman, 1979.
. Counterpoint: A Translation of Kontrapunkt, trans. John Rothgeb and Jrgen Thym.
New York: Schirmer, 1987.
. Der Tonwille: Pamphlets in Witness of the Immutable Laws of Music, vol. 1, ed. William
Drabkin, trans. Ian Bent et al. Oxford: Oxford University Press, 2004.
Schoenberg, Arnold. Fundamentals of Musical Composition. New York: St. Martins Press,
1967.
Sechter, Simon. Analysis of the Finale of Mozarts Symphony no. [41] in C [K551(Jupiter)],
excerpted in Music Analysis in the Nineteenth Century, vol. 1: Fugue, Form and Style, ed.
Ian D. Bent. Cambridge: Cambridge University Press, 1994, 8296.
Sheinbaum, John J. Timbre, Form and Fin-de-Sicle Refractions in Mahlers Symphonies.
Ph.D. diss., Cornell University, 2002.
Silbiger, Alexander. Il chitarrino le suoner: Commedia dellarte in Mozarts Piano Sonata
K. 332. Paper presented at the annual meeting of the Mozart Society of America, Kansas
City, November 5, 1999.
Sisman, Elaine R. Brahms Slow Movements: Reinventing the Closed Forms, in Brahms
Studies, ed. George Bozarth. Oxford: Oxford University Press, 1990, 79103.
. Haydn and the Classical Variation. Cambridge, MA: Harvard University Press, 1993.
. Mozart: The Jupiter Symphony. Cambridge: Cambridge University Press, 1993.
. Genre, Gesture and Meaning in Mozarts Prague Symphony, in Mozart Studies, vol.
2, ed. Cliff Eisen. Oxford: Oxford University Press, 1997, 2784.
Smith, Peter H. Expressive Forms in Brahms Instrumental Music: Structure and Meaning in
His Werther Quartet. Bloomington: Indiana University Press, 2005.
Spitzer, John. Grammar of Improvised Ornamentation: Jean Rousseaus Viol Treatise of
1687. Journal of Music Theory 33 (1989): 299332.
330
Bibliography
Spitzer, Michael. Metaphor and Musical Thought. Chicago: University of Chicago Press, 2004.
Stell, Jason T. The Flat-7th Scale Degree in Tonal Music. Ph.D. diss., Princeton University,
2006.
Straus, Joseph N. A Principle of Voice Leading in the Music of Stravinsky. Music Theory
Spectrum 4 (1982): 106124.
Tarasti, Eero. A Theory of Musical Semiotics. Bloomington: Indiana University Press, 1994.
. Signs of Music: A Guide to Musical Semiotics. Berlin: de Gruyter, 2002.
Tarasti, Eero, ed. Musical Semiotics in Growth. Bloomington: Indiana University Press,
1996.
. Musical Semiotics Revisited. Helsinki: International Semiotics Institute, 2003.
Temperley, David. Communicative Pressure and the Evolution of Musical Styles. Music
Perception 21 (2004): 313337.
Tovey, Donald Francis. A Musician Talks, vol. 2: Musical Textures. Oxford: Oxford University
Press, 1941.
. Essays and Lectures on Music. Oxford: Oxford University Press, 1949.
Urban, Greg. Ritual Wailing in Amerindian Brazil. American Anthropologist 90 (1988):
385400.
Vaccaro, Jean-Michel. Proposition dun analyse pour une polyphonie vocale dux vie sicle.
Revue de musicology 61 (1975): 3558.
van den Toorn, Pieter. The Music of Stravinsky. New Haven, CT: Yale University Press, 1983.
Wallace, Robin. Background and Expression in the First Movement of Beethovens op. 132.
Journal of Musicology 7 (1989): 320.
Walsh, Stephen. Stravinsky: A Creative Spring: Russia and France, 18821934. Berkeley: University of California Press, 1999.
Watson, Derek. Liszt. London: Dent, 1989.
White, Eric Walter. Stravinsky: The Composer and His Works. Berkeley: University of California Press, 1966.
Whittall, Arnold. Romantic Music: A Concise Survey from Schubert to Sibelius. London:
Thames and Hudson, 1987.
. Musical Composition in the Twentieth Century. Oxford: Oxford University Press,
2000.
Whitworth, Paul John. Aspects of Mahlers Musical Style: An Analytical Study. Ph.D. diss.,
Cornell University, 2002.
Williamson, John. Mahler, Hermeneutics and Analysis. Music Analysis 10 (1991): 357373.
. Music of Hans Pfitzner. Oxford: Clarendon, 1992.
. Dissonance and Middleground Prolongations in Mahlers Later Music, in Mahler
Studies, ed. Stephen E. Hefling. Cambridge: Cambridge University Press, 1997, 248270.
Wilson, Paul. Concepts of Prolongation and Bartks opus 20. Music Theory Spectrum 6
(1984): 7989.
Wintle, Christopher., 2969.
Wintle, Christopher, ed. Hans Keller (19191985): A Memorial Symposium. Music Analysis 5 (1986): 343440.
Wood, Patrick. Paganinis Classical Concerti. Unpublished paper.
Zbikowski, Lawrence M. Conceptualizing Music: Cognitive Structure, Theory, and Analysis.
New York: Oxford University Press, 2002.
. Musical Communication in the Eighteenth Century, in Communication in Eighteenth-Century Music, ed. Danuta Mirka and Kofi Agawu. Cambridge: Cambridge University Press, 2008, 283309.
INDEX
Bartk, Bla, 3, 49
Improvisations for Piano, op. 20,
no. 1, 9093
Music for Strings, Percussion and
Celesta, 71
Becker, Judith and Alton, 16
Beethoven, 4, 6, 7, 8, 17, 54, 93, 224,
274, 276
Piano Sonata in C major op. 53
(Waldstein), first movement,
127128
Piano Sonata in E-flat major op. 81a
(Les Adieux), 257
String Quartet in D major, op. 18, no.
3, first movement, 184198, 290
String Quartet in F major, op. 59,
no. 1, first movement, 97
String Quartet in F major, op. 59,
no. 1, third movement, 9798
String Quartet in B-flat major, op. 130,
first movement, 12, 281301
String Quartet in B-flat major, op. 130,
third movement, 99101
String Quartet in A minor, op. 132, first
movement, 9495
String Quartet in A minor, op. 132,
fourth movement, 101
Symphony No. 3 (Eroica), 115
Symphony No. 3 (Eroica), slow
movement, 42
Symphony No. 4, second movement,
245
Symphony No. 5, first movement, 25,
103104
Symphony No. 5, finale, 52
See also late Beethoven
Beethoven and Stravinsky compared,
312315
331
332
Index
Index
Eitan, Zohar, 62n.31
Everett, Daniel, 21n.21
Ewe (African people), 22
Fabian, Johannes, 18n.5
Feil, Arnold, 82n.5
Feld, Steve, and Aaron Fox, 17, 22
Floros, Constantin, 47n.11, 254, 273
foreground vs. background, 11, 111, 113
form, 78, 6061
in J. S. Bach, 149153
as beginning, middle, and ending, 52
in Liszt, 220226
in Mahler, 262, 271275, 277
paradigmatic approach to, 166167
as periodicity, 7677
as prolongation, 130131
in Stravinsky, 309330, 312, 314
formalism, 5, 6
Forte, Allen, 313n.7
and Steven Gilbert, 151
fragments, 33, 291292
Frisch, Walter, 239240, 252
functional music, 23
Fux, Johann, 114
generative analysis, 3334, 113, 122129
Gluck, Orfeo ed Euridice, 224
God Save the King, 168175
Grbocz, Mrta, 9, 46, 49, 103
ground bass, 8586
Handel, Suites de pieces, 2nd collection,
no. 1, Air with Variations, 115116
Hanslick, Eduard, 189190
harmony
in paradigmatic analysis, 172
vs. melody, 25
Hasty, Christopher, 76, 184
Hatten, Robert, 4, 9, 43, 45, 50n.15, 93n.8,
113n.4
Hauptstimme, 259, 279, 314
Haydn, Franz Joseph, 22
Chaos, from The Creation, 112
Hefling, Stephen, 254n.2, 273
Heine, Heinrich, 85, 93, 104
Henrotte, Gayle, 21, 27
Henschel, Georg, 203204
Hepokoski, James, and Warren Darcy, 8,
75, 166n.5
333
334
Index
Index
Paganini, Niccol, 17, 46n.10
paradigm (vs. syntagm), 163164. See
also paradigmatic analysis
paradigmatic analysis, 12, 163207, 252,
253, 271272, 274275, 284, 286,
301, 304305, 309310
parenthesis, 11, 9598, 259, 269
periodicity, 7, 11, 7598
Perrey, Beate, 106n.16
Plato, 15
polyphonic melody, 313n.7
Pople, Anthony, 320
Powers, Harold, 16, 17, 20, 21
preference rules (vs. well-formedness
rules), 19
prolongation, 9697, 122125, 158160.
See also prolonged counterpoint
prolonged counterpoint, 129162
prototypes, 11, 131
public (vs. private), 4243
Puccini, Giacomo
Tosca, 23
Puffett, Derrick, 33n.45
question vs. answer, 3536, 241, 283, 292
Rameau, Jean-Philippe, 116
Ratner, Leonard, 3, 5, 4142, 43, 45, 75,
176, 196, 283, 317, 318, 320
Ratz, Erwin, 128
recitative vs. aria, 22, 101
recomposition, 3637, 248
Reed, John, 82n.5
Reger, Max, 120
repetition, 12, 31, 281, 300, 301, 305,
312313, 319
Reynolds, Christopher, 50n.14
rhetoric, 106, 158160, 242, 285,
301, 313
rhythm, 312
of theoretical system, 6869
ricercar, 283
Richards, Paul, 21n23
Richter, 114
Riemann, Hugo, 16, 75
Riezler, Walter, 312
Rosand, Ellen, 146
Rosen, Charles, 9, 52, 75, 166, 224
Rothstein, William, 8, 75, 136n.27
Rousseau, Jean, 17
335
Rowell, Lewis, 52
Ruwet, Nicolas, 16, 21, 165, 319
Saint Augustine, 15
salience (in Romantic music), 11, 318
Salzer, Felix
Structural Hearing, 38, 118, 313n.7
Samson, Jim, 46n.10
Saussure, Ferdinand, 25, 71
Schenker, Heinrich, 3, 5, 6, 8, 11, 18, 29,
51, 58n.29, 69n.36, 112, 113118,
161, 175, 313, 317, 318, 320
Schneider, Marius, 16
Schoenberg, Arnold, 8, 75, 240, 314
Schubert, Franz, 3, 4, 6, 17, 54, 98
An die Musik, 6365
Dass sie hier gewesen, 135136
Wo ist Sylvia? 80
Der greise Kopf, from Winterreise, 10
Frhlingstraum, from Winterreise, 119
Der Lindenbaum, from Winterreise,
121122
Im Dorfe, from Winterreise,
8285
Piano sonata in C minor D. 958,
Adagio, 3035
String Quintet in C major, first
movement, 76, 118119, 128129
String Quintet in C major, second
movement, 121
Schumann, Robert, 3, 98, 276
Dichterliebe, 101, 104106
Ich grolle nicht, from Dichterliebe,
8587
Frauenliebe und Leben, 42
Fantasy for piano op. 17, 52
Piano Quintet op. 44, 76
Der Dichter spricht, from
Kinderszenen, 101102
Sechter, Simon, 125126, 129
segmentation, 184188, 240, 302,
33n.45
criteria for, 254256
of music and language, 24
semiology and Schenkerian theory, 113
Sheinbaum, John, 255n.3
Singer, Otto, 240n.2
Sisman, Elaine, 7
Smetana, Bedrich, 276
sonata deformation, 166
336
Index | https://id.scribd.com/doc/314994182/Music-as-Discourse | CC-MAIN-2019-30 | refinedweb | 83,306 | 51.48 |
Details
- Type:
New Feature
- Status: Closed
- Priority:
Minor
- Resolution: Fixed
- Affects Version/s: None
-
- Component/s: core/search
- Labels:None
- Lucene Fields:Patch Available
Description();
Issue Links
- is related to
LUCENE-1465 NearSpansOrdered.getPayload does not return the payload from the minimum match span
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
Do you mean in a separate interface? I suppose I should for backward compatibility so that people with existing Span implementations outside of Lucene aren't broken..
My mistake, I thought Spans was an abstract class, but it is an interface.
That also means that Spans should not be changed at all, interfaces are forever.
Something like this could do nicely:
public interface PayloadSpans extends Spans{ // as above }
I'd prefer the payload "core" classes to stay in their own package search/payload
because they may well turn out to be useful in other circumstances, for example
as a way to avoid disjunctions with many terms.
At the moment I have no preference for a package for the PayloadSpans above,
it could be search.spans or search.payloads.
public interface PayloadSpans extends SpansUnknown macro: { // as above }
I think this is problematic too, unfortunately, since many spans actually contain other spans, so there is no way to safely cast even in the internal implementations.
Alternative might be to add SpanQuery.getPayloadSpans() but that is ugly, too.
I wish there was an equivalent way to deprecated that allowed one to tell people new methods are coming, but that won't break the existing interface. Semantics of it would need to be figured out, but it would be useful here to just be able to let people know that we want to add to the Spans interface, but they just get a warning when compiling until we make it official.
I suppose the right thing to do if we really want this to work is to deprecate Spans and SpanQuery.getSpans() and introduce a new form of Spans (maybe as an abstract class this time?)
Or am I missing something that provides a clearer way of doing this?
I think I would just go ahead and create a parallel class hierarchy starting from class PayloadSpanQuery with a getPayloadSpans() method, and try and use delegation to the various SpanQueries and their Spans as much as possible.
That means you would end up with this a few times:
return new PayLoadSpans (){ Spans delegatedTo = aFinalSpans; .... some Spans methods directly delegated... }
;
When this delegation happens too often, it could even be factored out into its own superclass.
If the delegation turns out to be a performance problem it might be inlined, but that would mean code duplication.
For the rest, in case you need some existing SpanQuery private methods you could change them to package private, and move your classes to the search.spans package for that reason.
Paul,
I think I have this implemented for the most part, but am having trouble with the NearSpansUnordered. Can you enlighten me to the use of the PriorityQueue in the file? Not saying its wrong, just saying I don't understand what's going on. Also wondering about how it relates to the ordered member and the first and last SpansCell.
Thanks,
Grant
I only wrote NearSpansOrdered. NearSpansOrdered is what is left of the original NearSpans after the ordered case was taken out, and after I specialized NearSpans the unordered case. That means I only simplified the original NearSpans.
Off the top of my head: the priority queue is used to make sure that the Spans are processed by increasing doc numbers and increasing token positions; the first and the last Spans determine whether there is a match, and all other Spans (in the queue) are "in between".
I think you'll only need to implement the Spans interface to use the same priority queue,
and you'll have to come up with a way to collect all the payloads from your payload spans on a match.
Probably fairly straightforward, but with Spans there is always unexpected fun waiting around the next corner.
So far, it's easier than that: when they match, they all match, so you only need to keep the input Spans around in List or whatever. Then use them all as a source for your payloads.
Off the top of my head: the priority queue is used to make sure that the Spans are processed by increasing doc numbers and increasing token positions; the first and the last Spans determine whether there is a match, and all other Spans (in the queue) are "in between".
Would it be simpler to just use a SortedSet? Then we could iterate w/o losing the sort, right? Would this be faster since we wouldn't have to do the heap operations?
> Would it be simpler to just use a SortedSet?
TreeMap is slower than a PriorityQueue for this. With PriorityQueue, insertions and deletions do not allocate new objects. And, if some items are much more frequent than others, using adjustTop() instead of inserting and deleting makes merges run much faster, since most updates are then considerably faster than log
....
> how do I get access to the position payloads in the order that they occur in the PQ?
Why do you need them in that order? In the API you propose in the description of this issue, there's no clear association between the payloads returned and the query terms. So I don't yet see how the order of the payloads is useful.
You could pretty easily return the list of payloads along with their positions by iterating through the list of sub-queries. The problem is that providing that sorted by position is expensive. Perhaps you could leave any such sorting, if required, to the application?
Yeah, I was thinking this as a possibility, but thought people may want to rely on the ordering, even if they mark it as unordered. I guess I will just have to properly document it, b/c I agree it is expensive to sort.
I will submit a patch shortly.
First draft of a patch for this issue. Need to expand/double check the tests and cleanup a few things before committing, but wanted to get opinion on the API.
Also, would like to see if NearSpansOrdered can be optimized a bit to not load the payloads in the case where the user doesn't ask for PayloadSpans. The other implementations shouldn't have this issue.
There is an issue w/ this patch related to unordered, overlapping spans that still needs to be fixed. Will try to get an updated patch out soon.
Fixes the unordered problem. Still needs more testing, but I believe it is working
I don't think that patch is compatible w/ anything
It was a
rough sketch that never properly worked. I put it up there in the
hopes that maybe someone would have some more insight to offer.
--------------------------
Grant Ingersoll
Lucene Helpful Hints:.
Without the absolute paths in the patch this time (get it together eclipse)
Fixes the unorderedspan ispostionavailable issue for good measure.
I think we have to give the payloads back unsorted - there are probably cases where you could just use all the payloads for a span rather than per term, so we might as well not incur a penalty there. If you need per term, you can put the position into the payload (pretty simple) and then just sort yourself.
I'll correct it if I have anything to add later, but the new isPayloadAvailable on the unordered spans should start at min(), not first.
Might as well keep striking while the iron's hot. This fixes the first to min() issue, I think it adds an isSpansAvailable call that had been commented out, adds a couple tests, tightens a test, and adds a new class that takes a single document and returns all of payloads from the terms that match a given Query object (so you could do a mix of span/query) - may or may not be useful someday.
TestBoostingTermQuery.testNoPayload now fails for me.
Also noticed some extraneous System.out.println.
I see what happened with the boosting test - the old patch didn't apply cleanly for me to the trunk for that test class - I looked for the issue but it looked clean so I left it to deal with later - turns out one or two lines were mangled. New patch that fixes that.
Also turned off DEBUG for the payloads test class so that will drop the System.outs.
Pretty clean now.
Added to CHANGES.txt
Made the SpanQuery.getPayloadSpans() method an empty implementation that returns null instead of being abstract, so as not to break anyone that extends SpanQuery. All Lucene span implementations override it.
Also added in license headers.
Plan to commit in a day or two
Took one last look through for final cleanup - removed an unused import and some unneeded commented code.
Committed revision 687379.
Hi,
I use getPayloadSpans to get the spans (PayloadSpans spans = sq.getPayloadSpans(this.getIndexReader())
and for each span I extract the relevant payload using spans.getPayload() (after calling spans.next()).
I have tested it for a SpanNearQuery, I have stored the offset in the payload (for testing).
It seems to me that the payloads returned for the span (spans.getPayload()) does not match the current span (given by span.next()). In fact, the offset returned by the payload are different from the offset returned by span.start().
It occurs when they are multiple occurrences of the terms.
Are you aware of this bug?
Thanks,
Jonathan
So are you finding the payloads not at the right term if the terms match ie
term1 term2 term1
You might get the second term1's offsets for the first term1 and vice versa?
In my document, I have ".... term1 ... term1 term2 ..."
offset of term1: 10, 20
offset of term2: 21
When running the query SpanNearQuery(term1 term2),
according to span.start, I get 20
while I get 10 and 21 when reading the payloads of the span.
I would expect to get 20 and 21when reading the payloads of the span.
Hi,
Here is the relevant code.
I would expect to obtain
10
pos: 10
pos: 11
while I obtain
10
pos: 0
pos: 11
import java.io.StringReader;
import java.util.Collection;
import java.util.Iterator;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spans.PayloadSpans;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
public class Test {
public static void main (String args[]) throws Exception{
IndexWriter writer = new IndexWriter(args[0], new
TestPayloadAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.add();new Field("content", new StringReader("a b c d e f g
h i j a k")));
writer.addDocument(doc);
writer.close();
IndexSearcher is = new IndexSearcher(args[0])
;
SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a"
));
SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k"
));
SpanQuery[] sqs =
;
SpanNearQuery snq = new SpanNearQuery(sqs,1,true);
PayloadSpans spans = snq.getPayloadSpans(is.getIndexReader());
TopDocs topDocs = is.search(snq,1);
for (int i = 0; i < topDocs.scoreDocs.length; i++) {
while) (spans.next()) {
System.out.println(spans.start());
Collection<byte[]> payloads = spans.getPayload();
for (Iterator<byte[]> it = payloads.iterator();
it.hasNext()
}}
}
}
}}
-------------------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.LowerCaseTokenizer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.Payload;
public class TestPayloadAnalyzer extends Analyzer {
public TokenStream tokenStream(String fieldName, Reader reader){ TokenStream result = new LowerCaseTokenizer(reader); result = new PayloadFilter(result, fieldName); return result; }
}
class PayloadFilter extends TokenFilter {
String fieldName;
int pos;
public PayloadFilter(TokenStream input, String fieldName){ super(input); this.fieldName = fieldName; pos = 0; }
public Token next() throws IOException {
Token result = input.next();
if (result != null)
return} result;
}
}
Jonathan
Okay, I still understand like 2% of spans, but I think I have fixed the bug.
After finding a match, but before finding a min match, we were pulling the payload - works fine when the match is the min match, but otherwise we actually have to wait to get the payload until we have crunched in on the min match. I had an idea of this before, and the code before I touched it tried to grab the payloads at this point - the problem is, in finding the min match, you've often advanced passed the term position of interest to find out there was no such min match. So you have to save the possible payload ahead of time, and either find a new one or use the possible saved one. Sucks to have to add extra loading, but at the moment I don't see how to do it differently (I admittedly can't see much in spans). Thats all partly a guess, partly probably true.
Non the less, this patch handles the previous test cases, plus the bug case reported above. I have also added a modified version of the given test for the bug to the span battery of tests.
Thanks Jonathan!
Whats the best procedure JIRA wise on this? Reopen this issue or start a new issue? If we reopen this issue, how is the bug fix tracked in changes?
Open a new one.
Could you put this in a subclass of Spans?
A little while ago I suggested to add a score() method to Spans to summarize the influence of subspans on the span score, and that would be another direction for a subclass. | https://issues.apache.org/jira/browse/LUCENE-1001 | CC-MAIN-2016-36 | refinedweb | 2,298 | 65.01 |
pbs_deljob man page
pbs_deljob — delete a pbs batch job
Synopsis
#include <pbs_error.h>
#include <pbs_ifl.h>
int pbs_deljob(int connect, char *job_id, char *extend)
Description
Issue a batch request to delete a batch job. If the batch job is running, the execution server will send the SIGTERM signal followed by SIGKILL .
A Delete Job batch request is generated and sent to the server over the connection specified byconnect which is the return value of pbs_connect().
The argument,job_id, identifies which job is to be deleted, it is specified in the form:sequence_number.server
The argument, extend, is overloaded to serve two purposes. If the pointer extend extend is the null pointer or points to a null string, the administrator established default time delay is used.
If extend points to a string other than the above, it is taken as text to be appended to the message mailed to to the job owner. This mailing occurs if the job is deleted by a user other than the job owner.
See Also
qdel(1B) and pbs_connect(3B)
Diagnostics
When the batch request generated by the pbs_deljob() function has been completed successfully by a batch server, the routine will return 0 (zero). Otherwise, a non zero error is returned. The error number is also set in pbs_errno. | https://www.mankier.com/3/pbs_deljob | CC-MAIN-2017-26 | refinedweb | 214 | 55.44 |
A mainstay of academic research into the market is the Random Walk Hypothesis (RWH). This is the idea that market moves are random and follow a normal distribution that can be easily described using a concept borrowed from physics called Brownian Motion.
This makes the market mathematics manageable, but is it true? Is the market really random?
If it is, then there’s little point to trying to beat it. But if it isn’t, then there are repeatable patterns that can be algorithmically exploited.
Thankfully, the issue of randomness is very important for fields like cryptography, so it is well studied and there are statistical tests that we can apply to market data to investigate this.
We’re going to borrow a few standard tests for randomness and apply it to historical data to see just how randome the markets really are.
Measuring Market Randomness
There are a host of randomness tests that have been developed over the years which look at binary sequences to determine whether or not a random process was used to generate these values. Notably, we have test suites such as the Diehard Tests, TestU01, NIST tests and others that have been published over the years.
We could run a large battery of tests (maybe we’ll get to that in a future post)to test our market data, but for now, we’ll just select three tests to see how the RWH holds up: runs test, discrete Fourier Transform test, and the Binary Matrix Rank test from the NIST suite.
Runs Test
If the market truly is random, then we shouldn’t see any dependence on previous prices; the market being up today should have no impact on what it will do tomorrow (and vice versa).
The runs test can help us look this aspect of randomness. It works by looking at the total number of positive and negative streaks in a sequence and checking the lengths.
We’ll take our prices and make all positive price changes into 1s and negative changes into 0s, and keep this binary vector as X. We’ll set n as the number of observations we have (e.g.
n = len(X)). Then, to implement the runs test, we take the following steps (adapted from section 2.3 of the NIST Statistical Test Suite):
1. Compute the proportion of 1s in the binary sequence:
\pi = \frac{\sum_j X_j}{n}
2. Check the value \pi against the frequency test. It passes if: \mid \pi - 1/2 \mid < \tau, where \tau = \frac{2}{\sqrt{n}}. If the frequency test is failed, then we can stop and we don’t have a random sequence and we’ll set our P-value to 0. If we pass, then we can continue to step 3.
3. Compute our test statistic V_n where:
V_n = \sum_{k=1}^{n-1} r(k) + 1
where r(k) = 0 if X_k = X_{k+1}, otherwise r(k) = 1. So if we have the sequence [0, 1, 0, 0, 0, 1, 1], then this becomes: V_n = (1 + 1 + 0 + 0 + 1 + 0) + 1 = 4
4. Compute our P-value where:
p = erfc\bigg( \frac{ \mid V_n - 2n \pi (1 - \pi) \mid}{2 \pi (1-\pi) \sqrt{2n}} \bigg)
Note that erfc is the complementary error function (given below). Thankfully, this is available in Python with
scipy.special.erfc(z):
With all of that, we can now use our P-value to determine whether or not our sequence is random. If our P-value is below our threshold (e.g. 5%), then we reject the null hypothesis, which means we have a non-random sequence on our hands.
import numpy as np from scipy.special import erfc def RunsTest(x): # Convert input to binary values X = np.where(x > 0, 1, 0) n = len(X) pi = X.sum() / n # Check frequency test tau = 2 / np.sqrt(n) if np.abs(pi - 0.5) >= tau: # Failed frequency test return 0 r_k = X[1:] != X[:-1] V_n = r_k.sum() + 1 num = np.abs(V_n - 2 * n * pi * (1 - pi)) den = 2 * pi * (1 - pi) * np.sqrt(2 * n) return erfc(num / den)
The NIST documentation gives us some test data to check that our function is working properly, so let’s drop that into our function and see what happens.
# eps from NIST doc eps = '110010010000111111011010101000100010000101101' + \ '0001100001000110100110001001100011001100010100010111000' x = np.array([int(i) for i in eps]) p = RunsTest(x) H0 = p > 0.01 # NIST P-value = 0.500798 print("Runs Test\n"+"-"*78) if H0: print(f"Fail to reject the Null Hypothesis (p={p:.3f}) -> random sequence") else: print(f"Reject the Null Hypothesis (p={p:.3f}) -> non-random sequence.")
Runs Test ------------------------------------------------------------------------------ Fail to reject the Null Hypothesis (p=0.501) -> random sequence
We get the same P-value, so we can be confident that our implementation is correct. Note also that NIST recommends we have at least 100 samples in our data for this test to be valid (i.e. $n \geq 100$).
Discrete Fourier Transformation Test
Our next test is the Discrete Fourier Transformation (DFT) test.
This test computes a Fourier Transform on the data and looks at the peak heights. If their are too many high peaks, then it indicates we aren’t dealing with a random process. It would take us too far afield to dive into the specifics of Fourier Transforms, but check out this post if you’re interested to go deeper.
Let’s get to the NIST steps. We have data (x) and we need to set a threshold, which is usually 95% as inputs.
1. We need to convert our time-series x into a sequence of 1s and -1s for positive and negative deviations. This new sequence is called \hat{x}.
2. Apply discrete Fourier Transform (DFT) to \hat{x}:
\Rightarrow S = DFT(\hat{x})
3. Calculate M = modulus(S') = \left| S \right|, where S' is the first n/2 elements in S and the modulus yields the height of the peaks.
4. Compute the 95% peak height threshold value. If we are assuming randomness, then 95% of the values obtained from the test should not exceed T.
T = \sqrt{n\textrm{log}\frac{1}{0.05}}
5. Compute N_0 = \frac{0.95n}{2}, where N_0 is the theoretical number of peaks (95%) that are less than T (e.g. if n=10, then N_0 = \frac{10 \times 0.95}{2} = 4.75).
6. Compute the P-value using the erfc function:P = erfc \bigg( \frac{\left| d \right|}{\sqrt{2}} \bigg)
Just like we did above, we’re going to compare our P-value to our reference level and see if we can reject the null hypothesis – that we have a random sequence – or not. Note too that it is recommended that we use at least 1,000 inputs (n \geq 1000) for this test.
def DFTTest(x, threshold=0.95): n = len(x) # Convert to binary values X = np.where(x > 0, 1, -1) # Apply DFT S = np.fft.fft(X) # Calculate Modulus M = np.abs(S[:int(n/2)]) T = np.sqrt(n * np.log(1 / (1 - threshold))) N0 = threshold * n / 2 N1 = len(np.where(M < T)[0]) d = (N1 - N0) / np.sqrt(n * (1-threshold) * threshold / 4) # Compute P-value return erfc(np.abs(d) / np.sqrt(2))
NIST gives us some sample data to test our implementation here too.
# Test sequence from NIST eps = '110010010000111111011010101000100010000101101000110000' + \ '1000110100110001001100011001100010100010111000' x = np.array([int(i) for i in eps]) p = DFTTest(x) H0 = p > 0.01 print("DFT Test\n"+"-"*78) if H0: print(f"Fail to reject the Null Hypothesis (p={p:.3f}) -> random sequence") else: print(f"Reject the Null Hypothesis (p={p:.3f}) -> non-random sequence.")
DFT Test ------------------------------------------------------------------------------ Fail to reject the Null Hypothesis (p=0.646) -> random sequence
Same as the NIST documentation, we reject the null hypothesis.
Binary Matrix Rank Test
We’ll choose one last test out of the test suite – the Binary Matrix Rank Test.
Steps:
1. Divide the sequence into 32 by 32 blocks. We’ll have N total blocks to work with and discard any data that doesn’t fit nicely into our 32×32 blocks. Each block will be a matrix consisting of our ordered data. A quick example will help illustrate, say we have a set of 10, binary data points:
X = [0, 0, 0, 1, 1, 0, 1, 0, 1, 0] and we have 2×2 matrices (to make it easy) instead of 32×32. We’ll divide this data into two blocks and discard two data points. So we have two blocks (B_1 and B_2) that now look like:
2. We determine the rank of each binary matrix. If you’re not familiar with the procedure, check out this notebook here for a great explanation. In Python, we can simply use the
np.linalg.matrix_rank() function to compute it quickly.
3. Now that we have the ranks, we’re going to count the number of full rank matrices (if we have 32×32 matrices, then a full rank matrix has a rank of 32) and call this number F_m. Then we’ll get the number of matrices with rank one less than full rank which will be F_{m-1}. We’ll use N to denote the total number of matrices we have.
4. Now, we compute the Chi-squared value for our data with the following equation:\chi^2 = \frac{(F_m-0.2888N)^2}{0.2888N} + \frac{(F_{m-1} - 0.5776N)^2}{0.5776N} + \frac{(N - F_m - F_{m-1} - 0.1336N)^2}{0.1336N}
- Calculate the P-value using the Incomplete Gamma Function, Q\big(1, \frac{\chi^2}{2} \big):
Scipy makes this last bit easy with a simple function call to
scipy.special.gammaincc().
Don’t be intimidated by this! It’s actually straightforward to implement.
from scipy.special import gammaincc def binMatrixRankTest(x, M=32): X = np.where(x > 0, 1, 0) n = len(X) N = np.floor(n / M**2).astype(int) # Create blocks B = X[:N * M**2].reshape(N, M, M) ranks = np.array([np.linalg.matrix_rank(b) for b in B]) F_m = len(np.where(ranks==M)[0]) F_m1 = len(np.where(ranks==M - 1)[0]) chi_sq = (F_m - 0.2888 * N) ** 2 / (0.2888 * N) \ + (F_m1 - 0.5776 * N) ** 2 / (0.5776 * N) \ + (N - F_m - F_m1 - 0.1336 * N) ** 2 / (0.1336 * N) return gammaincc(1, chi_sq / 2)
If our P-value is less than our threshold, then we have a non-random sequence. Let’s test it with the simple example given in the NIST documentation to ensure we implemented things correctly:
eps = '01011001001010101101' X = np.array([int(i) for i in eps]) p = binMatrixRankTest(X, M=3) H0 = p > 0.01 print("Binary Matrix Rank Test\n"+"-"*78) if H0: print(f"Fail to reject the Null Hypothesis (p={p:.3f}) -> random sequence") else: print(f"Reject the Null Hypothesis (p={p:.3f}) -> non-random sequence.")
Binary Matrix Rank Test ------------------------------------------------------------------------------ Fail to reject the Null Hypothesis (p=0.742) -> random sequence
And it works! Note that in this example, we have a much smaller data set, so we set M=3 for 9-element matrices. This test is also very data hungry. They recommend at least 38 matrices to test. If we’re using 32×32 matrices, then that means we’ll need 38x32x32 = 38,912 data points. That’s roughly 156 years of daily price data!
Only the oldest companies and commodities are going to have that kind of data available (and not likely for free). We’ll press on with this test anyway, but take the results with a grain of salt because we’re violating the data recommendations.
Testing the RWH
With our tests in place, we can get some actual market data and see how well the RWH holds up. To do this properly, we’re going to need a lot of data, so I picked out some indices with a long history, a few old and important commodities, some of the oldest stocks out there, a few currency pairs, and Bitcoin just because.
Data from:
- Dow Jones
- S&P 500
- Gold
- Oil
- USD/GBP
- BTC/USD
One thing to note as well, we want to also run this against a baseline. For each of these I’ll be benchmarking the results against NumPy’s binomial sampling algorithm, which should have a high-degree of randomness.
I relied only on free sources so you can replicate this too, but more and better data is going to be found in paid subscriptions. I have defined a
data_catalogue as a dictionary below which will contain symbols, data sources, and the like so our code knows where to go to get the data.
data_catalogue = {'DJIA':{ 'source': 'csv', 'symbol': 'DJIA', 'url': '^dji&i=d' }, 'S&P500': { 'source': 'csv', 'symbol': 'SPX', 'url': '^spx&i=d' }, 'WTI': { 'source': 'yahoo', 'symbol': 'CL=F', }, 'Gold': { 'source': 'yahoo', 'symbol': 'GC=F', }, 'GBP': { 'source': 'yahoo', 'symbol': 'GBPUSD=X' }, 'BTC': { 'source': 'yahoo', 'symbol': 'BTC-USD' } }
Now we’ll tie all of this together into a
TestBench class. This will take our data catalogue, reshape it, and run our tests. The results are going to be collected for analysis, and I wrote a helper function to organize it into a large, Pandas dataframe for easy viewing.
import pandas as pd import pandas_datareader as pdr import yfinance as yf from datetime import datetime class TestBench: data_catalogue = data_catalogue test_names = ['runs-test', 'dft-test', 'bmr-test'] def __init__(self, p_threshold=0.05, seed=101, dftThreshold=0.95, bmrRows=32): np.random.seed(seed) self.seed = seed self.p_threshold = p_threshold self.dftThreshold = dftThreshold self.bmrRows = bmrRows self.years = [1, 4, 7, 10] self.trading_days = 250 self.instruments = list(self.data_catalogue.keys()) def getData(self): self.data_dict = {} for instr in self.instruments: try: data = self._getData(instr) except Exception as e: print(f'Unable to load data for {instr}') continue self.data_dict[instr] = data.copy() self.data_dict['baseline'] = np.random.binomial(1, 0.5, size=self.trading_days * max(self.years) * 10) def _getData(self, instr): source = self.data_catalogue[instr]['source'] sym = self.data_catalogue[instr]['symbol'] if source == 'yahoo': return self._getYFData(sym) elif source == 'csv': return self._getCSVData(self.data_catalogue[instr]['url']) elif source == 'fred': return self._getFREDData(sym) def _getCSVData(self, url): data = pd.read_csv(url) close_idx = [i for i, j in enumerate(data.columns) if j.lower() == 'close'] assert len(close_idx) == 1, f"Can't match column names.\n{data.columns}" try: std_data = self._standardizeData(data.iloc[:, close_idx[0]]) except Exception as e: raise ValueError(f"{url}") return std_data def _getYFData(self, sym): yfObj = yf.Ticker(sym) data = yfObj.history(period='max') std_data = self._standardizeData(data) return std_data def _getFREDData(self, sym): data = pdr.DataReader(sym, 'fred') data.columns = ['Close'] std_data = self._standardizeData(data) return std_data def _standardizeData(self, df): # Converts data from different sources into np.array of price changes try: return df['Close'].diff().dropna().values except KeyError: return df.diff().dropna().values def runTests(self): self.test_results = {} for k, v in self.data_dict.items(): print(f"{k}") self.test_results[k] = {} for t in self.years: self.test_results[k][t] = {} data = self._reshapeData(v, t) if data is None: # Insufficient data continue self.test_results[k][t]['runs-test'] = np.array( [self._runsTest(x) for x in data]) self.test_results[k][t]['dft-test'] = np.array( [self._dftTest(x) for x in data]) self.test_results[k][t]['bmr-test'] = np.array( [self._bmrTest(x) for x in data]) print(f"Years = {t}\tSamples = {data.shape[0]}") def _reshapeData(self, X, years): d = int(self.trading_days * years) # Days per sample N = int(np.floor(X.shape[0] / d)) # Number of samples if N == 0: return None return X[-N*d:].reshape(N, -1) def _dftTest(self, data): return DFTTest(data, self.dftThreshold) def _runsTest(self, data): return RunsTest(data) def _bmrTest(self, data): return binMatrixRankTest(data, self.bmrRows) def tabulateResults(self): # Tabulate results table = pd.DataFrame() row = {} for k, v in self.test_results.items(): row['Instrument'] = k for k1, v1 in v.items(): row['Years'] = k1 for k2, v2 in v1.items(): pass_rate = sum(v2>self.p_threshold) / len(v2) * 100 row['Test'] = k2 row['Number of Samples'] = len(v2) row['Pass Rate'] = pass_rate row['Mean P-Value'] = v2.mean() row['Median P-Value'] = np.median(v2) table = pd.concat([table, pd.DataFrame(row, index=[0])]) return table
We can initialize our test bench and call the
getData() and
runTests() method to put it all together. The
tabulateResults() method will give us a nice table for viewing.
When we run our tests, we have a print out for the number of years and full samples of data we have. You’ll notice that for some of these (e.g. Bitcoin) we just don’t have a great amount of data to go off of, but we’ll do our best with what we do have.
tests = TestBench() tests.getData() tests.runTests()
DJIA Years = 1 Samples = 129 Years = 4 Samples = 32 Years = 7 Samples = 18 Years = 10 Samples = 12 S&P500 Years = 1 Samples = 154 Years = 4 Samples = 38 Years = 7 Samples = 22 Years = 10 Samples = 15 WTI Years = 1 Samples = 21 Years = 4 Samples = 5 Years = 7 Samples = 3 Years = 10 Samples = 2 Gold Years = 1 Samples = 20 Years = 4 Samples = 5 Years = 7 Samples = 2 Years = 10 Samples = 2 GBP Years = 1 Samples = 18 Years = 4 Samples = 4 Years = 7 Samples = 2 Years = 10 Samples = 1 BTC Years = 1 Samples = 10 Years = 4 Samples = 2 Years = 7 Samples = 1 Years = 10 Samples = 1 baseline Years = 1 Samples = 100 Years = 4 Samples = 25 Years = 7 Samples = 14 Years = 10 Samples = 10
We have 129 years of Dow Jones data, which gives us 12, 10-year samples and 154 years for the S&P 500 (the index doesn’t go back that far, but our data source provides monthly data going back to 1789). This is in contrast to most of our other values which have two decades or less.
To take a look at the results, we can run the
tabulateResults() method, and do some pivoting to reshape the data frame for easier viewing.
table = tests.tabulateResults() pivot = table.pivot_table(index=['Instrument', 'Years'], columns='Test') samps = pivot['Number of Samples'].drop(['bmr-test', 'dft-test'], axis=1) pivot.drop(['Number of Samples'], axis=1, inplace=True) pivot['Number of Samples'] = samps pivot
Let’s start with the baseline.
As expected, NumPy’s random number generator is pretty good, and it passes most of the tests without issue. The median P-values for the runs and DFT tests remain fairly high as well, although they are lower for the BMR test. Another thing to note, the 1 and 4 year BMR tests didn’t return any values because we were unable to complete a single 32×32 matrix with such small sample sizes. Overall, the lack of data for the BMR test makes the results here dubious (we could recalculate it with a smaller matrix size, but we’d need to recalibrate all of the probabilities for these different matrices).
The DFT test showed randomness for most cases in our test set. For what it’s worth, the P-values for our DFT tests of all sizes remained fairly high regardless of the sample size.
The runs test provides the most varied and interesting results.
import matplotlib.pyplot as plt plt.figure(figsize=(12, 8)) for i, instr in enumerate(tests.instruments): sub = table.loc[(table['Instrument']==instr) & (table['Test']=='runs-test')] plt.plot(tests.years, sub['Pass Rate'], label=instr, c=colors[i], marker='o') plt.legend() plt.xlabel('Years') plt.ylabel('Pass Rate (%)') plt.title('Runs Test Pass Rate for all Instruments') plt.show()
The runs test tends to produce less random results as time goes on. The notable exception being our WTI data, which passes more tests for randomness over time. However, if we look at our P-values, we do see them falling towards 0 (recall, our null hypothesis is that these are random processes).
plt.figure(figsize=(12, 8)) for i, instr in enumerate(table['Instrument'].unique()): sub = table.loc[(table['Instrument']==instr) & (table['Test']=='runs-test')] plt.plot(tests.years, sub['Median P-Value'], label=instr, c=colors[i], marker='o') plt.legend() plt.xlabel('Years') plt.ylabel('P-Value') plt.title('Median P-Values for Runs Test for all Instruments') plt.show()
We added the baseline to this plot to show that it remains high even as the time frame increases, whereas all other values become less random over time. We’re showing P-values here, which are the probabilities that the results are due to noise if the process we’re testing is random. In other words, the lower our values become, the less likely it is that we have a random process on our hands.
This downward sloping trend may provide evidence that supports the value of longer-term trading.
Jerry Parker, for example, has moved toward longer-term trend signals (e.g. >200 day breakouts) because the short term signals are no longer profitable in his system. Data is going to be limited, but it could be interesting to run this over multiple, overlapping samples as in a walk forward analysis to see if randomness in the past was lower during shorter time frames. Additionally, there are more statistical tests we could look at to try to tease this out.
Death of the Random Walk Hypothesis?
The evidence from these few tests is mixed. Some tests show randomness, others provide an element of predictability. Unfortunately, we can’t definitively say the RWH is dead (although I think it, and the theories it is based on, are more articles of academic faith than anything).
To improve our experiment we need more data and more tests. We also used a series of binary tests, although technically the RWH asserts that the changes in price are normally distributed, so statistical tests that look for these patterns could strengthen our methodology and lead to more robust conclusions.
If you’d like to see more of this, drop us a note at hello@raposa.trade and let us know what you think! | https://raposa.trade/tag/data/ | CC-MAIN-2021-49 | refinedweb | 3,700 | 67.04 |
txshark 0.1.0
Python/Twisted wrapper for tshark
Asynchronous TShark wrapper for Twisted.
Introduction
txshark is based on pyshark.
As pyshark, it uses TShark (Wireshark command-line utility) to analyze network traffic by simply parsing the TShark pdml output (XML-based format).
Parsing TShark pdml output is not the most efficient way (in terms of performance) to analyze network traffic. It might not keep up with very heavy traffic. But it works very well to decode low/specific traffic (using a capture filter) and allows to take advantage of all the existing Wireshark dissectors.
This package provides a Twisted service to start and stop TShark. It allows a Twisted app to decode packets from a live network or a file.
Requirements
- Tool required:
- TShark! (should be in your PATH)
- Python packages required:
- Twisted
- lxml
Usage
TsharkService
Create a service that inherits from TsharkService and override the packetReceived method to handle incoming packets:
from twisted.python import log from txshark import TsharkService class SnifferService(TsharkService): def packetReceived(self, packet): """Override the TsharkService method""" log.msg("Packet received: {}".format(packet)
The interfaces to listen to should be given as a list of {"name": <name>, "filter": <filter>}. This allows to give a specific filter to each interface:
service = SnifferService( [{"name": "eth0", "filter": "tcp and port 8521"}, {"name": "eth1", "filter": "tcp and port 8522"}])
To read packets from a captured file, just give the name of the file instead of the interface. If a filter is used in this case, it should be a display filter (syntax different from a capture filter):
service = SnifferService( [{"name": "test.pcap", "filter": "tcp.port == 8501"}])
The filter is optional in both case.
The service can be started with the startService method:
service.startService()
But as a Twisted Service, it is designed to be started automatically by a Twisted Application. Refer to Twisted documentation for more information.
Accessing packet data
Data can be accessed in multiple ways. Packets are divided into layers, first you have to reach the appropriate layer and then you can select your field.
All of the following work:
packet['ip'].dst >>> 192.168.0.1 packet.ip.src >>> 192.168.0.100 packet[2].src >>> 192.168.0.100
- Author: Benjamin Bertrand
- Keywords: wireshark packet parsing twisted
- License: MIT
- Categories
- Package Index Owner: beenje
- DOAP record: txshark-0.1.0.xml | https://pypi.python.org/pypi/txshark/0.1.0 | CC-MAIN-2016-26 | refinedweb | 387 | 55.95 |
Okay, I have this code below just to illustrate what my problem is, I want to capture the title of the active window and display that in the output. And then it would not do anything unless the user switched to another window. For that it works fine, but I also want it to log all the titles in the active window, so for example if I open firefox( my homepage is google), it would log the google part but if I continue browsing it doesn't log all the other new websites. So I'm just looking for a code that will log all the new titles regardless if you switched between those windows. You can try the code below and have two windows open and switching between them will output the titles, but if you just have one window and you're just browsing that it doesn't log the new titles, just the first one. I hope I've made it clear what I'm trying to do, maybe this is the wrong function call so I hope someone can tell me that but if it's right I'd appreciate if someone could fix it for or give me a hint or two thanks.
Code:#include <iostream> #include <fstream> #include <windows.h> using namespace std; char name[MAX_PATH]; HWND currentWin = GetForegroundWindow(); HWND temporaryWin; int main(){ while(1){ temporaryWin = currentWin; currentWin = GetForegroundWindow(); if(temporaryWin != currentWin){ GetWindowText(currentWin, name, 256); cout << name << endl;}} return 0; } | https://cboard.cprogramming.com/cplusplus-programming/90619-problem-capturing-titles-one-window.html | CC-MAIN-2017-09 | refinedweb | 247 | 62.11 |
Running Selenium Tests With Chrome Headless
Running Selenium Tests With Chrome Headless
Learn how to use Java to execute tests in a headless Google Chrome browser and make testing your web applications a little easier.
Join the DZone community and get the full member experience.Join For Free
Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required
Introduction
Before Google Chrome 59, headless execution had to be done by third-party headless browsers like PhantomJS, SlimerJS, TrifleJS, Nightmare, and HTMLUnit.
The "problem" is that these headless browsers emulate some engines, but not V8 (the Chrome engine).
When we talk about testing, it's necessary to simulate Google's real engine, as both Internet users and web devs tend toward using Google Chrome.
How to Do it With Java
As Google Chrome ships with headless execution in version 59 (as you can see here) we can tell ChromeDriver the options before the execution.
In the code below I added two options through ChromeOptions: headless and the window-size.
// imports omitted public class ChromeHeadlessTest { @Test(""); // a guarantee that the test was really executed assertTrue(driver.findElement(By.id("q")).isDisplayed()); driver.quit(); } }
The headless option will tell to Google Chrome to execute in headless mode. The window-size is a way to control the responsiveness (and allows your site be displayed, like a mobile site, if you have not set a window size).
You can see some other ways to inform the ChromeOptions here.
#1 for location developers in quality, price and choice, switch to HERE.
Published at DZone with permission of Elias Nogueira . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/running-selenium-tests-with-chrome-headless?fromrel=true | CC-MAIN-2019-09 | refinedweb | 295 | 52.9 |
Introduction
The linked list is one of the most important data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.
Problem Statement
In this question, we are given a singly linked list. We have to search for a given element X in the list. If it is present, we have to return its index, otherwise -1.
Problem Statement Understanding
Let’s first understand the problem statement with the help of examples.
Suppose the given list is:
and the element to be searched is 15. As we can see, 15 is present in the list at the 2nd index.
So, our program will return the value 2 (considering 0 based indexing), which is the index of elements to be searched in the given linked list.
Input:
X = 15.
Output: 2
Explanation: As we can see, 15 is present at the 2nd index.
Now, I think it is clear from the above example what we have to do in the problem. So let’s move to approach.
Before jumping to approach, just try to think how you can approach this problem?
It's okay, if your solution is not the best optimized solution, we will try to optimize it together.
This question is not a very complex one. We have to make use of list traversal in the question. We can either use the in-built library to traverse through the linked list or the normal linked list traversal method.
Let us have a glance at the approaches.
Approach and Algorithm(In-built libraries)
The approach is going to be pretty simple.
- First, we will initialize the linked list.
- Now, as we are allowed to use in-built libraries, we can use a for loop with zero-based indexing to traverse through the list.
- To extract the ith element, we can simply use List.get(i).
- We will create an integer variable ans and initialize it with -1.
- Now, we will simply traverse through the loop and for every element, we will check if the data of that node is equal to the searched element. If the condition becomes true, we will store i in ans and break from the loop.
- In the end, if the value of ans remains -1, it means that the element is not present in the list. Else, we will print the ans.
Code Implementation
import java.util.LinkedList; public class SearchInALinkedList { public static void main(String[] args) { LinkedList
llist = new LinkedList<>(); llist.add(1); llist.add(7); llist.add(15); llist.add(27); int element = 15; int ans = -1; for (int i = 0; i < llist.size(); i++) { int llElement = llist.get(i); if (llElement == element) { ans = i; break; } } if (ans == -1) { System.out.println("Element not found"); } else { System.out.println( "Element found at index " + ans); } } }
Output
Element found at index 2
Time Complexity: O(n), as list traversal is needed.
Space Complexity: O(1), as only temporary variables are being created.
Approach (Generic node class)
In this approach, we will use the generic list traversal method.
- If the head of the list is null, we will return -1.
- Now, we will traverse through the list and check if the element is present in the list or not. We will also maintain an index variable which will initially be 0 and will be incremented by 1 in every iteration.
- If the element to be searched matches with the current node's data, we will return the index.
In the end, if element to be searched, not found in the list we will return -1, as the element is not present.
Algorithm
- Base case - If the head is null, return -1
- Create a variable index and initialize it with 0, and a node curr which will have the value of head.
- Traverse through the list using curr.
- In every iteration, check if the data of curr is equal to the search element or not. If it is equal, we will return the index variable. Also increment the index variable by 1 in every iteration.
- In the end, return -1, as the search element is not present in the list.
Dry Run
Code Implementation
class Node
{ E data; Node next; Node(E data) { this.data = data; } } class LinkedList { Node head = null; int size = 0; public void add(E element) { if (head == null) { head = new Node<>(element); size++; return; } Node add = new Node<>(element); Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = add; size++; } public int search(E element) { if (head == null) { return -1; } int index = 0; Node temp = head; while (temp != null) { if (temp.data == element) { return index; } index++; temp = temp.next; } return -1; } } public class PrepBytes { public static void main(String[] args) throws Exception { LinkedList ll = new LinkedList<>(); ll.add(1); ll.add(7); ll.add(15); ll.add(27); int element = 15; int ans = ll.search(element); if (ans == -1) { System.out.println( "Element not found in the Linked List"); } else System.out.println( "Element found at index " + ans); } }
Output:
Element found at index 2
Time Complexity: O(n), as list traversal is needed.
[forminator_quiz id="3906"]
So, in this article, we have tried to explain the most efficient approach to search an element in a Linked List in Java. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List. | https://www.prepbytes.com/blog/java/java-program-to-search-an-element-in-a-linked-list/ | CC-MAIN-2022-21 | refinedweb | 909 | 74.29 |
I am trying to access a C++ enumeration within an OOT module from a python instance of my OOT. When I try to run my python code it cannot find the enumeration. My OOT module is called pll_freq_phase_det_cf and is included in python as: from pll_freq_phase_det_cf import pll_freq_phase_det_cf The C++ enum is defined in the public section of the object class definition in the include header and looks like: enum ld_determination { USE_NONE = 0, USE_PHASE_THRESHOLD = 1, USE_SIG_THRESHOLD = 2, USE_ALL = 3, USE_FULL = USE_ALL }; I would expect to be able to reference this from my python code like "pll_freq_phase_det_cf.USE_ALL", but the python interpreter cannot find a reference to this. I have looked at gr-filter firdes windowing enum and I do not see anything special about how this was declared, or within any CMake or swig files for this, so I do not know where to go from here. I have also looked at the python files in /usr/local/lib/python2.7/site-packages for my OOT and firdes and see no differences between how the enum values look (besides the names obviously being different...). Any help on this would be greatly appreciated. Thank you very much, Michael Berman
on 2013-12-19 20:09
on 2013-12-19 21:38
On Thu, Dec 19, 2013 at 2:07 PM, Michael Berman <mrberman87@gmail.com> wrote: > USE_NONE = 0, USE_PHASE_THRESHOLD = 1, USE_SIG_THRESHOLD = 2, > > Michael Berman It sounds like you're definitely on the right track. My only suggestion is to double-check your swig file that the header is being included properly. But you're right; it's nothing special exporting those enums through swig. Another place to look is sig_source_waveform.h in gr-analog. Tom
on 2013-12-19 21:50
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I had a hard time adding the tag_propagation_policy_t enum to the swig gateway; maybe my pull request from back then might help you: The point is that I haven't been able to have an enum definition as class member; only directly in the namespace. Happy hacking, Marcus On 19.12.2013 21:36, Tom Rondeau wrote: >> The C++ enum is defined in the public section of the object class >> or swig files for this, so I do not know where to go from here. >> > > _______________________________________________ Discuss-gnuradio > mailing list Discuss-gnuradio@gnu.org > > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.15 (GNU/Linux) Comment: Using GnuPG with Thunderbird - iQEcBAEBAgAGBQJSs1vHAAoJEAFxB7BbsDrLi3cH/RVDAeTG8Ql4ctSd1LuSf/tF aiNQ+XX+wIB3CskMcwiFGLvUHfrg9/slOK8QehSG2/oZJWji1dGc9Tqko7DbYRhR GfZzHWpRjpUlzwiclm9IqKy4ZV1zkzH+DH5Im9FGwdbFBK+cDpupKB4lsKV9Cosm Q+JZXdMjGkqepraI58Aw9UsBML3akOrjSIYyE41BxCPEfLX9BXdM9aJxPnWl/gJY xKR38HAwZOTJh6/yojZZ9dOHrWbdJPxFaTF9XaaDrNjEf3SEsvUBV1XQgpUZj/12 jImHwCLBGhoaXbuNf5gw89NSbgSucZRPlus0eX78IK6LNAWInmr3W4BRxHGKIC8= =Eb1v -----END PGP SIGNATURE-----
on 2013-12-19 22:08
Hi, For what it's worth, I have enums in fosphor and the way I had to access them is : from gnuradio.fosphor.fosphor_swig import base_sink_c base_sink_c.REF_DOWN Because the base_sink_c from gnuradio.fosphor directly isn't really the SWIG object ... it's just the wrapper for the make() function that creates the sptr and you can't access any of the members. Cheers, Sylvain
on 2013-12-23 19:31
Thank you all for the ideas so far. I unfortunately will not be able to play around with this until the new year, but I will post back then if I get it working to help people down the road. Michael | https://www.ruby-forum.com/topic/4419436 | CC-MAIN-2018-13 | refinedweb | 545 | 61.16 |
insq - insert a message into a queue
#include <sys/stream.h> int insq(queue_t *q, mblk_t *emp, mblk_t *nmp);
Architecture independent level 1 (DDI/DKI).
Pointer to the queue containing message emp.
Enqueued message before which the new message is to be inserted. mblk_t is an instance of the msgb(9S) structure.
Message to be inserted.
The insq() function inserts a message into a queue. The message to be inserted, nmp, is placed in q immediately before the message emp. If emp is NULL, the new message is placed at the end of the queue. The queue class of the new message is ignored. All flow control parameters are updated. The service procedure is enabled unless QNOENB is set.
The insq() function returns 1 on success, and 0 on failure.
The insq() function can be called from user, interrupt, or kernel context.
This routine illustrates the steps a transport provider may take to place expedited data ahead of normal data on a queue (assume all M_DATA messages are converted into M_PROTO T_DATA_REQ messages). Normal T_DATA_REQ messages are just placed on the end of the queue (line 16). However, expedited T_EXDATA_REQ messages are inserted before any normal messages already on the queue (line 25). If there are no normal messages on the queue, bp will be NULL and we fall out of the for loop (line 21). insq acts like putq(9F) in this case.
1 #include <sys/stream.h> 2 #include <sys/tihdr.h> 3 4 static int 5 xxxwput(queue_t *q, mblk_t *mp) 6 { 7 union T_primitives *tp; 8 mblk_t *bp; 9 union T_primitives *ntp; 10 11 switch (mp->b_datap->db_type) { 12 case M_PROTO: 13 tp = (union T_primitives *)mp->b_rptr; 14 switch (tp->type) { 15 case T_DATA_REQ: 16 putq(q, mp); 17 break; 18 19 case T_EXDATA_REQ: 20 /* Insert code here to protect queue and message block */ 21 for (bp = q->q_first; bp; bp = bp->b_next) { 22 if (bp->b_datap->db_type == M_PROTO) { 23 ntp = (union T_primitives *)bp->b_rptr; 24 if (ntp->type != T_EXDATA_REQ) 25 break; 26 } 27 } 28 (void)insq(q, bp, mp); 29 /* End of region that must be protected */ 30 break; . . . 31 } 32 } 33 }
When using insq(), you must ensure that the queue and the message block is not modified by another thread at the same time. You can achieve this either by using STREAMS functions or by implementing your own locking.
putq(9F), rmvq(9F), msgb(9S)
Writing Device Drivers in Oracle Solaris 11.4
STREAMS Programming Guide
If emp is non-NULL, it must point to a message on q or a system panic could result. | https://docs.oracle.com/cd/E88353_01/html/E37855/insq-9f.html | CC-MAIN-2022-05 | refinedweb | 431 | 64.81 |
Dependency Injection in ASP.NET MVC: Final Look
Other posts in this series:
In this series, we’ve looked on how we can go beyond the normal entry point for dependency injection in ASP.NET MVC (controllers), to achieve some very powerful results by extending DI to filters, action results and views. We also looked at using the modern IoC container feature of nested containers to provide injection of contextual items related to both the controller and the view.
In my experience, these types of techniques prove to be invaluable over and over again. However, not every framework I use is built for dependency injection through and through. That doesn’t stop me from getting it to work, in as many places as possible.
Why?
It’s really amazing how much your design changes once you remove the responsibility of locating dependencies from components. But instead of just talking about it, let’s take a closer look at the alternatives, from the ASP.NET MVC 2 source code itself.
ViewResult: Static Gateways
One of my big beefs with the design of the ActionResult concept is that there are two very distinct responsibilities going on here:
- Allow an action method to describe WHAT to do
- The behavior of HOW to do it
Controller actions are testable because of the ActionResult concept. I can return a ViewResult from a controller action method, and simply test its property values. Is the right view name chosen, etc.
The difficulty comes in to play when it becomes harder to understand what is needed for the HOW versus the pieces describing the WHAT. From looking at this picture, can you tell me which is which?
Offhand, I have no idea. The ViewName member I’m familiar with, but what about MasterName in the ViewResult class? Then you have a “FindView” method, which seems like a rather important method. The other pieces are all mutable, that is, read and write. Poring over the source code, none of these describe the WHAT, that’s just the ViewName and MasterName. Those are the pieces the ViewEngineCollection uses to find a view.
Then you have the View property which can EITHER be set in a controller action, or is dynamically found by looking at the ViewEngineCollection. So let’s look at that property on the ViewResultBase class:
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This entire type is meant to be mutable.")] public ViewEngineCollection ViewEngineCollection { get { return _viewEngineCollection ?? ViewEngines.Engines; } set { _viewEngineCollection = value; } }
Notice the static gateway piece. I’m either returning the internal field, OR, if that’s null, a static gateway to a “well-known” location. Well-known, that is, if you look at the source code of MVC, because otherwise, you won’t really know where this value can come from.
So why this dual behavior?
Let’s see where the setter is used:
The setter is used only in tests. All this extra code to expose a property, this null coalescing behavior for the static gateway (referenced in 7 other places), all just for testability. Testing is supposed to IMPROVE design, not make it more complicated and confusing!
I see this quite a lot in the MVC codebase. Dual responsibilities, exposition of external services through lazy-loaded properties and static gateways. It’s a lot of code to support this role of exposing things JUST for testability’s sake, but is not actually used under the normal execution flow.
So what you wind up happening is a single class that can’t really make up its mind on what story it’s telling me. I see a bunch of things that seem to help it find a view (ViewName, MasterName), as well as the ability to just supply a view directly (the View property). I also see exposing through properties things I shouldn’t set in a controller action. I can swap out the entire ViewEngineCollection for something else, but really, is that what I would ever want to do? You have pieces exposed at several different conceptual levels, without a very clear idea on how the end result will turn out.
How can we make this different?
###
Separating the concerns
First, let’s separate the concepts of “I want to display a view, and HERE IT IS” versus “I want to display a view, and here’s its name”. There are also some redundant pieces that tend to muddy the waters. If we look at the actual work being done to render a view, the amount of information actually needed becomes quite small:
public class NamedViewResult : IActionMethodResult { public string ViewName { get; private set; } public string MasterName { get; private set; } public NamedViewResult(string viewName, string masterName) { ViewName = viewName; MasterName = masterName; } } public class ExplicitViewResult : IActionMethodResult { public IView View { get; private set; } public ExplicitViewResult(IView view) { View = view; } }
Already we see much smaller, much more targeted classes. And if I returned one of these from a controller action, there’s absolutely zero ambiguity on what these class’s responsibilities are. They merely describe what to do, but it’s something else that does the work. Looking at the invoker that handles this request, we wind up with a signature that now looks something like:
public class NamedViewResultInvoker : IActionResultInvoker<NamedViewResult> { private readonly RouteData _routeData; private readonly ViewEngineCollection _viewEngines; public NamedViewResultInvoker(RouteData routeData, ViewEngineCollection viewEngines) { _routeData = routeData; _viewEngines = viewEngines; } public void Invoke(NamedViewResult actionMethodResult) { // Use action method result // and the view engines to render a view
Note that we only use the pieces we need to use. We don’t pass around context objects, whether they’re needed or not. Instead, we depend only on the pieces actually used. I’ll leave the implementation alone as-is, since any more improvements would require creation of more fine-grained interfaces.
What’s interesting here is that I can control how the ViewEngineCollection is built, however I need it built. Because I can now use my container to build up the view engine collection, I can do things like build the list dynamically per request, instead of the singleton manner it is now. I could of course build a singleton instance, but it’s now my choice.
The other nice side effect here is that my invokers start to have much finer-grained interfaces. You know exactly what this class’s responsibilities are simply by looking at its interface. You can see what it does and what it uses. With broad interfaces like ControllerContext, it’s not entirely clear what is used, and why.
For example, the underlying ViewResultBase only uses a small fraction of ControllerContext object, but how would you know? Only by investigating the underlying code.
New Design Guidelines
I think a lot of the design issues I run into in my MVC spelunking excursions could be solved by:
- Close attention to SOLID design
- Following the Tell, Don’t Ask principle
- Favoring composition over inheritance
- Favoring fine-grained interfaces
So why doesn’t everyone just do this? Because design is hard. I still have a long ways to go, as my current AutoMapper configuration API rework has shown me. However, I do feel that careful practice of driving design through behavioral specifications realized in code (AKA, BDD) goes the farthest to achieving good, flexible, clear design. | https://lostechies.com/jimmybogard/2010/06/02/dependency-injection-in-asp-net-mvc-final-look/ | CC-MAIN-2022-40 | refinedweb | 1,205 | 52.9 |
Well, I believe that I have most of the technical bits in place for Mailman for Fedora Hosted. Now we just need to figure out a few policy items... 1) Who can request lists? My proposal: anyone that is listed as an administrator in the project's group in FAS. 2) What sorts of lists can be requested? My proposal: Lists may be reqested for discussing the use of, development of, or disseminating other useful information about (e.g. announcement or commit lists) projects hosted with Fedora. Lists about non-F/OSS topics or F/OSS projects not hosted with Fedora would not be acceptable. 3) What should the policy on list names be? My proposal: A) All list names must be prefixed with "<projectname>-". B) All list names must be suffixed with "-list". C) Lists may optionally have something between the prefix and suffix, as long as it's not obviously vulgar or obscene. For example, the following would be acceptable list names: smolt-list smolt-dev-list smolt-commits-list The purpose for the "-list" suffix is to keep lists in a separate namespace in case we want to use <something>@fedorahosted.org for some other purpose in the future. The exceptions to this rule would be the default "mailman" site list and possibly a list dedicated to discussing the Fedora Hosted service itself (name to be determined later). FESCo or the Fedora Board could approve other exceptions. 4) What should the policy on archives be? My proposal: A) All lists must have public archives. The exception would be the default "mailman" list. B) Requests to remove a post from the archives will be denied unless it can be shown that by *not* removing the post RedHat and/or Fedora face a credible threat of civil or criminal liability. We'll likely require the assistance of RH Legal to make these sorts of determinations (hopefully they will never happen). Jeff | https://listman.redhat.com/archives/fedora-infrastructure-list/2008-February/msg00101.html | CC-MAIN-2021-39 | refinedweb | 322 | 65.12 |
Setting main Window on top using flags parameter not working as I expected
Environment: Windows7 / Qt 5.4.2 with QtCreator 3.4.1 / MSVC2013
I'm having problem setting a qml window on top. I create a new QtQuick 2.4 project and set the flags property as follows:
import QtQuick 2.4 import QtQuick.Window 2.2 Window { visible: true flags: Qt.Window | Qt.WindowStaysOnTopHint MainForm { anchors.fill: parent mouseArea.onClicked: { Qt.quit(); } } }
The result is a window without title bar that stays on top.
I have managed to do what I needed using C++ code, but it'd be great if I can learn why the previous QML code doesn't work...
Just for completeness, you can do this in C++ (using Qt 5.4) as follows:
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QObject *topLevel = engine.rootObjects().value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); Qt::WindowFlags flags = window->flags(); window->setFlags(flags | Qt::WindowStaysOnTopHint); return app.exec(); }
References:
- p3c0 Moderators
@David-A. It works on Ubuntu with Qt 5.4.1. Result is a Window with title bar and stays on top as expected. Could be a bug on windows. Try searching on | https://forum.qt.io/topic/55817/setting-main-window-on-top-using-flags-parameter-not-working-as-i-expected | CC-MAIN-2018-17 | refinedweb | 209 | 62.75 |
Do you have a website, application, or blog which is powered by Vue.js? Or, are you using a Vue-based framework like Vuetify or Nuxt? This guide explains how to add comments to any Vue application using the Hyvor Talk commenting platform.
First, what is Hyvor Talk?
Hyvor Talk is an embeddable, fully-functional commenting platform for any website (that supports many platforms). Among the other similar options available in the market, Hyvor Talk is special due to a few reasons.
- Privacy-focused -- never sell your or your visitors' data, no ads/tracking on your website.
- Fast and lightweight.
- Fully customizable.
- Top-notch moderation panel and tools.
How to Use Hyvor Talk on Your Vue-Powered Site
Step 1: Register your site in Hyvor Talk Console
First of all, you need a Hyvor Account, which you can sign up in a few minutes. Register here. Then, navigate to the Hyvor Talk console. In the console you can find two fields to add your website details. You can add multiple websites here if you want.
Then you can see the newly added website on the top left corner and all the controllers related to that website. This panel gives you full authority to control and customize your Hyvor Talk integration.
Step 2: Integrate Hyvor Talk to your site
Installing Hyvor Talk on your Vue JS powered website can be done easy with hyvor-talk-vue npm library. Let's start installing it.
npm install hyvor-talk-vue
or
yarn add hyvor-talk-vue
Next, we import the above installed Hyvor Talk vue library to our webpages. There are two main components in this library,
Embed and
CommentCount.
Embed-- The comments embed
CommentCount-- Render the comment count of a page
import { Embed } from 'hyvor-talk-vue' ...
Now, you can place the 'Embed' component where you need to place comments.
<template> <div> <Embed websiteId={WEBSITE_ID} id={WEBPAGE_IDENTIFIER} /> </div> </template>
- WEBSITE_ID-- This is a unique identifier of your website. You can copy it from General area in your account console.
- WEBPAGE_IDENTIFIER -- Unique ID to identify the current page. We'll load the different comments section on each page. If you do not set this, the canonical URL of the page will be used as the identifier.
Tip: If you want to load comments when the user scrolls down (Lazy Mode) add
loadMode="scroll" property to embed component like shown bellow.
<Embed websiteId={WEBSITE_ID}
There are several values for loadModes.
Comment Count
There is a separate component to show comment count of each article to keep users engaged on your website. You can do it simply by importing CommentCount component from
hyvor-talk-vue.
import { CommentCount } from 'hyvor-talk-vue' ... <CommentCount websiteId={WEBSITE_ID} id={WEBPAGE_IDENTIFIER} />
- WEBPAGE_IDENTIFIER-- Unique identifier of page/post. Use the same you set in
Embedcomponent. If you do not set any ID there, you'll need to use the canonical URL of the page here.
That's how simple it is to add comments to your vue application. And, there's a lot of customizations available. You can check them in the console or go through our documentation for more details. If you have any questions, feel free to comment below.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/hyvortalk/adding-comments-to-your-vue-application-with-hyvor-talk-54ak | CC-MAIN-2022-33 | refinedweb | 532 | 66.54 |
RegLoadAppKey function
Loads the specified registry hive as an application hive.
Syntax
Parameters
- lpFile [in]
The name of the hive file. This hive must have been created with the RegSaveKey or RegSaveKeyEx function. If the file does not exist, an empty hive file is created with the specified name.
- phkResult [out]
Pointer to the handle for the root key of the loaded hive.
The only way to access keys in the hive is through this handle. The registry will prevent an application from accessing keys in this hive using an absolute path to the key. As a result, it is not possible to navigate to this hive through the registry's namespace.
- samDesired [in]
A mask that specifies the access rights requested for the returned root key. For more information, see Registry Key Security and Access Rights.
- dwOptions [in]
If this parameter is REG_PROCESS_APPKEY, the hive cannot be loaded again while it is loaded by the caller. This prevents access to this registry hive by another caller.
- Reserved
This parameter is reserved. RegLoadKey, RegLoadAppKey does not load the hive under HKEY_LOCAL_MACHINE or HKEY_USERS. Instead, the hive is loaded under a special root that cannot be enumerated. As a result, there is no way to enumerate hives currently loaded by RegLoadAppKey. All operations on hives loaded by RegLoadAppKey have to be performed relative to the handle returned in phkResult.
If two processes are required to perform operations on the same hive, each process must call RegLoadAppKey to retrieve a handle. During the RegLoadAppKey operation, the registry will verify if the file has already been loaded. If it has been loaded, the registry will return a handle to the previously loaded hive rather than re-loading the hive.
All keys inside the hive must have the same security descriptor, otherwise the function will fail. This security descriptor must grant the caller the access specified by the samDesired parameter or the function will fail. You cannot use the RegSetKeySecurity function on any key inside the hive.
In Windows 8 and later, each process can call RegLoadAppKey to load multiple hives. In Windows 7 and earlier, each process can load only one hive using RegLoadAppKey at a time.
Any hive loaded using RegLoadAppKey is automatically unloaded when all handles to the keys inside the hive are closed using RegCloseKey.
To compile an application that uses this function, define _WIN32_WINNT as 0x0600 or later. For more information, see Using the Windows Headers.
Requirements
See also | https://msdn.microsoft.com/en-us/library/ms724886(v=vs.85) | CC-MAIN-2016-40 | refinedweb | 410 | 57.16 |
Create Automated Backups in Google Docs Using the GData API
/skill level/
/viewed/
As you're probably aware, Google Documents offers free online storage for a variety of common files. You can upload Microsoft Office documents, spreadsheets, text files and presentations, then have read/write access to them from anywhere. And even if you don't actually use Google Documents for editing or creating documents, it can serve as a handy backup for your desktop files.
Google hosts a set of APIs called GData that provide a simple way of writing data on the web. The GData APIs don't do much, but they can be used to publish data to any Google web service that supports the GData format. Luckily, Google Docs is one of those services.
We're going to take Google's GData API for Google Docs and use it to automatically upload our local office docs into the online service, all without opening a browser window or clicking on any buttons.
If you want to go a little further, you can create your own web application that creates secure, timed backups of your work.
We'll start out by taking a look at the specific GData APIs that allow you to upload files from your local machine and store them in Google Documents, then attach those to a script to automate everything.
This article is a wiki. Got extra advice about using the Documents List Data API? Log in and add it.
Install the GData API
Because most of what we're going to do is shell-based, we'll be using the the Python GData library. Here's Google's Python GData client.
If you're not a Python fan, there are a number of other client libraries available for interacting with Google Docs, including JavaScript, PHP, .NET, Java and Objective-C. Go ahead and pick from the list.
To get started, download the Python GData Client Library. Follow the instructions for installing the Library as well as the dependencies (in this case, ElementTree -- only necessary if you aren't running Python 2.5)
Now, just to make sure you've got everything set up correctly, fire up a terminal window, start Python and try importing the modules we need:
>>> import gdata.docs >>> import gdata.docs.service
Assuming those imports worked, you're ready to start working with the API.
The first thing we need to get out of the way is what kinds of documents we can upload. There's a handy static member we can access to get a complete list:
>>> from gdata.docs.service import SUPPORTED_FILETYPES >>> SUPPORTED_FILETYPES
Running that command will reveal that these are our supported upload options:
- RTF: application/rtf
- PPT: application/vnd.ms-powerpoint
- DOC: application/msword
- HTM: text/html
- ODS: application/x-vnd.oasis.opendocument.spreadsheet
- ODT: application/vnd.oasis.opendocument.text
- TXT: text/plain
- PPS: application/vnd.ms-powerpoint
- HTML: text/html
- TAB: text/tab-separated-values
- SXW: application/vnd.sun.xml.writer
- TSV: text/tab-separated-values
- CSV: text/csv
- XLS: application/vnd.ms-excel
Definitely not everything you might want to upload, but between the Microsoft's Office options and good old plain text files, you should be able to back up at least the majority of your files.
Now let's take a look at authenticating with the GData API.
Authenticate with GData
Create a new file named
gdata_upload.py and save it somewhere on your Python Path. Now open it in your favorite text editor. Paste in this code:
from gdata.docs import service def create_client(): client = service.DocsService() client.email = 'yourname@gmail.com' client.password = 'password' client.ProgrammaticLogin() return client
All we've done here is create a wrapper function for easy logins. Now, any time we want to log in, we simply call
create_client. To make you code a bit more robust you can pull out those hardcoded
password attributes and define them elsewhere.
Upload a document
Now we need to add a function that will actually upload a document. Just below the code we created above, paste in this function:
def upload_file(file_path, content_type, title=None): import gdata ms = gdata.MediaSource(file_path = file_path, content_type = content_type) client = create_client() entry = client.UploadDocument(ms,title) print 'Link:', entry.GetAlternateLink().href
Now let's play with this stuff in the shell:
>>> import gdata_upload >>> gdata_upload.upload_file('path/to/file.txt','text/plain','Testing gData File Upload') Link:<random string of numbers> >>>
Note that our
upload_file takes an optional parameter "title", if you import Python's date module and pass along the date as a string it's easy to make incremental backups, like:
myfile-082908.txt,
myfile-083008.txt and so on.
Where to go from here
To automate our backup process you could call the upload file function from a cronjob. For instance, I use:
0 21 * * * python path/to/backup_docs.py 2>&1
In this case,
backup_docs.py is just a three-line file that imports our functions from
gdata_uploader.py and then uses Python's
os module to grab a list of files I want backed up and calls the
upload_file function.
While the automated script is a nice extra backup, unfortunately the GData Documents API is somewhat limited. For instance, it would be nice if we could automatically move our document to a specific folder, but that currently isn't possible.
There are some read functions available though, have a look through the official docs and if you come up with a cool way to use the API, be sure to add it to this page.
- This page was last modified 13:13, 10 September 2008.
/related_articles/
- YouTube Tutorial Lesson 2 - The Data API
- Install Django and Build Your First App
- Build a Microblog with Django
- Back Up Disqus Comments
See more related articles
Special Offer For Webmonkey Users
WIRED magazine:
The first word on how technology is changing our world.
Subscribe for just $10 a year | http://www.webmonkey.com/tutorial/Create_Automated_Backups_in_Google_Docs_Using_the_GData_API | crawl-002 | refinedweb | 986 | 56.35 |
Welcome to the Parallax Discussion Forums, sign-up to participate.
#include "simpletools.h" #include "laserping.h" #define LASER 16 #define PING 0 int i; int main() { laserping_start('S', LASER); while(1) { i = laserping_distance(); printi("Distance: %d\n", i); pause(500); } }My setup was a box positioned 150 mm in front of the sensors.
A very helpful post. I have been working with the Ping Ultrasonic detectors and not found the LaserPing to be "code compatible" using the Arduino Ping library.
How can I access the simpletools.h and laserping.h libraries that you reference? I don't find them in the Arduino IDE library manager.
Thanks.
I uploaded it to the Object exchange and you can find it there: Laser Ping Library
Mike | http://forums.parallax.com/discussion/comment/1470053 | CC-MAIN-2019-35 | refinedweb | 123 | 60.11 |
Microsoft 365 Enterprise E5
When you add a subscription through the admin center, the new subscription is associated with the same organization (domain namespace) as your existing subscription. This makes it easier to move users in your organization between subscriptions, or to assign them a license for the additional subscription they need.
Try or buy a Microsoft 365 subscription
Sign in to the admin center at, and then go to Billing > Purchase services.
On the Purchase services page, the subscriptions that are available to your organization are listed. Choose the Microsoft 365 plan that you want to try or buy.
On the next page, choose Get free trial, which gives you 25 user licenses for a one-month term, or you can Buy.
Note
If you start a free trial, skip to step 8.
If you buy, enter the number of user licenses you need and choose whether to pay each month or for the whole year, then choose Check out now.
Your cart opens. Review the pricing information and choose Next.
Provide your payment information, then choose Place order.
On the confirmation page, choose Go to admin home. You're all set!
Choose to receive a text or a call, enter your phone number, then choose Text me or Call me.
Enter the verification code, then choose Start your free trial.
On the Check out page, choose Try now.
On the order receipt page, choose continue.
Not using preview yet?
If you have preview turned off, watch the following video to sign up for a trial Microsoft 365 subscription.
Next steps
After you get the new subscription, you have to assign a license to the users who will use that subscription. To learn how, see Assign licenses to users in Office 365 for business.
Feedback | https://docs.microsoft.com/en-us/office365/admin/try-or-buy-microsoft-365?redirectSourcePath=%252fhr-hr%252farticle%252fIsprobajte-ili-Kupite-pretplatu-na-Microsoft-365-9E8CEAC6-8D20-4D28-837A-D766AE99CBD1&view=o365-worldwide | CC-MAIN-2019-30 | refinedweb | 296 | 74.19 |
On 25 July 2011 01:33, Guido van Rossum <guido at python.org> wrote: > On Sun, Jul 24, 2011 at 3:47 PM, Nick Coghlan <ncoghlan at gmail.com> wrote: > > We've actually been down the 'namespace object' road years ago (Steve > > Bethard even wrote a proto-PEP IIRC) and it suffered the same fate as > > most enum PEPs: everyone has slightly different ideas on what should > > be supported, so you end up being faced with one of two options: > > 1. Ignore some of the use cases (so some users still have to do their own > thing) > > 2. Support all of the use cases by increasing the API complexity (so > > many users will still do their own thing instead of learning the new > > API) > > For enums, I think we should just pick a solution. I'm in favor of > Barry Warsaw's version, flufl.enum. > I generally like the flufl.enum API. There are two things it doesn't do. For new apis it is *usually* possible to just use strings rather than integers - and have your library do the mapping if an underlying api takes integers. For existing ones, for example many parts of the python standard library, we couldn't replace the integer values with enums without a lot of effort. If the flufl enums subclassed integer then replacing most of the existing constants in the standard library would be trivially easy (so we'd have a built-in use case). e The second use case, where you really do want to use integers rather than strings, is where you have flag constants that you "or" together. For example in the standard library we have these in r, gzip, msilib, some in xml.dom.NodeFilter, plus a bunch of others. It would be nice to add support for or'ing of enums whilst retaining a nice repr. I did collect a whole lot of emails from a thread last year and was hoping to put a pep together. I'd support flufl.enum - but it would be better if it was extended so we could use it in the standard library. All the best, Michael Foord > > -- > --Guido van Rossum (python.org/~guido <>) > _______________________________________________ > Python-ideas mailing list > Python-ideas at python.org > > -- May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/python-ideas/2011-July/010828.html | CC-MAIN-2014-10 | refinedweb | 411 | 78.99 |
Currently all HDFS on-disk formats are version by the single layout version. This means that even for changes which might be backward compatible, like the addition of a new edit log op code, we must go through the full `namenode -upgrade' process which requires coordination with DNs, etc. HDFS should support a lighter weight alternative.
Copied description from
HDFS-8075 which is a duplicate and now closed. (by sanjay on APril 7 2015)
Background
- HDFS image layout was changed to use Protobufs to allow easier forward and backward compatibility.
- Hdfs has a layout version which is changed on each change (even if it an optional protobuf field was added).
- Hadoop supports two ways of going back during an upgrade:
- downgrade: go back to old binary version but use existing image/edits so that newly created files are not lost
- rollback: go back to "checkpoint" created before upgrade was started - hence newly created files are lost.
Layout needs to be revisited if we want to support downgrade is some circumstances which we dont today. Here are use cases:
- Some changes can support downgrade even though they was a change in layout since there is not real data loss but only loss of new functionality. E.g. when we added ACLs one could have downgraded - there is no data loss but you will lose the newly created ACLs. That is acceptable for a user since one does not expect to retain the newly added ACLs in an old version.
- Some changes may lead to data-loss if the functionality was used. For example, the recent truncate will cause data loss if the functionality was actually used. Now one can tell admins NOT use such new such new features till the upgrade is finalized in which case one could potentially support downgrade.
- A fairly fundamental change to layout where a downgrade is not possible but a rollback is. Say we change the layout completely from protobuf to something else. Another example is when HDFS moves to support partial namespace in memory - they is likely to be a fairly fundamental change in layout.
Attachments
- is duplicated by
-
- is related to
-
-
-
- relates to
- | https://issues.apache.org/jira/browse/HDFS-5223?subTaskView=all | CC-MAIN-2020-40 | refinedweb | 359 | 59.94 |
Internationalization¶
This page contains the most common techniques needed for managing CommCare HQ localization strings. For more comprehensive information, consult the Django Docs translations page or this helpful blog post.
Tagging strings in views¶
TL;DR:
ugettext should be used in code that will be run per-request.
ugettext_lazy should be used in code that is run at module import.
The management command
makemessages pulls out strings marked for
translation so they can be translated via transifex. All three ugettext
functions mark strings for translation. The actual translation is performed
separately. This is where the ugettext functions differ.
ugettext: The function immediately returns the translation for the currently selected language.
ugettext_lazy: The function converts the string to a translation “promise” object. This is later coerced to a string when rendering a template or otherwise forcing the promise.
ugettext_noop: This function only marks a string as translation string, it does not have any other effect; that is, it always returns the string itself. This should be considered an advanced tool and generally avoided. It could be useful if you need access to both the translated and untranslated strings.
The most common case is just wrapping text with ugettext.
from django.utils.translation import ugettext as _ def my_view(request): messages.success(request, _("Welcome!"))
Typically when code is run as a result of a module being imported, there is not yet a user whose locale can be used for translations, so it must be delayed. This is where ugettext_lazy comes in. It will mark a string for translation, but delay the actual translation as long as possible.
class MyAccountSettingsView(BaseMyAccountView): urlname = 'my_account_settings' page_title = ugettext_lazy("My Information") template_name = 'settings/edit_my_account.html'
When variables are needed in the middle of translated strings, interpolation can be used as normal. However, named variables should be used to ensure that the translator has enough context.
message = _("User '{user}' has successfully been {action}.").format( user=user.raw_username, action=_("Un-Archived") if user.is_active else _("Archived"), )
This ends up in the translations file as:
msgid "User '{user}' has successfully been {action}."
Using
ugettext_lazy¶
The ugettext_lazy method will work in the majority of translation situations. It flags the string for translation but does not translate it until it is rendered for display. If the string needs to be immediately used or manipulated by other methods, this might not work.
When using the value immediately, there is no reason to do lazy translation.
return HttpResponse(ugettext("An error was encountered."))
It is easy to forget to translate form field names, as Django normally builds nice looking text for you. When writing forms, make sure to specify labels with a translation flagged value. These will need to be done with ugettext_lazy.
class BaseUserInfoForm(forms.Form): first_name = forms.CharField(label=ugettext_lazy('First Name'), max_length=50, required=False) last_name = forms.CharField(label=ugettext_lazy('Last Name'), max_length=50, required=False)
ugettext_lazy, a cautionary tale¶
ugettext_lazy does not return a string. This can cause complications.
When using methods to manipulate a string, lazy translated strings will not work properly.
group_name = ugettext("mobile workers") return group_name.upper()
Converting
ugettext_lazy objects to json will crash. You should use
dimagi.utils.web.json_handler to properly coerce it to a string.
>>> import json >>> from django.utils.translation import ugettext_lazy >>> json.dumps({"message": ugettext_lazy("Hello!")}) TypeError: <django.utils.functional.__proxy__ object at 0x7fb50766f3d0> is not JSON serializable >>> from dimagi.utils.web import json_handler >>> json.dumps({"message": ugettext_lazy("Hello!")}, default=json_handler) '{"message": "Hello!"}'
Tagging strings in template files¶
There are two ways translations get tagged in templates.
For simple and short plain text strings, use the trans template tag.
{% trans "Welcome to CommCare HQ" %}
More complex strings (requiring interpolation, variable usage or those that span multiple lines) can make use of the blocktrans tag.
If you need to access a variable from the page context:
{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
If you need to make use of an expression in the translation:
{% blocktrans with amount=article.price %} That will cost $ {{ amount }}. {% endblocktrans %}
This same syntax can also be used with template filters:
{% blocktrans with myvar=value|filter %} This will have {{ myvar }} inside. {% endblocktrans %}
In general, you want to avoid including HTML in translations. This will make it easier for the translator to understand and manipulate the text. However, you can’t always break up the string in a way that gives the translator enough context to accurately do the translation. In that case, HTML inside the translation tags will still be accepted.
{% blocktrans %} Manage Mobile Workers <small>for CommCare Mobile and CommCare HQ Reports</small> {% endblocktrans %}
Text passed as constant strings to template block tag also needs to be translated. This is most often the case in CommCare with forms.
{% crispy form _("Specify New Password") %}
Keeping translations up to date¶
Once a string has been added to the code, we can update the .po file by running makemessages.
To do this for all langauges:
$ django-admin.py makemessages --all
It will be quicker for testing during development to only build one language:
$ django-admin.py makemessages -l fra
After this command has run, your .po files will be up to date. To have content in this file show up on the website you still need to compile the strings.
$ django-admin.py compilemessages
You may notice at this point that not all tagged strings with an associated translation in the .po shows up translated. That could be because Django made a guess on the translated value and marked the string as fuzzy. Any string marked fuzzy will not be displayed and is an indication to the translator to double check this.
Example:
#: corehq/__init__.py:103 #, fuzzy msgid "Export Data" msgstr "Exporter des cas" | https://commcare-hq.readthedocs.io/translations.html | CC-MAIN-2020-34 | refinedweb | 950 | 59.09 |
How do I do so the program dont automatically closes after its been run? Reply greatly appreciated
How do I do so the program dont automatically closes after its been run? Reply greatly appreciated
Simplest thing is to just put in something like
The program will then wait for you to enter something before exiting.The program will then wait for you to enter something before exiting.Code:int a; cin >> a;
Ok, I tryed to make a little thing in dos modus
code:
#include <iostream.h>
#include <stdlib.h>
int main()
{
int age;
cout<<"Please write your age"<<endl;
cin >> age;
int loc;
cout<<"Please write where you live"<<endl;
cin >> loc;
cout<<"you are "<<age<<" years old, and you live in "<<loc<<endl;
int exit;
cin >> exit;
return 0;
}
It doesnt seem to work at this point, it close fast just like earlier, can you see why?
Well I can't see why it should be doing that, but you can put,
in before the return statement.in before the return statement.Code:system ("pause");
I just tried your example (without system ("pause")) and it works fine.
I assume you realise that you are using an integer to hold the value of the user input in response to the question about where the user lives. If you actually want them to write the name of their town or something you should use a character string.
OK, couple of things here.
Firstly:
should be:should be:Code:#include <iostream.h> #include <stdlib.h>
Second, you're asking for location as an integer, you should learn about the char type and about arrays.Second, you're asking for location as an integer, you should learn about the char type and about arrays.Code:#include <iostream> #include <cstdlib> using namespace std;
Lastly read the FAQ on how to pause your
thankz all | http://cboard.cprogramming.com/cplusplus-programming/39597-how-do-i.html | CC-MAIN-2016-30 | refinedweb | 311 | 72.26 |
It’s clearer now, more than ever before, that there’s no expiration on the value of data. It’s because of this that companies hoard data if there’s the slightest chance it can be utilised in the future. Despite this fact, the value of data is at its greatest the closer it is to its point of creation. For example, when dealing with monetary transactions, it’s so much better to carry out fraud prevention instead of just detecting it after the fact.
This means that you’d most likely want to process each new transaction as its own real-time event instead of undertaking micro-batch processing or even waiting for the data to reach a database after the transaction. Nevertheless, you wouldn’t want to throw away important data analysis tools such as windowing. It would be even better if you could customise the windows based on time, number of events, or even some combination of the two. Apache Flink allows you to do all of this with horizontal scalability, to fit any of your needs.
Earlier this year, we released a blog post and a repository for Streamr integrations to Apache Spark. The Spark integration can now also be found as an out-of-the-box integration library in Maven Central. In that blog post, I touched on why Apache Flink is a better real-time streaming data processing engine than Spark.
Here I am going into a little more detail. Apache Spark and Flink are both Big Data processing systems that are basically in-memory databases that allow you to do very fast queries on data (because most data is stored in the RAM). Both guarantee low latencies, high throughput and ‘exactly-once’ processing (different from an at-least-once or at-most-once approach). Both also have libraries for graph processing and machine learning, although Spark’s libraries are more comprehensive due to the larger contributor base. However, there might be changes to this in the near future as the Chinese giant Alibaba has widely adopted Flink. Alibaba has already dedicated teams to further develop the open-source codebase of Apache Flink.
Most differences between Spark Streaming and Flink are because streaming functionalities were added to Spark as an afterthought, whereas Flink was built for streaming from day one.
Because of this, Spark Streaming is only capable of doing its computations in micro-batches whereas Flink is real-time event-based. So if you require true real-time results from your data processing engine, picking Flink over Spark is a fairly obvious choice.
But it isn’t all in Flink’s favour. In many scenarios, Spark is simply faster than Flink, especially with larger volumes of data. In terms of data ingestion, Flink is faster but due to Spark being able to process the windows in parallel, the overall processing time tends to favour Spark. You can find a nice visualisation and more detailed explanations about the differences in this blog post.
In most cases, you get more accurate results with Flink’s event-based windowing when compared to Spark’s time-based only windowing. Spark is also faster when processing large graphs. Conversely, Flink is faster when processing smaller graphs.
Flink also seems to scale better with the number of nodes in a cluster. You can check out more performance comparisons between Spark and Flink in this or this more recent paper.
Some additional benefits of Flink are that it is possible to utilise durable application state saves. This means you can process reruns of your data if it turns out that your machine learning model needs tweaking. You can also use these snapshots of the state in other parts of your architecture if needed.
Flink also allows you to do iterations and delta iterations. Iterations are often used in machine learning and graph processing; you are able to use or check an iteration’s result as a solution. For Spark you have to use loops outside the system to achieve similar results. You can also deploy Apache Storm topologies in older versions of Flink (1.7 and under).
Streamr Labs has created Java and Scala integration templates between Apache Flink and Streamr. The templates use the streamr flink integration library created by Streamr Labs. The capability to pull historical data from Streamr, based on timestamps and message counts, will be included to the library in the future.
If you are new to Apache Flink you might want to start with the integration template repository. You should also check out Flink’s documentation to gain a deeper understanding of how Apache Flink works. Comprehensive guides on how to set up Flink locally on Linux, Mac or Window can be found in the setup section of Flink’s documentation.
The templates are preconfigured to be buildable and runnable with IntelliJ IDEA. So you can simply clone the repository and open the template with your preferred programming language in IDEA. You only need to add your Streamr API key and your subscribe and publish stream IDs to get the template code running. The Streamr API key and stream IDs can be found in Streamr’s Core app.
To use the Helsinki tram demo Marketplace stream that’s used in the templates, go to its Marketplace page, then add it to your purchases (it’s free of charge). You should now be able to see the “Public Transport Demo” stream on your streams page. Next, check if the stream is receiving data by looking at the “Preview” section inside the tram stream details page (the stream might not receive any data between 10PM–2 AM UTC because the trams don’t run at night).
After the tram stream is set up, you should create a new stream for publishing the data coming out of Flink. Use the tram stream’s ID to subscribe to data and the new empty stream’s ID to publish the data.
After Streamr data is flowing through the template successfully, you can start playing around with different aggregations or even Flink’s ML libraries. The flink_streamr integration library hands you the Streamr data as Java maps. This makes handling the data easy; you can simply use the names of the data fields as keys in the map. When publishing data back to Streamr, the data should also be in Map<String, Object> format.
If you are already familiar with Flink and have your own preference on how to set up and run your projects, you can easily include the Streamr Integration to your project by adding this snippet to your pom.xml file:
<dependency>
<groupId>com.streamr.labs</groupId>
<artifactId>streamr_flink</artifactId>
<version>0.1</version>
</dependency>
Then you can start using the connectors by adding these lines to your Flink program:
import com.streamr.labs.streamr_flink.StreamrPublish;
import com.streamr.labs.streamr_flink.StreamrSubscribe;final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();StreamrSubscribe streamrSub = new StreamrSubscribe(
"YOUR_STREAMR_API_KEY", "YOUR_SUB_STREAM_ID");DataStreamSource<Map<String, Object>> tramDataSource = env.addSource(streamrSub);StreamrPublish streamPub = new StreamrPublish(
"YOUR_STREAMR_APIKEY", "YOUR_PUB_STREAM_ID");tramDataSource.addSink(streamrPub);
After everything is set up, you can start doing data aggregations, data analysis, or training machine learning on your own Streamr data, or any streams that you have purchased access to in the Marketplace. | https://medium.com/streamrblog/streamr-integration-templates-to-apache-flink-eea032754fd3?source=collection_home---6------7----------------------- | CC-MAIN-2020-10 | refinedweb | 1,206 | 62.27 |
miniasync is a small library build on top of asyncio to faciliate running small portions of asynchronous code in an otherwise synchronous application
Project description
miniasync
miniasync is a small library build on top of asyncio to faciliate running small portions of asynchronous code in an otherwise synchronous application.
A typical use case is an application which is build as a synchronous application, but at some point needs to make an http request to two different web services and await the results before continuing. In synchronous Python you’d have to do each request in turn - miniasync makes it easier to run both requests in parallel without having to write asyncio boilerplate code.
Example:
import aiofiles import miniasync async def get_file_content(filename): async with aiofiles.open(filename, mode='r') as f: return await f.read() results = miniasync.run( get_file_content('file1.txt'), get_file_content('file2.txt'), ) assert results == [ '<the content of file1.txt>', '<the content of file2.txt>' ]
See the documentation on readthedocs for more examples and API.
License
Copyright © 2018, Alice Heaton. Released under the LGPL 3 License
Changes
V0.1.2
- Documentation fixes
V0.1.1
- Documentation improvements
V0.1.0
- Initial implementation: miniasync.run and miniasync.loop
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/miniasync/ | CC-MAIN-2019-26 | refinedweb | 225 | 50.94 |
The event command assigns collision events to a particle object. Collision events are stored in multi-attributes in the particle shape. The event command returns the event name.
Derived from mel command maya.cmds.event
Example:
import pymel.core as pm pm.event( em=2, t='newCloud' ) # At every collision, emit two new particles into the object # newCloud. The original colliding particles will survive and # remain in their original object. This event will be # assigned to the currently selected object. pm.event( em=2 ) # At every collision, emit two new particles into the same object. pm.event( count=1, em=2 ) # At the first collision for each particle, emit two new particles # into the same object. # Subsequent collisions for that same particle will not cause any # additional particles to be emitted. However, the new particles will # each emit two new ones at their first collision, since they also # belong to the object for which this event has been assigned. pm.event( die=1, count=2 ) # All particles in the selected object will die at their second # collision. pm.event( 'myCloud', name='foo', count=1, q=1 ) # Return the current value of the count parameter for the event "foo" # assigned to particle shape myCloud. The order of the flags is # important. Thef lag you are querying (in this case, -count) must # come before the -q. The -name flag and the particle object name must # come after. pm.event( 'myCloud', d=True, name='foo' ) # Delete the event "foo" assigned to particle shape myCloud. pm.event( 'myCloud', e=True, name='foo', emit=2 ) # Edit the "emit" value of the event "foo" assigned to # particle shape myCloud. pm.event( 'myCloud', proc='myProc' ) # Call the MEL proc "myProc(name, id, name) each time a particle # of myCloud collides with anything. pm.event( name='oldName', e=1, rename='newName' ) # For the selected particle shape, rename the event "oldName" to "newName." | http://www.luma-pictures.com/tools/pymel/docs/1.0/generated/functions/pymel.core.effects/pymel.core.effects.event.html#pymel.core.effects.event | crawl-003 | refinedweb | 314 | 66.94 |
Default WSDL
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
The default WSDL is returned when the argument string wsdl is passed to an HTTP SOAP endpoint that is running on an instance of SQL Server; for example:.
For default WSDL documents, the parameter elements contain type mappings from the WSDL sqltypes:type mappings to SQL Server system data types. For information about these mappings, see Data Type Mappings in Native XML Web Services.
The default WSDL document generated by an endpoint specifies parameter type by referencing one of the types defined in Data Type Mappings or by referencing subtypes of those types, and then additionally adding restrictions. For all string and binary types, the default WSDL returned by the endpoint will include a subtype that includes the XSD maxLength facet for specifying number of bytes or characters.
The maxLength facet is not generated for variable-length types that are declared with the (max) specifier. For decimal and numeric data types, the default WSDL will generate a subtype that includes the XSD totalDigits and fractionDigits facets that will describe the precision and scale of the parameter.
Default WSDL instances include support for mapping SQL Server data types to common language runtime (CLR) types that are provided in the Microsoft .NET Framework 2.0. Because some built-in CLR data types do not align well with SQL Server data types, the System.Data.SqlTypes namespace is provided in the .NET Framework 2.0. This enables a managed type system that could specifically handle many of the facets of the SQL Server data type system that otherwise cannot be mapped within XSD types.
For the .NET Framework 2.0 release, the Web Services Definition Language Tool (Wsdl.exe) has built-in support for generating the appropriate SQL Server to CLR type mappings for default WSDL instances. This support is available whether you are using Wsdl.exe at the command prompt or by way of adding a Web Reference to a Visual Studio 2005 project.
In the WSDL instances that are generated by using this type mapping support, all SQL Server data types are encoded by declaring and using a specific namespace URI () and its corresponding prefix (sqltypes). The following table shows how sqltype:type mappings in WSDL instances generated through the Wsdl.exe tool to map to their corresponding CLR types.
1 Mapped to a class wrapper for an array of System.Xml.XmlNode objects. The wrapper class is named xml for untyped XML parameters, but uses a generated name for typed XML parameters.
2 Mapped to a wrapper class around a single System.Xml.XmlElement object that uses a generated name.
When xml data type parameters are defined in the default WSDL, they are mapped to the sqltypes:xml WSDL data type. This allows for any well-formed XML to be specified without any additional content or schema-based validation. For more information, see Implementing XML in SQL Server
For xml data type parameters bound to an XML namespace, the default WSDL document will generate an <xsd:complexType> element that contains restrictions over the sqltypes:xml type. The typed XML in turn, specifies xsd:any type as the restriction rule. As shown in the following example, this restriction in turn will specify the processContents attribute setting its value to strict and will also specify the namespace attribute and set its value to a list of the corresponding XML namespaces associated with the schema collection to which the typed XML is bound. | https://technet.microsoft.com/en-us/library/ms190983(v=sql.105).aspx | CC-MAIN-2015-22 | refinedweb | 603 | 53.1 |
Candle - signal Hub - A universal 433Mhz signal detector and cloner
It took three weeks to build, but here it is: a device that will easily connect almost any 433Mhz device to your smart home.
The 433 Hub can do two things:
- You can teach it a signal, and from then on it will be able to detect it.
- You can teach it a signal, and from then on it will be able to replay it.
Both of these features come in 'single signal' and 'on+off" versions. So for example:
- You could copy the ON and OFF button from a remote for your 433Mhz sockets, and from then on switch the socket from your smart home controller.
- You could teach it to detect window sensors that have both on and off states.
- You could teach it to detect the alarm signal from a wireless smoke detector.
For each signal that you teach it to recognise, a door sensor will be presented to your controller.
For each signal that you teach it to replay, an on/off switch will be presented to your controller.
Signals take between 8 and 28 bytes to store, depending on complexity and if they are simple or on+off signals. This means an Arduino Nano can store between 20 and 60 signals in just half of it's eeprom (512 bytes).
HARDWARE
Arduino
433Mhz receiver & transmitter
Touch screen (optional, recommended)
or
OLED screen (optional)
Keypad (optional)
Here's the version that uses a touch screen.
Here's a version that uses a keypad.
With a 12 button keypad you can easily replay 10 signals. The last two buttons are used to navigate and make selections in the menu system.
You can also trigger the learning sequences from 4 virtual buttons that the device creates on your controller (detect simple, detect on+off, replay simple, replay on+off).
It works best if you use the touch screen. Using the menu you can delete the last recorded signal, or delete all recorded signals.
It's designed to work with the upcoming Candle privacy friendly smart home, and the Candle Manager. More on that later this year.
CODE
Exactly.
And a learning detector at the same time.
The touch screen code is now also available.
Something I had hoped actually works: it can also copy IR (infrared) signals!
Settings need to be slightly different, as IR signals are 'slower' than RF signals. Changes I made to the settings are:
#define MAXEDGES 100 // instead of 400 #define GRANULARITY 100 // the default settings of '50' also work, but IR signals need less precision. #define MAXIMUMDURATION 66000 #define MINIMUMSILENCE 66000
It doesn't recognise things perfectly, as IR signals don't seem to repeat themselves in the same way. You may have to press the button a few times before the signal can be copied.
I also haven't tested if transmitting the signals actually switches IR devices on and off.
An example:
00000000 > 0 11110111 > 239 00010000 > 8 11101111 > 247
- It can now handle even more 433 signals.
- Slight code simplification
Probably a bit of a noob question, but if I don't have any of the optional items, can I still use this? Will it just save the RF commands until it can't save anymore?
@alowhum said in Candle - signal Hub - A universal 433Mhz signal detector and cloner:
Thanks, and thanks for your private messages!
I managed to build a rf433 sender which is connected to wifi and is outside of the Mysensors environment, and it works, but I can't get my controller (Vera) to communicate with it. This looks like it should work perfectly for what I want it to do!
Thanks for sharing!
I am having issues with the device I made myself which doesn't use this code, so I have decided to give this project a go. One problem though... I copied the sketch from you link, and even without any changes or alterations, the sketch doesn't compile. It gets to line 468 and says "detectedMessage" was not declared in this scope.
Please ignore the above.... I don't know why but I just tried it again and it compiled immediately.
I just worked out what I did! I had commented that I didn't have a touchsceen and that caused the error. I thought I should do this as I don't have one, but I guess I'll have a go at uploading the sketch as it is.
Thanks for the feedback. Let me know if you have any issues and I can try to fix them.
@alowhum I've finished building this. I have also bought a couple cheap window/door sensors to try, but I've hit a snag.
When I joined this to my controller (Vera) it said that it found 2 devices, but when I check my devices I only find one device, and all it says is that it's a node; I have very little in the way of interacting with it. I'm not sure what's going on.... It's weird that it found two devices and only displays one! Seeing that I'm not using any screen, I can't do anything because I thought I could interact with the hub from within my controller. Have I done something wrong?
I haven't tested it without a screen myself. I'll look into it for you and see if I can make the code work optimally without it. I'll get back to you with the updated code.
Awesome, thanks!!!
Here is the new version which should work just fine without a touchscreen attached.
I also added a new playlist feature. If multiple replay requests are received in quick succession (perhaps from a home automation rule that wants to trigger multiple sockets), it can remember these requests and replay them one after the other.
Awesome, thanks for your work! I'll be giving this a go today.
The extra feature of it remembering if multiple commands are given is great too!
I've finally finished building this, but sadly it doesn't want to work with my controller (Vera). When I start the inclusion process I'm says that it has found 2 devices, but when the controller finishes setting it up it only ends up showing one device, and all it says is that it is a node.
Has anyone built this and have had success with Vera? If you are using this, which controller do you use?
It should not show a temperature sensor, since it doesn't have one. Are you sure it has actually connected? Try listening to the serial output of the node (using the Arduino IDE's option to do this), and check if it says that it has connected ok, and that is is showing you the decoded signals then you play the RF signal. You can even try enabling the debug option to get even more details about the node's state.
Thanks for the reply!
It doesn't show a temp sensor. I circled the device that it shows, but of course I only circled one because the second device doesn't show.
@homer Look at your device list on a computer web browser. It appears that you are viewing it with the Vera app on your phone or tablet. I have seen where some devices don't show correctly on the Vera app. I don't know what type of device it will identify as, but you should see "<some device type> (12)" with the key being the (12) as that identifies the node that presented it. Also, do you have any 433Mhz devices that it may be detecting? Looking at the code a bit, it looks like it will present any 433Mhz devices that it sees to your Vera controller.
@dbemowsk thanks for your reply. Yes the screenshot was taken Vera using my phone, but I only did that as I was using the phone at the time. I went out to have a smoke lol after I tried on my laptop.
From what I understand, it should have created devices that then allow for the inclusion of rf433 devices, but if that isn't the case, I'm happy to be corrected!
@homer It creates one device. This device will get more children when it learns more codes.
For example:
- If you teach it a on+off code, the new child will be a toggle switch.
- If you teach it to recognize a signal, the new child will be a motion sensor.
If you are not using the touch screen, then you will also have 4 children that allow you to toggle the recording of the new signals.
- A button to record a single signal that you want to be able to replay.
- A button to start learning of an of+off combo signal (like a power socket that you can turn of and off).
- A button to start learning a single detection signal (like a basic 433 window sensor)
- A button to start learning a on+off detection signal (like a fancy 433 window sensor that supports both open and closed states).
@homer have you commented out the
#define has_screenin the code? They only show up if you don't use a touch screen.
Also, make sure you use the very latest code.
@alowhum Yes, no touchscreen
Here is the first section of the code:
/* * * Signal Hub * * This device can copy signals from wireless remote controls that use the 433 frequency, and then rebroadcast them. It can optionally also copy Infra red (IR) signals. * * It can do this in three ways: * - Copy and replay ON and OFF signals. For example, from cheap wireless power switches. It basically copies remote controls. * - Copy and then replay a single signal. For example, to emulate a window sensor. * - Recognise signals without replaying them. For example, After learning the signal once, it can detect when a window sensor is triggered again. Or when a button on a remote control is pressed. * * This allows you to: * - Create a smart home security solution using cheap window and movement sensors. * - Automatically turn on lights and other devices when you get home, or when the sun goes down etc, using wireless power sockets. * - Control automations using wireless buttons or remote controls. * * An Arduino Nano can store 50 "recognise only" signals, or about 20 on/off signals. You can store any combination of these. If you need to store more signals you could look into using an Arduino Mega. * * Are there any limits? * - This does not work on things like garage door openers or keyless entry systems for cars. * These devices have a very basic protection: the code changes everytime you use it, so replaying signals will not open the door again. * * Security? * - Many cheap 433Mhz devices do not use encryption. This allows us to copy the signal in the first place. * This also means that your neighbour can in theory do the same thing you can: copy and replay signals picked up through the walls. * * * * SETTINGS */ //#define HAS_TOUCH_SCREEN // Have you connected a touch screen? Connecting a touch screen is recommend. //#define MY_ENCRYPTION_SIMPLE_PASSWD "changeme" // If you are using the Candle Manager, the password will be changed to what you chose in the interface automatically. Be aware, the length of the password has an effect on memory use. /* END OF SETTINGS * * * ABOUT THE CODE * * The code has a number of states it can be in. * LISTENING MODE. Here The main loop continuously listens for signals. If it detects it calls three successive funtions: * 1. Check if signal is a signal (SignalViabilityCheck function) * 2. Clean up the signal (signalCleaner function) * 3. Analyse the signal to find the binary code it represents (signalAnalysis function). * * If a valid binary code is found, the next action depends on which 'state' the system is in. * - If in LISTENING_SIMPLE state, then the signal is compared to all the stored signals. It lets you know if there is a match. * - If in LISTENING_ON state, then the signal is compared to all the stored signals. It lets you know if there is a match. * - If in COPYING_SIMPLE state, the code is stored as a 'simple' signal. This can then be replayed later. * - If in COPYING_ON state, the code is stored, after which the system asks for the OFF code (COPYING_OFF state), and then stores it with the same data. * - If in LEARNING_SIMPLE state, only the binary code is stored, and not the meta-data required to fully recreate the signal. * * The final states the system can be in are: * - IN_MENU. This is when the system is displaying a menu on the screen. * - REPLAYING. This is the state while a signal is being replayed. * * Depending on the current state the various functions can work in slightly different ways. * take for example the scanEeprom function: * - When in LISTENING state it compares the latest found signal to existing signals stored in the EEPROM memory. * - When in REPLAYING state it returns data required to rebuild the original signal. * - If called with a 0, then it does not try to recognise or rebuild anything. This is used during setup, when we only need to know how many signals are stored. * * __SIGNAL ANALYSIS DETAILS__ * When it detects a signal, the code tries to find the part of the signal that repeats. * In normal operation the signalCleaner function cleans up the signal and simultaneously tries to find the 'betweenSpace' variable. * Often, 433Mhz signals have a repeating binary code that is interrupted by a short burst of different signals (called the 'anomaly' in this code). * If no anomaly can be detected, then the repeating part is probably 'back to back', without a separator signal. * In this case there is a 'backup' function, the 'pattern finder'. This uses brute force to find the signal. * If both methods fail, then the signal cannot be copied. * * * * TODO * - Check if signal is already stored before storing it. Then again, there can be good reasons to store a signal twice. Perhaps only check for doubles with recognise-only signals? * - Another bit could be used to store if an on/off signal should also be recognisable. That way the remote could be used twice somehow.. Or: * - Request current status of on/off toggles from the controller. Though it might be jarring or even dangerous if all devices suddenly toggled to their new positions. * - Turn off the display after a while. * - Send new children as they are created. */ //#define DEBUG // Do you want to see extra debugging information in the serial output? //#define DEBUG_SCREEN // Do you want to see extra debugging information about the touch screen in the serial output? //#define MY_DEBUG // Enable MySensors debug output to the serial monitor, so you can check if the radio is working ok. // Receiver and transmitter pins #define RECEIVER 3 // The pin where the receiver is connected. #define TRANSMITTER 4 // The pin where the transmitter is connected. #define TOUCH_SCREEN_RX_PIN 7 // The receive (RX) pin for the touchscreen. This connects to the transmit (TX) pin of the touchscreen. #define TOUCH_SCREEN_TX_PIN 8 // The receive (TX) pin for the touchscreen. This connects to the transmit (RX) pin of the touchscreen. // This code has an extra pattern finding trick. Using brute force it will try to find a pattern in the data. The downside is it takes a lot of time to analyse signals this way. // This means the system might not detect a signal because it is busy analysing a bad signal. It's up to you if you want to use it. //#define PATTERN_FINDER // advanced security //#define MY_SECURITY. // REQUIRED LIBRARIES #include <MySensors.h> // The library that helps form the wireless network. #include <EEPROM.h> // Allows for storing data on the Arduino itself, like a mini hard-drive. //#define HAS_BASIC_OLED_SCREEN // Have you connected a simple OLED screen? Connecting a screen is recommend. // Basic OLED screen #ifdef HAS_BASIC_OLED_SCREEN #define INCLUDE_SCROLLING 0 // Simple drivers for the OLED screen. #define OLED_I2C_ADDRESS 0x3C #include <SSD1306Ascii.h> #include <SSD1306AsciiAvrI2c.h> SSD1306AsciiAvrI2c oled; #endif // Touch screen #ifdef HAS_TOUCH_SCREEN #include <SoftwareSerial.h> SoftwareSerial mySerial(TOUCH_SCREEN_RX_PIN,TOUCH_SCREEN_TX_PIN); // RX (receive) pin, TX (transmit) pin #define MAX_BASIC_COMMAND_LENGTH 16 // How many bytes are in the longest basic command? #define TOUCHSCREEN_WIDTH 240 #define TOUCHSCREEN_HEIGHT 320 #define BUTTON_HEIGHT 53 // How many pixels tall are the touch screen buttons? #define BUTTON_PADDING (BUTTON_HEIGHT/2) - 7 // The font is 14 pixels high, so this calculation places it in the middle of the buttons.
Suggested Topics
Sensor for Vallox DigitSE RS485 ventilation system with integration into FHEM.
d-diot Gas sensors and RGB lamp
When 3D printing and electronics work together!
Particle Powered Air Quality Sensor Logging to Google Docs
Irrigation Controller (up to 16 valves with Shift Registers)
Round water tank level sensor
d-diot: dual MySensors gateway for Raspberry... And more! | https://forum.mysensors.org/topic/10094/candle-signal-hub-a-universal-433mhz-signal-detector-and-cloner | CC-MAIN-2019-30 | refinedweb | 2,797 | 73.78 |
Circle of Fourths with Inversions
I’ve been exploring Python and NumPy for synthesizing music. One program I wrote generates circles of fourths, with harmonic seventh chords, and inverts the chords such that all tones fall within a single octave. This gives the feeling of a never ending descent of fifths or ascent of fourths (whichever way you choose to look at it), all without actually leaving the octave range.
First, take a listen:
The Theory
The Circle of Fifths can also be thought of as a circle of fourths. So we start at A (specifically, A3 which is 220 Hz), and work our way around the circle of fifths in a counter-clockwise fashion.
We start at A, working counter-clockwise, to D, G, and so on, until finally ending on E. Since we’ll be repeating the whole sequence, the E resolves back to the A and the process continues on. And since we’re using dominant 7th chords, we have a sense of resolution on each. A7 -> D7 -> G7 … -> E7 -> A7 … and so on.
The Code
The interesting parts of the code are below.
I used my PyWaveTools library to do the synthesis using sine waves. I set the base root note to 220 Hz which is A3. Then we build an array of NOTES to hold all the root notes we’ll be cycling through, stacking in fourths, by multiplying each by a fourth interval. Since a 4th is actually 5 semitones away, and there are 12 semitones in an octave, we use the 2*(5i/12.0) multiplier to achieve a fourth of a given tone1. We do this 11 times to get all 12 notes into the array.
import wavelib SAMPLE_RATE = 44100.0 NOTE = 220.0 # A3 NOTES = [NOTE] note = NOTE for i in range(1, 12): note = NOTE * (2**(5*i/12.0)) # equal temperament NOTES.append(note)
I decided to play each note for one second, so we set up the total duration, and use PyWaveTools to build an array of times for the whole buffer.
NOTE_DURATION = 1 # play each n seconds DURATION = len(NOTES) * NOTE_DURATION times = wavelib.createtimes(DURATION, SAMPLE_RATE)
I wanted to keep all of the tones within the same octave, so I set min/max notes to constrain my frequencies to a between A3 and A4).
# keep it within one octave, so we'll invert as needed notemin = NOTE notemax = NOTE * 2
The intervals array holds all the intervals of each given root note we will generate. In this case, I want a Root note (1), major 3rd (5/4 interval), a perfect fifth (3/2 interval), and a harmonic seventh (7/4 interval). I am using Just Intonation intervals here to minimize the “beats”, which would be intolerable if using Equal Temperament. I chose the harmonic seventh (as opposed to a normal minor seventh interval of 9/5) to sweeten it, again reducing the beats within the chords.
I loop through each interval, so I can build a sine wave for that specific voice within the chord. I then loop through each step in the cycle of fourths, multiply or divide by 2 to get it into the desired octave range, and then set that frequency, f, to a NumPy array at the appropriate 1-second mark. Once I have the frequency array built, I generate the sine wave for that voice. Each voice/harmony sine wave is simply added to the final vals array to build the chord.
# use harmonic 7th (7/4 interval) for smoother beatless chord intervals = [1.0, 5.0/4.0, 3.0/2.0, 7.0/4.0] vals = wavelib.zero(times) for i in range(len(intervals)): interval = intervals[i] freq = wavelib.zero(times) for n in range(len(NOTES)): note = NOTES[n] f = NOTES[n] * interval while f >= notemax: f = f / 2.0 while f < notemin: f = f * 2.0 startidx = int(n * NOTE_DURATION * SAMPLE_RATE) endidx = int(((n+1) * NOTE_DURATION) * SAMPLE_RATE) freq[startidx:endidx] = f vals += wavelib.sinewave(times, freq)
And finally, we normalize the wave values to get it to a consistent gain, then use the play_n function to play the sequence a total of 5 times. This gives us a full 60 seconds of cycling fourth chords.
vals = wavelib.normalize(vals) vals = wavelib.play_n(vals, 5) wavelib.write_wave_file('output/circle_fourths_chords.wav', vals)
The full source code is available in the PyWaveTools repo, specifically this file: circle_fourths_chords.py
Notes
1.: My algorithm originally used the stacking of perfect fourth intervals (4/3 ratio, about 498 cents) to build the circle, as opposed to equal temperament of 500 cents (using the (2*(5i/12.0)) multiplier). Thus by the end where we wrap from E7 to back around to the beginning of the next A, the interval was a little off. It is barely noticable, but I decided to correct it. You can hear the original in the following clip… notice when it wraps from E back to the A (every 12 seconds) the jump feels just slightly off. | http://randbrown.site/python/music/2017/10/15/circle-of-fourths.html | CC-MAIN-2019-30 | refinedweb | 839 | 71.85 |
Red Hat Bugzilla – Bug 725757
NameError: name 'setupProgressDisplay' is not defined
Last modified: 2014-09-30 19:40:13 EDT
Created attachment 515282 [details]
proposed patch
Description of problem:
cmdline mode kickstart install failure
Version-Release number of selected component (if applicable):
* anaconda-16.13
Steps to Reproduce:
1.
Actual results:
Running anaconda 16.13, the Fedora system installer - please wait.
Traceback (most recent call last):
File "/usr/sbin/anaconda", line 747, in <module>
setupDisplay(anaconda, opts)
File "/usr/sbin/anaconda", line 537, in setupDisplay
anaconda.initInterface()
File "/tmp/updates/pyanaconda/__init__.py", line 255, in initInterface
from cmdline import InstallInterface
File "/tmp/updates/pyanaconda/cmdline.py", line 37, in <module>
stepToClasses = { "install" : setupProgressDisplay }
NameError: name 'setupProgressDisplay' is not defined
Expected results:
No traceback
Additional info:
* This impacts the F16 Beta release criteria regarding installation automation - "Any installation method or process designed to run unattended must do so (there should be no prompts requiring user intervention) "
Seems related to commit 8b6d7f89
Ales has patch for it.
Hi James,
Can you please retest with ?
The patch is here:
Thank you.
Ales
(In reply to comment #3)
> Hi James,
>
> Can you please retest with ?
Resolves the reported problem, thanks!
Thanks for testing, pushed as 6caf7e595148a329b4cce915f9d872e196447f9e.
*** Bug 727810 has been marked as a duplicate of this bug. ***
It seems still happen in F16-alpha-RC1.
(In reply to comment #7)
> It seems still happen in F16-alpha-RC1.
Can you please attach the complete traceback? Thanks.
Created attachment 517354 [details]
error log of anaconda 16.14.3
(In reply to comment #8)
> (In reply to comment #7)
> > It seems still happen in F16-alpha-RC1.
>
> Can you please attach the complete traceback? Thanks.
Hi Ales,
I have just test F16-alpha-RC2(anaconda 16.14.3), and still meet this error. The attachment is the screen shot of the error on F16-alpha-RC2. Pleas have a look, thanks.
Hi,
it looks like my change hasn't been merged to the f16-alpha-branch. Can you please retest with post-alpha Anaconda?
Ales
(In reply to comment #11)
> Hi,
>
> it looks like my change hasn't been merged to the f16-alpha-branch. Can you
> please retest with post-alpha Anaconda?
>
> Ales
Okay, I will test with post-alpha Anaconda, thanks!
Hi Ales,
It seems still happen in F16-alpha-RC4, i386 dvd install. The screen shot and anaconda log are in the attachment.
Created attachment 518429 [details]
screen shot of error message
Created attachment 518432 [details]
error log of anaconda 16.14.5
tao: it's expected to happen in all Alpha builds. this bug is not Alpha critical, so the fix is not in any Alpha builds. you'd need to build a test ISO with an anaconda build 16.15 or later - not a build on the 16.14 branch - to check this. 16.14 is the branch for Alpha.
--
Fedora Bugzappers volunteer triage team
Discussed in the 2011-08-26 blocker review meeting. Accepted as a Fedora 16 beta blocker as it violates the following beta release criterion [1]:
Any installation method or process designed to run unattended must do so (there should be no prompts requiring user intervention)
[1]
Tao and/or James: can you please confirm that this is fixed in Beta TC1? Thanks!
I was able to complete an unattended, cmdline kickstart-based minimal install of Beta TC2 using the ks . BobLFoot also reported a 'pass' for this test case in the matrix. So I'm closing this as ERRATA (the fixed anaconda was already pushed to stable). | https://bugzilla.redhat.com/show_bug.cgi?id=725757 | CC-MAIN-2017-26 | refinedweb | 592 | 58.89 |
An Enum that inherits from str.
Project description
StrEnum
StrEnum is a Python
enum.Enum that inherits from
str to complement
enum.IntEnum in the standard library. Supports python 3.6+.
Installation
You can use pip to install.
pip install StrEnum
Usage
from enum import auto from strenum import StrEnum class HttpMethod(StrEnum): GET = auto() HEAD = auto() POST = auto() PUT = auto() DELETE = auto() CONNECT = auto() OPTIONS = auto() TRACE = auto() PATCH = auto() assert HttpMethod.GET == "GET" ## You can use StrEnum values just like strings: import urllib.request req = urllib.request.Request('', method=HttpMethod.HEAD) with urllib.request.urlopen(req) as response: html = response.read() assert len(html) == 0 # HEAD requests do not (usually) include a body
There are classes whose
auto() value folds each member name to upper or lower
case:
from enum import auto from strenum import LowercaseStrEnum, UppercaseStrEnum class Tag(LowercaseStrEnum): Head = auto() Body = auto() Div = auto() assert Tag.Head == "head" assert Tag.Body == "body" assert Tag.Div == "div" class HttpMethod(UppercaseStrEnum): Get = auto() Head = auto() Post = auto() assert HttpMethod.Get == "GET" assert HttpMethod.Head == "HEAD" assert HttpMethod.Post == "POST"
As well as classes whose
auto() value converts each member name to camelCase,
PascalCase, kebab-case and snake_case:
from enum import auto from strenum import CamelCaseStrEnum, PascalCaseStrEnum from strenum import KebabCaseStrEnum, SnakeCaseStrEnum class CamelTestEnum(CamelCaseStrEnum): OneTwoThree = auto() class PascalTestEnum(PascalCaseStrEnum): OneTwoThree = auto() class KebabTestEnum(KebabCaseStrEnum): OneTwoThree = auto() class SnakeTestEnum(SnakeCaseStrEnum): OneTwoThree = auto() assert CamelTestEnum.OneTwoThree == "oneTwoThree" assert PascalTestEnum.OneTwoThree == "OneTwoThree" assert KebabTestEnum.OneTwoThree == "one-two-three" assert SnakeTestEnum.OneTwoThree == "one_two_three"
As with any Enum you can, of course, manually assign values.
from strenum import StrEnum class Shape(StrEnum): CIRCLE = "Circle" assert Shape.CIRCLE == "Circle"
Doing this with other classes, though, won't manipulate values--whatever you assign is the value they will have.
from strenum import KebabCaseStrEnum class Shape(KebabCaseStrEnum): CIRCLE = "Circle" # This will raise an AssertionError because the value wasn't converted to # kebab-case. assert Shape.CIRCLE == "circle"
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please ensure tests pass before submitting a PR. This repository uses Black and Pylint for consistency. Both are run automatically as part of the test suite.
Running the tests
Tests can be run using
make:
make test
This will create a virutal environment, install the module and its test dependencies and run the tests. Alternatively you can do the same thing manually:
python3 -m venv .venv .venv/bin/pip install .[test] .venv/bin/pytest
License
Contents
N.B. Starting with Python 3.11,
enum.StrEnum is available in the standard
library. This implementation is not a drop-in replacement for the standard
library implementation. Sepcifically, the Python devs have decided to case fold
name to lowercase by default when
auto() is used which I think violates the
principle of least surprise.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/StrEnum/ | CC-MAIN-2021-43 | refinedweb | 496 | 51.44 |
Forum:Permission for running a bot
From Uncyclopedia, the content-free encyclopedia.
Now that all the interwiki linkss seem to be working (notice the 33 links in the main page) I ask the admins here for permission to have on of the Spanish-language uncyclopedia running a bot to add interwikis. I'd ask Carlb, but he's been absent for a while now. The bot was actually sporked from his and updated, work's just fine at es:. ---Asteroid B612
(aka Rataube) - Ñ 17:45, 12 November 2006 (UTC)
- I havn't got a problem with it, as none of the other admins have I'm guessing they feel the same!--The Right Honourable Maj Sir Elvis UmP KUN FIC MDA VFH Bur. CM and bars UGM F@H (Petition) 22:45, 25 November 2006 (UTC)
Also, who's in charge of meta and uncyclopedia.info now that Carlb is absent? Couse some proposed a collaboration portal for the iberian lanaguages (spanish, portuguese, catalan, galician, etc) or even all the latin languages, and I thought meta or babel might be the right places.---Asteroid B612
(aka Rataube) - Ñ 19:27, 12 November 2006 (UTC)
- The metawiki already has its own sysops (nominated from when it was on Chron's server), meta:special:listusers/sysop would be a good place to start. The 'bot flags? Those are given out by bureaucrats on each individual wiki, and are used primarily for bots that would otherwise be spamming special:recentchanges with massive numbers of minor edits. If you plan to make a thousand edits in one session, please do contact one of the bureaucrats and get a 'bot flag first. It is also advisable to create a userpage on each language wiki affected by an interwiki.py instance, identifying both the evil killer robot and its human (or inhuman) handler. There'd be more than two dozen by now. The 'bot would need a separate userid so it can be shutdown in a hurry if it malfunctions if it malfunctions if it malfunctions if it malfunctions *thud* sorry about that, minor malfunction there. Beyond that, I don't think there is a strict policy on bots if they're doing something useful.
- In any case, the matter is entirely out of my hands. I'm not a bureaucrat, I am not the one to contact if you need a 'bot flag. I'm not the author of any of the 'bot code; the pywikipediabot project on sourceforge is the place to look for technical info. While I used to run a 'bot here, I had to discontinue the practice months ago as too many broken interlanguage links were appearing when trying to link from here to many other languages. --Carlb 00:51, 26 November 2006 (UTC)
- Well, Thanks. I will create the bot user here user:ChixpyBot, but I don't have an account here and the links to the handler will go to my account in Wikia (in Inciclopedia to be exact).
- About the families.py, I copy it from User:Hymie the SpelChek™ bot/uncyclopedia family.py, but it halted many times because the URLs of some wikis were wrong, after I fixed they the bot works nicely. You can see my "famisannse
(talk) 20:15, 29 November 2006 (UTC)lies,py" here. The ja: interwiki is commented out because no works in Inciclopedia the others are duplicates.
- I will run it from Inciclopedia..., then the bot will add only the pages of Inciclopedia that have interwiki to Uncy, but the interwikis are from all wikis found. I will skip some of then because there are some pages with a mess
- About bot flag... as far I know in wikia's wiki can't be set... (but I'm only a Sysop) @ Chixpy from Inciclopedia 19:08, 26 November 2006 (UTC)
- Well the puppet user is created, when you say (bot flag, etc) that all is correct I will do my first run --ChixpyBot 19:37, 26 November 2006 (UTC)
- Hi, is this just a bot flag for this wiki? or any other versions on Wikia? Everyone... you got 4 days to scream if you don't want this bot flag for Uncyc... otherwise I'll turn it on on Monday. Ta -- sannse
(talk) 20:15, 29 November 2006 (UTC)
- Well, the same interwiki.py instance writes in Valenciclopedia and Inciclopedia too. In wikia the bot's username is the same. --ChixpyBot 21:02, 29 November 2006 (UTC)
- OK, I will ask about the bot flag in Valenciclopedia, Inciclopedia and Nonsensopedia.
- I will link to the permissions of use the bot in the other wikis.
- The permission to use in Nonsensopedia is here and here.
- The permission to use in Valenciclopedia is here in Uniò Llatina title asked by Fer in Valenciá, (I don't know why the link don't give the title directly)
- In Inciclopedia it's not clear where is the permission to use it... ^_^U. here and here too (In Spanish), Rataube asks me if I know how to run a bot, how many interwikis work (23 in this moment) and something else.
- I will ask in the affected wikis now about the flag bot, after all if they want to hide the changes of this account is their decission XD
- --ChixpyBot 02:43, 3 December 2006 (UTC)
- I haven't gave approval for setting flag for this bot on Nonsensopedia (actually I can't give it myself). I've just said it will be good when bot won't miss Nonsensopedia in updating. It can work on Nonsensopedia without flag, there's no many interwiki to update and Chixpy is confirming every edit manually, so bot won't flood RC. Szoferka 05:00, 3 December 2006 (UTC)
In edit conflict
- Relax, Szoferka... Nobody says here that the bot flag will be set in Nonsensopedia, as I do with you I'm only asking...
- Well, I ask to the bureaucrats of the wikis that will be changed.
For Nonsensopedia, I ask Szoferka (here. He may reply here).He replied here
- For Inciclopedia, I ask The Great and Magnanimus Rataube I "el Xusto" (Follow this, in spanish)
- Finally, for Valenciclopedia. ca:Usuari:Toni de l'Hostal (Of course the link, spanish too)
- In the three, I ask with the main with my username Chixpy.
- I hope I'm doing it well... I think that next time a table like this can do the work a little easier XD:
- ↑ 1.0 1.1 I found a better link for Inciclopedia
- ↑ 2.0 2.1 2.2 With "never", I want to say that I will never try to get this flag
- ↑ Not needed. Only few pages blocked for non Sysop users in main space (Main Page, Community Portal, etc)
- Now, I only wait.
--ChixpyBot 06:24, 3 December 2006 (UTC)
- PD: About flood RC. After RCMurphy aprobation you can see for example... [1]
- Of course next runs will be smaller than the first... --ChixpyBot 06:36, 3 December 2006 (UTC)
- If by community aproval Sannse can take bureaus' answer, mine is whatever. I only asked for a flag here at uncy, becouse I understood from Carl's words that the flag was a requirement.---Asteroid B612
(aka Rataube) - Ñ 14:14, 3 December 2006 (UTC)
- One more question, the flags allow a user to choose wether he wants to hide the changes by a bot or not, right? If a bot gets the flag, you can still see the changes in recent changes if you choose to?---Asteroid B612
(aka Rataube) - Ñ 14:17, 4 December 2006 (UTC)
WOW, another edit conflict
- Well, I updated the previous table.
- Toni's answer is here(Engrich) and here(Valencià), but the bot flag is not nedeed and it's not my choice to use the flag. So, I think we'd better leave it as No use the flag in Valenciclopedia.
- And Rataube answers here, we are voting now.
- --ChixpyBot 14:59, 3 December 2006 (UTC)
I just wanna say there will no problem with sysop protected pages on Nonsensopedia, coz we don't have any full protected content pages and only five other full protected in "Project:" and "Template:" namespaces. Szoferka 17:21, 3 December 2006 (UTC)
OK, ChixpyBot is botted here, (sorry, forgot to do that on Monday) -- sannse
(talk) 16:22, 7 December 2006 )
(just moving this here - HumboT appears to be an interwiki.py with contribs: pt/cs --Carlb 19:23, 27 January 2007 (UTC))
- As usual, this needs community approval, and then I can flag. It might be an idea for Humbertomc to run this for a while without the flag... then everyone can check they are happy with the edits before they are hidden on Recent Changes -- sannse
(talk) 19:55, 28 January 2007 (UTC)
- Well, i configured the bot for connect the bot, BUT, i can't connect it. I think there's something wrong. My bot can't connect on Wikia's Uncyclopedias:nonsenso(pl) and uncyclo(en), but in desciclo(pt) and Necyklo(cs) everything is right. I join the wikia's channel on irc, and they said there r making some changes in server, probably thats the reason. Someone could help me? :) HumboT 16:39, 29 January 2007 (UTC) | http://uncyclopedia.wikia.com/wiki/Forum:Permission_for_running_a_bot | crawl-002 | refinedweb | 1,550 | 70.23 |
Solved!
Go to Solution.
@Sirisha2020 :
Hope below code will help you out in saving response to txt file, it will work in tear down script of test case:
import groovy.json.JsonOutput;
testCase.testStepList.each{
type = it.config.type
name = it.name
response = it.getPropertyValue("Response")
if(type == "restrequest"){
def pretty = JsonOutput.prettyPrint(response);
def responseFile="F://testing//"+name.toString()+"__response.txt";
def rsfile = new File(responseFile);
rsfile.write(pretty, "UTF-8");
}
}
Click "Accept as Solution" if my answer has helped,Remember to give "Kudos" 🙂 ↓↓↓↓↓
View solution in original post
Thank you Himanshu🙂
@Sirisha2020 Does this code help?
Hi Himanshu,
i am able to write the response to a document. But i am trying to update the request to a separate word document it is not saving the request along with the time stamp to the word document. Please find the code as below :
def rawRequest = JsonOutput.prettyPrint(request);def file1 = new File("C://Users//appu//Desktop//proj//groovy1.doc");file1.write (rawRequest,"UTF-8");
I tried various ways to get the request but no luck. Also i want to save request and response along with time stamp.
Thanks. | https://community.smartbear.com/t5/API-Functional-Security-Testing/i-want-to-save-REST-Response-on-test-case-level-to-a-notepad-or/m-p/206894/highlight/true | CC-MAIN-2021-10 | refinedweb | 189 | 52.76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.