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
Lab 12: matplotlib Logistics Due: Tuesday, November 19th no later than 11:58 p.m. Partner Information: Complete this assignment individually. Submission Instructions: Upload your solution, named YourFirstName-YourLastName-Lab12.py to the BrightSpace Lab 12 matplotlib to display information. Continue to gain experience with numpy. Background The Registrars Office at Montana State University makes various enrollment statistics available. The file, fall-2019.csv captures some of the information that is available in the Fall 2019 Report G - Part A: Headcount Enrollment, All Students by Primary Major. The first line contains how many lines of data follow. Each subsequent line contains the name of one of MSU's colleges (such as CLS for the College of Letters & Science) followed by the Fall 2019 enrollment for that college. Use lab12.py , renamed according to the instructions above, as a starting point. The read_file function should return (1) a numpy array that contains each college name and (2) a corresponding numpy array that contains each college's enrollment. The main function should produce the desired bar graph using the information contained in the numpy arrays named college_names and college_enrollments. Assignment Write a program that matches this graph as closely as possibly. Grading - 10 points Each of the following categories are all or nothing: 1 point - The upper gray bar contains the words Montana State University Fall 2019 Enrollments . 1 point - The x-axis is labeled College Name and the y-axis is labeled College Enrollment . 1 point - The y-axis goes from 0 to 4400 in increments of 400. 1 point - The x-axis contains the same college names that appear in the input file. 2 points - The bar graph reflects the data in the file accurately. 1 point - The colors of the bars in the bar graph alternate between "blue" and "gold". 2 points - The function read_file returns (1) one numpy array that contains the names of the colleges and (2) a second numpy array that contains the enrollments of the colleges. 1 point - The bar graph is created and plotted entirely in the main function. If Time Remains Work on Program 5, seeking feedback from your lab assistant if desired.
https://www.cs.montana.edu/paxton/classes/csci127/inlabs/lab12/
CC-MAIN-2022-05
refinedweb
360
56.25
Re: [STAThread] - From: "Willy Denoyette [MVP]" <willy.denoyette@xxxxxxxxxx> - Date: Wed, 12 Apr 2006 01:11:44 +0200 "Jon Skeet [C# MVP]" <skeet@xxxxxxxxx> wrote in message news:MPG.1ea602fc4da98b5f98d08b@xxxxxxxxxxxxxxxxxxxxxxx | Willy Denoyette [MVP] <willy.denoyette@xxxxxxxxxx> wrote: | > | Nah - I hardly know anything about COM. I've seen various things about | > | COM marshalling "just working" that never seemed to "just work" when I | > | tried it. My knowledge is very flaky in this area. I want it to stay | > | that way in some senses - I hope to have very little to so with it! | > | > Well, you can hardly stay out of it, remember .NET on Windows is COM3 :-), | > take away COM and look what's left. | | Quite a lot, IMO. Put it this way - I doubt that Mono on Linux uses | COM, and it still manages to be useful. Java doesn't use COM (at least | not on non-Windows platforms) and manages to achieve many of the same | things as .NET. I don't see why COM is a necessary part of applications | which don't appear to naturally require it. | True, but that's because Linux doesn't have COM. That means you don't need to interop with existing COM servers (like the Office product suite, Exchange server, a zillion of VB6 applications....). Believe me, without COM, .NET would have died before it was even born, for the same reason why Java failed on the Windows client. Note also that Windows isn't Unix or Linux, most existing applications on windows are COM based (directly or under the covers). Services like Exchange, SQL Server and many more expsose their functionality to the external world through COM. Internally, they use COM as a glue in order to build complex systems using an higly modular design (look at SQL server and count the number of COM dll's included in bin and bi. To get an idea about the number of COM interfaces available in a system, watch your registry and count the number of COM classes registered, you might be suprised. Nor does it have to interop with things like Active Directory,ADO, COM+ services, CDO, OLEDB, OleTx, MSMG, DirectX and WMI to name a few, that's why there are no System.DirectoryServices, System.EnterpriseServices, System.Messaging, System.Data, System.Transactions, System.Drawing and System.Management namespaces available in mono. And don't get me started on the profiler, debugger and hosting services as now available in V2, the hosting interfaces,just like the profiler and debugger interfaces (COM) are needed to ease the interoperation between unmanaged code and managed code. The unmanaged (again COM) hosting interface is used by SQL Server 2005, and all serious debuggers and profilers are written in unmanaged C/C++. | > Also, don't believe that COM is going | > away, it's just moving down from the user level to the system level, Vista | > has a lot more COM components added than there are .NET components. Actually | > Vista can run without .NET, but it can't without COM. | | Fine, I can live with that. | | > Note that I'm not talking about technologies built on top of COM (like | > ActiveX, OLE etc), I'm talking about the low level COM binary interface | > standard, which makes it possible for software components (whatever | > language) to interoperate seamlessly using a well defined standard | > interface. | > Once you understand the COM interface definitions (the object model) and | > it's rules, you'll better understand why/how things are working (or | > fail). | | Hmm... unfortunately, in my limited experience things don't quite work | as they're meant to. For instance, the way you expressed the use of COM | in a previous message suggested that if I'm using a COM wrapper that | requires an STA, it's more efficient to specify STAThread but that | things should still work without, via marshalling. Well, thinking of | the one time I've definitely had to use COM explicitly in C#, things | didn't work at all without STAThread. (I can't remember the exact error | message, unfortunately.) It could very well be that this was a badly | written COM library, but my impression from messages I've read over the | years is that there are more badly written bits of COM than well | written ones... | The major problem with .NET is the fact that users start to run multiple thread to create all kind of objects, without respecting some basic rules. Two important rules that seems to be forgotten quite often, are: - Windows UI elements have thread affinity, so don't touch them from another thread than the creator's thread, and - 'Apartment' threaded COM objects have STA thread affinity, and while COM takes care of this, it's far better to arrange that your objects run on the creator's STA thread, which is preferably the UI thread. If you don't take care of this, you'll incur marshaling overhead, worse, if your objects marshals to the COM default thread, make sure it's a pumping thread (like the UI thread), or you will block the finalizer thread. Note that you might have some issues with 'apartment' threaded objects in a multi-threaded application, but once you follow some simple rules, they are quite simple to use. Note also that most COM classes are 'both' threaded, so they can live in an STA and an MTA. Some quite sophisticated COM objects are thread neutral (just like CLR objects), and they don't need an apartment to live in, but they are quite complex to author (correctly). Honestly, take some time to learn the basics of COM, I'm sure you will like it. Willy. . - Follow-Ups: - Re: [STAThread] - From: Jon Skeet [C# MVP] - References: - Re: [STAThread] - From: Willy Denoyette [MVP] - Re: [STAThread] - From: Michael Nemtsev - Re: [STAThread] - From: Jon Skeet [C# MVP] - Re: [STAThread] - From: Willy Denoyette [MVP] - Re: [STAThread] - From: Jon Skeet [C# MVP] - Prev by Date: Re: Winforms Picturebox control - Next by Date: Re: C# Remoting ??? - Previous by thread: Re: [STAThread] - Next by thread: Re: [STAThread] - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2006-04/msg01743.html
crawl-002
refinedweb
1,008
67.99
emulab-devel:0b056d93c3e7ea3358a0c8163972bd8a5366446b commits 2005-01-12T00:43:15+00:00 Allow a switch to be in more than one stack at a time, as in a switch 2005-01-12T00:43:15+00:00 Robert Ricci ricci@cs.utah.edu that is both in the experimental and control nets. New firewall directory. Has the master file that describes the default 2005-01-11T23:37:42+00:00 Mike Hibler mike@flux.utah.edu. New table, default_firewall_vars, for firewall variables. 2005-01-11T23:34:43+00:00 Mike Hibler mike@flux.utah.edu Also, reflect new way of populating default_firewall_rules (not done here anymore, done in the new firewall subdirectory) Changes to allow variable expansion in firewall rules 2005-01-11T23:33:08+00:00 Mike Hibler mike@flux.utah.edu Fetch values of firewall variables from the DB rather than just making 2005-01-11T21:54:27+00:00 Mike Hibler mike@flux.utah.edu them up! Add "obstacles" for robots to avoid. 2005-01-11T19:38:09+00:00 Leigh B. Stoller stoller@flux.utah.edu * New database table to store obstacles, in the usual coord system; x1,y1, is the upper left corner. * New web page to dump the entire obstacle list <a href="" rel="nofollow noreferrer noopener" target="_blank"></a> *. Clarify some questions Woojin @KISTI had. 2005-01-11T18:50:03+00:00 Robert Ricci ricci@cs.utah.edu Oops, dabbrevs error ... change TBWebdbAllowed to TBWebCamAllowed(). 2005-01-11T01:00:24+00:00 Leigh B. Stoller stoller@flux.utah.edu A quick hack job to get the webcams onto the web interface. 2005-01-11T00:52:52+00:00 Leigh B. Stoller stoller@flux.utah.edu *. Make it clear to the poor admin (eg, Jay) how he can recover from thinking 2005-01-10T22:29:47+00:00 Jay Lepreau lepreau@flux.utah.edu that text will get emailed with the "postpone" menu selection. Whoops, forgot the goo to generate the shd GNUmakefile... 2005-01-10T22:18:47+00:00 Mike Hibler mike@flux.utah.edu Experimental support for Sid's checkpointer. 2005-01-10T22:11:01+00:00 Mike Hibler mike@flux.utah.edu. Minor tweaks so that we can default boss/ops to pc850s, but allow us 2005-01-10T20:08:50+00:00 Leigh B. Stoller stoller@flux.utah.edu to override from the NS file. In your NS file: namespace eval TBCOMPAT { set elabinelab_fixnodes("boss") pc171 set elabinelab_hardware("boss") pc2000 set elabinelab_hardware("ops") pc2000 } A short note on configuring the testbed tree for a cross-compile 2005-01-10T17:06:01+00:00 Timothy Stack stack@flux.utah.edu environment. Updated makefile that builds garcia-pilot 2005-01-10T16:44:58+00:00 Timothy Stack stack@flux.utah.edu 2005-01-10T16:41:25+00:00 Timothy Stack stack@flux.utah.edu. Temp change; I am am still copying over a couple of files to the target 2005-01-10T16:23:30+00:00 Leigh B. Stoller stoller@flux.utah.edu boss node, which were coming from my home dir. Take them from the source tree instead in /proj. Just can't resist pissing on things... 2005-01-08T01:57:45+00:00 Mike Hibler mike@flux.utah.edu Try my hand at modifying named config creation. Allows for "fs" to be different than ops/users. Also tried to eliminate some redundant output. We still generate multiple A records for some IPs (e.g., "ops" and "users") and don't (I think) generate MX records consistently. We don't have enough config time variables yet, so I added: 2005-01-08T01:52:13+00:00 Mike Hibler mike@flux.utah.edu. Checkpoint some minor fixes so thet go into new images. 2005-01-08T00:01:36+00:00 Leigh B. Stoller stoller@flux.utah.edu Crap, have to make sure the log file is unbuffered or else all is lost 2005-01-07T22:44:26+00:00 Leigh B. Stoller stoller@flux.utah.edu when the node reboots. Slight improvment to disgusting hack in last revision, to make sure we 2005-01-07T22:10:12+00:00 Leigh B. Stoller stoller@flux.utah.edu read in all of the bootlog data. * Make sure we capture STDERR. 2005-01-07T21:11:46+00:00 Leigh B. Stoller stoller@flux.utah.edu * Do not exit from the cdboot, just return! sync with GNUmakefile in freebsd directory 2005-01-07T21:00:18+00:00 Mike Hibler mike@flux.utah.edu Fix divide by zero error. 2005-01-07T20:53:47+00:00 Leigh B. Stoller stoller@flux.utah.edu adding first time 2005-01-07T20:04:52+00:00 Siddharth Aggarwal saggarwa@flux.utah.edu Named setup gets a serious collagen injection ... As per Mike/Rob 2005-01-07T18:53:45+00:00 Leigh B. Stoller stoller@flux.utah.edu). Fix eid length in virt_vtypes table. 2005-01-07T17:35:56+00:00 Leigh B. Stoller stoller@flux.utah.edu Add a sanity check to make sure that we have appropriate stacks for 2005-01-06T23:53:20+00:00 Robert Ricci ricci@cs.utah.edu all ports that have been specified. Hmm, somehow, I was editing a VERY old revision of this file when I 2005-01-06T22:35:35+00:00 Robert Ricci ricci@cs.utah.edu made my last commit. Re-apply my changes to the right version of the file. Bring the switch stack creation doc. up to date. 2005-01-06T22:23:29+00:00 Robert Ricci ricci@cs.utah.edu Code works for checkpointing active filesystem on s1 2005-01-06T20:45:47+00:00 Siddharth Aggarwal saggarwa@flux.utah.edu Code works for checkpointing an active filesystem on s1 2005-01-06T20:44:48+00:00 Siddharth Aggarwal saggarwa@flux.utah.edu A bunch of boot changes. Read carefully. 2005-01-06T19:33:13+00:00 Leigh B. Stoller stoller@flux.utah.edu *. Left out call to endStateWait(). No biggie; just being pedantic. 2005-01-06T18:57:21+00:00 Leigh B. Stoller stoller@flux.utah.edu Return some firewall variables/values which can be used in firewall rules. 2005-01-06T00:10:49+00:00 Mike Hibler mike@flux.utah.edu Bump version # to 22 as a result. more graceful failure if tmcc fails 2005-01-06T00:08:59+00:00 Mike Hibler mike@flux.utah.edu Minor CygWin setup script fixes. 2005-01-04T23:11:34+00:00 Russ Fish fish@flux.utah.edu The CygWin minires-devel package includes resolv.h, __res_init, and __res_state. 2005-01-04T23:10:27+00:00 Russ Fish fish@flux.utah.edu This is used to locate the Boss, assuming that it provides the DNS service. Create an /etc/resolv.conf file at boot-up from the ipconfig DNS state. Switch to using sitevars for autoswap mode (checkbox checked) and 2005-01-04T00:26:57+00:00 Leigh B. Stoller stoller@flux.utah.edu threshold.
https://gitlab.flux.utah.edu/emulab/emulab-devel/-/commits/0b056d93c3e7ea3358a0c8163972bd8a5366446b?format=atom
CC-MAIN-2021-43
refinedweb
1,155
54.08
The procedure of translating a Qt Quick application is similar to a Qt Widgets application. We'll walk through the process with another example application. Create a new Qt Quick application project and name it Internationalization_QML. The generated main.qml file has already added a qsTr() function for us. The contents may differ slightly in a later version of Qt Creator and (or) Qt Library. However, it should look similar to this one: import QtQuick 2.3 import QtQuick.Controls 1.2 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("&Open") onTriggered: console.log("Open action triggered"); } MenuItem { text: qsTr("Exit") ... No credit card required
https://www.safaribooksonline.com/library/view/qt-5-blueprints/9781784394615/ch08s05.html
CC-MAIN-2018-26
refinedweb
117
53.27
Factories and Functions for Fiddling with Units Project description Introduction F3U1 - Factories and Functions for Fiddling with Units. Backstory Once upon a time, the quest for a method to format seconds into a human readable string was given to a hero. Braving through the nets of Inter, our hero stumbled upon place after places, such as State of Active, the Exchange of Stacks, and even some other Hubs of Gits. Some giants were found, like Tens of Tens Lines Long of Repetition, others were touching strange, unrelated things and looking complicated. Those that spoke in other unworldly incantations were of no use. In the end, our hero gave up, and constructed this monstrosity from the corpses of fairies: def format_timedelta(delta_t): hours = delta_t.seconds / 3600 days = delta_t.days seconds = delta_t.seconds # Don't ask. Read the test; be happy you don't have to write this. # (WTB something simple like str(delta_t) with more control.) # (Maybe I should just do this in javascript?) return '%(day)s%(hour)s' % { 'day': days and '%(days)d day%(dayp)s%(comma)s' % { 'days': days, 'dayp': days != 1 and 's' or '', 'comma': seconds > 3599 and ', ' or '', } or '', 'hour': (hours > 0 or days == 0 and hours == 0) and '%(hours)d hour%(hourp)s' % { 'hours': hours, 'hourp': hours != 1 and 's' or '', } or '', } (OOC: It was actually tested; see earliest commits). Then the realization hit our hero: sometimes a dworf want to micromanage the resolution in minutes, and then the middle management dino will come back and stamp on all the things and make the resolution to be no lesser than a weeks in the name of opsec. These arbitrary changes to this tiny simple thing resulted in many gnashing of teeth and also many nightmares that never seem to end. Many cries of F7U12 was thrown about. After countless nanoseconds of meditation, our hero destroyed 4 of those F’s and 11 of those U’s towards the direction of the unseen horizon, the solution was discovered, and it is one that transcends beyond time. What? This resulted in the creation of original F3U1 - Factory For Formatting Units. Other descriptions used to fit, including Factory of Functions for Formatting Units or Formatting Functions from Functions for Units. However, over time as this module matured, it really became Factories and Functions for Fiddling with Units. While this started as a module for formatting time into a human friendly string, this got generalized to be able to format arbitrary units, such as non-metric measurements units, into a human readable string. Then this got further generalized into being callable objects that can be used to construct an object representing some value and then be casted into the same human readable string. How? Just install with pip in your virtualenv setup. Alternatively you may clone this repository for running the tests, which will require some other dependencies which are specified inside the requirements.txt: $ git clone git://github.com/metatoaster/mtj.f3u1.git $ cd mtj.f3u1 $ pip install -r requirements.txt $ python setup.py develop Examples Using a predefined unit: >>> from mtj.f3u1.units import Time >>> value = Time(second=90210) >>> print value 1 day, 1 hour, 3 minutes, 30 seconds Or create your own group of units: >>> from mtj.f3u1.factory import UnitGroup >>> Custom = UnitGroup(base_unit='one', ratios={ ... 'thousand': 1000, ... 'hundred': 100, ... 'ten': 10, ... }) >>> custom = Custom(thousand=2, hundred=5, one=621) >>> print custom 3 thousand, 1 hundred, 2 ten, 1 one Resolution limitation can be done also: >>> value = Time('hour', second=99999) >>> print value 1 day, 3 hours Construction of the value can use any key as part of the defined set of units: >>> value = Time(hour=1, minute=99999) >>> print value 69 days, 11 hours, 39 minutes Any unit definitions can be respecified, along with their associated plural form: >>> TimeWithWeek = Time.respecify({'week': 604800}, ... plurals={'week': 'weeks'}) >>> value = TimeWithWeek(hour=1, minute=99999) >>> print value 9 weeks, 6 days, 11 hours, 39 minutes Note: currently the values are all limited to positive integers. This may change to be more inclusive in the future. Maybe if I go insane I might add a full blown units conversion and mathematics into here. Changelog 0.2 - 2014-11-07 - Python 3 compatibility. - Allow specification of the divider between elements. 0.1 - 2013-04-10 - Core functionality of formatting time into a human readable string is provided. - Other units are also provided, and new units can be constructed from a definition of ratios. 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/mtj.f3u1/
CC-MAIN-2018-47
refinedweb
769
63.19
Copies one or more files. FileCopy ( "source", "dest" [, flag = 0] ) See FileFindFirstFile() for a discussion about wildcards. The destination directory must already exist, except using with flag value $FC_CREATEPATH (8). For instance the combined flag $FC_OVERWRITE (1) + $FC_CREATEPATH (8) overwrites the target file and pre-checks for the destination directory structure and if it doesn't exist creates it automatically. Some file attributes can make the overwriting impossible, if this is the case look at FileSetAttrib() to change the attributes of a file. DirCopy, DirCreate, FileDelete, FileMove #include <FileConstants.au3> copy. If Not FileWrite($sFilePath, "This is an example of using FileCopy.") Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred whilst writing the temporary file.") Return False EndIf ; Copy Au3 files in the temporary directory to a new folder/directory called Au3Files. FileCopy(@TempDir & "\*.au3", @TempDir & "\Au3Files\", $FC_OVERWRITE + $FC_CREATEPATH) ; Display the temporary directory. ShellExecute(@TempDir) EndFunc ;==>Example
https://www.autoitscript.com/autoit3/docs/functions/FileCopy.htm
CC-MAIN-2018-43
refinedweb
145
50.33
I have been trying to figure out a substring method like Python's splice, e.g. 'hello'[2:4]. OLD: The pointers new toret hello #include <stdio.h> #include <stdlib.h> #include <string.h> //char * substr(char *str, int start, int end); //void substr(char *str, int start, int end); void get_substr(char *str, int start, int end, char *buffer); int main() { char word[] = "Clayton"; char buffer[15]; printf("buffer is now %s",get_substr(word,2,5,buffer); return 0; } void get_substr(char *str, int start, int end, char *buffer) { int length = end - start; printf("length %d\n",length); //char buffer[length]; //init normal array //assign values from *str int i; for (i = 0; i < length; i++) { buffer[i] = *(str+i+start); } } //char * substr(char *str, int start, int end) { /* char * substr(char *str, int start, int end) { int length = end - start; printf("length %d\n",length); char buffer[length]; //init normal array //assign values from *str int i; for (i = 0; i < length; i++) { buffer[i] = *(str+i+start); printf("i=%d buffer[i]=%c ptr=%c\n",i,buffer[i],*(str+i+start)); } //add endline if not present if (buffer[length] != '\0') { buffer[length] = '\0'; printf("buffer[%d] is %c\n",length,buffer[length]); printf("0 added\n"); } printf("buffer %s %p\n",buffer,buffer); printf("len(buffer) is %d\n",strlen(buffer)); char *toret; toret = (char*) &buffer; printf("toret %s %p\n",toret,toret); return toret; } */ You can't return a pointer to a buffer that is declared locally within the function. That memory resides on the stack, and the next function call will likely overwrite that memory. You would need to use malloc to create the memory you need if you are going to return it to the calling function, which then needs to be cleaned up with free, once you are done with it. That being said, it's usually not wise to allocate the memory in the called function and return it. In order to prevent the caller from forgetting to clean up the memory, I would recommend requesting a buffer into which the substring will be copied. I would change the function signature to return a void, and take an additional buffer into which the substring will be copied: void get_substr(char *str, int start, int end, char *buffer) Then, in your calling function, you can do this: int main() { char name[] = "Clayton"; char buffer[10]; get_substr(name, 0, 3, buffer); /* "Cla" now copied into buffer */ printf("%s", buffer); return 0; } Alternatively, since this is a substring function, and you know that the string is completely contained within the original string, you could return the size of the string's length and a pointer to the start of the string (within the original string). Your signature could look like this: int substr(char *str, int start, int end, char *substr) And usage could look like this: int main() { char name[] = "Clayton"; char *substr; int substr_len = substr(name, 0, 3, substr); /* substr now points to name, substr_len = 3 */ /* Copy substring to buffer to print */ char buffer[10]; strncpy(buffer, substr, substr_len); printf("%s", buffer); return 0; }
https://codedump.io/share/DP6gKfYN9THg/1/slicing-in-c-compared-with-python
CC-MAIN-2017-26
refinedweb
522
51.04
Hi, I ap posting my Assignment subject here, and hope to get some helps with each Classes, I am not asking that you do all my home works but to give me hints as I want to learn something and as I am new to Java I am block some times. this is the Subject The program allows customers to list the videos available and to borrow them (ignore returning videos). It records whether a video is on the shelf or on loan, and if it is on loan, the date it is due to be returned. Customers can borrow up to two videos for 3 days. Build the program according to the following recipe: There should be classes describing customers and videos and also a class called VideoStore that contains ArrayLists of customers and videos. There should also be a small public class VideoTest that contains the main() method. The Video class has instance fields for the video title, whether it is on loan and the date it is due to be returned. There are get and set methods for some of these fields and a toString() method. The Customer class has instance fields for the customer name and for the number of videos he is borrowing. A method borrowvideo(Video v) checks that the video is available and that the customer is not borrowing more than 2 videos, it then sets the duedate and onloan fields in the Video class. The due date is printed on screen. There is a get method for the customer name. The constructor for the VideoStore class initialises a small number (less than 10) of Customer and Video objects and stores them in two separate ArrayLists that are the instance fields for the class. It provides a method (listallvideos()) for listing all the videos in the store and a method called borrow(String,String) described below. The main method in VideoTest creates a VideoStore, then enters a loop that implements a menu: "Menu: L-List, B-Borrow, Q-Quit". A Scanner picks up the letter entered and causes the desired response. List, lists the titles of all the videos along with whether they are on the shelf or the due date if they are on loan. Quit, drops out of the loop and exits the application. Borrow, asks first the Customer's name, and then the title of the video he wishes to borrow and picks up responses with a Scanner. These are then passed to the VideoStore borrow method as borrow(name,title). The VideoStore borrow method checks that the name and title match entries in the VideoStore arrays, and identifies the Customer and Video objects they correspond to. The Customer borrowvideo(Video v) method can then be called. this is my VideoTest Class /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package assignement; import java.util.*; /** * * @author Harris */ public class VideotTest { public static void main(String[] args) { VideoStore vs = new VideoStore(); Scanner sc = new Scanner(System.in); String menuResponse; do { System.out.println("Menu: L-list, B-borrow, Q-quit"); menuResponse = sc.nextLine(); if(menuResponse.equals("L")) vs.listallvideos(); else if (menuResponse.equals("B")) { System.out.println("What is your name?"); String nameResponse = sc.nextLine(); System.out.println("What is the title of the video you want to borrow?"); String videoResponse = sc.nextLine(); // vs.borrow(nameResponse,videoResponse); } } while(!menuResponse.equalsIgnoreCase("Q")); } } ***************************************************** this is my VideoStore Class ***************************************************** /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package assignement; import java.util.*; /** * * @author Harris */ public class VideoStore { private String VideoName; private String CustomersName; private ArrayList<String> Videos = new ArrayList<String>(); private ArrayList<String> CustomersListe = new ArrayList<String>(); public VideoStore(){ VideoName = null; CustomersName = null; } public VideoStore(String VidName, String CustName){ VideoName = VidName; CustName = CustomersName; Videos.add("Brave Heart"); Videos.add("Troy"); Videos.add("Shakspear In Love"); Videos.add("Green Mile"); Videos.add("Ice Age"); CustomersListe.add("Harris"); CustomersListe.add("John"); CustomersListe.add("Ricky"); CustomersListe.add("Mike"); CustomersListe.add("Robin"); } public String getVideoName(){ return VideoName; } public String getCustomersName(){ return CustomersName; } public void listallvideos(){ for (int i = 0; i < Videos.size(); i++) System.out.println(Videos.get(i)); } } *********************************************** the problem which I get is when I run VideoTest which is my main class by chosing L it dosnt not list my Videos list which is an Array list it goes back to the menu. Anyone Can Help? Thanks
https://www.daniweb.com/programming/software-development/threads/236790/help-with-assignment
CC-MAIN-2017-09
refinedweb
733
72.87
Data binding is a process by which data can be displayed to user as well as data can be entered into the application using various elements. Data binding provides a method to bind UI elements with the data objects and it makes data flow between Binding source and UI elements. Binding UI elements to data Data binding establishes a connection between the data source and the elements on the UI of an app. In this process following terms are commonly used: Binding target: It is a UI component that is bound to a data item. For example TextBox and Image controls can be used as binding targets. Target property It is the property of UI component that needs to be bound to a data item. It is also termed as dependency property. For example the Text property of TextBox can be target property that is used to display the title of a note in an app. Binding source: Binding source is a data item. For example we can bind the Text property of the TextBox that accepts any information like Title of Note class. Data binding Types Based on the direction of data flow between UI elements and data items, data binding can be of following types: One way In this type of data binding, the binding target is updated at the time of binding and whenever the source gets updated. It is useful where data is presented in read only form but it needs to be updated regularly on user interface. For eg in Weather app the temperature is displayed in read only mode but it is updated at regular intervals. One Time In this type of data binding, the binding target is updated with the data from the binding source only at the time of creation of binding. If there are any changes in data source after the data binding, it will not be reflected in the binding target. For example if we are using an app where we have to display month of year in a drop down list. We can use this type of binding. Two Way In this type of data binding, the binding target and the binding source can reflect changes to each other. That means data can be flow between data source and UI elements and vice-versa. At the time of implementation data binding we can bind either a single data item to a UI element or multiple data items to a single UI element. Binding a UI element to Single item To bind a UI element to a single data item, we bind a property of UI element to single data item. For this we need to perform following steps: Define the data source To define the data source of app, we need to create a class whose instance will be used to store the values provided on interface. For eg if we are creating a note app then we can use following code to define a class. class Note { public string Title {get; set;} public string Content{get; set;} public Note(string Title, string Content) { this.Title=Title; this.Content=Content; } } Set the data context of UI element After the data source is defined, we set this data source as the data context of the UI element. In note app we bind the values stored in an object of the Note class to the text blocks on UI app. For this we set the data context of text blocks. We need to set the value of DataContext property of text blocks as an object of the Note class. For this we can use following code: txtNoteTitle.DataContext=note; txtNoteContent.DataContext=note; Bind the property of UI element with the appropriate property of data source. After above two steps we need to bind the property of UI element with the corresponding property of data source. In note app to display the title of a note, we bind the Title property of the Note object, note. We can use following code for this: <TextBlock x:Name=”txtNoteTitle” Text=”{Binding Title}”/> <TextBlock x:Name=”txtNoteContent” Text=”{Binding Content}”/> Binding UI element to a collection of items: To bind a UI element to a collection of items, we need to follow following steps: Create a collection If we need to create a collection of objects that is used to store details, we create an instance of the ObservableCollection class, that is available under the System.Collections.ObjectModel namespace. It is basically a generic class that is a collection of dynamic data and is capable of providing notifications at the time of adding or removing contents. Following code explains it: In this code: In Notes app, if we need to create a collection of objects that stores the note details. We use Following code : Add the data source objects to the collection After creating the collection, we need to add data source objects that store the data entered on the UI to the collection. For this we use following code: Bind the collection as data source of the UI element After adding data source objects to the collection, we need to bind the collection as the data source of the UI element. For this we need to set the ItemsSource property of UI element. Override ToString() method To display the data from a collection in a UI element, we need to override the ToString() method.
https://wideskills.com/windows-mobile-app-dev/implementing-data-binding-in-windows-store-app
CC-MAIN-2022-27
refinedweb
900
57
Various ways to write a file Persistence vs Permanent storage In programming, persistence storage refers to a storage area which may forget the data/information once it looses the electronic energy supply. such as RAM – Random Access Memory. When we run an application having some variables, methods, objects, etc. That data is stored in Computer RAM. Problem with this system is when we want to share some information between two execution cycle that won’t be possible. For Example: We have developed a “Student Management System” for a college and one operator starts entering student records in our software. If we as a developer has written code which stores student information in an Array, in that case a power failure/system crash/software termination/software closing may lead to information lost and operator need to start entering details from the scratch! Here the conclusion is: We cannot not store the important or permanent data in RAM. We must choose either 1) File 2) Database. In this tutorial we gonna learn about writing a file. so that the same/other application can read the data which we have written in future. By this way our application will also be in a consistent state. Following are the various ways to write a file in any storage device like hard disk, floppy, pen drive, etc. The basic need to use a storage device is to mount the same and you are ready to go! FileOutputStream FileOutputStream is derived from OutputStream class. import java.io.*; class FileOutputStreamDemo { public static void main(String[] s)throws IOException { byte[] b; String str = "I want to write some text to file."; b = str.getBytes(); File f = new File("data.txt"); // this will points to the data.txt of the same directory where your program is stored. FileOutputStream fos = new FileOutputStream(f); fos.write(b); fos.flush(); System.out.println("File Created!"); fos.close(); } } FileWriter import java.io.*; class File); fw.write(str); fw.flush(); System.out.println("File Created!"); fw.close(); } } BufferedWriter + FileWriter import java.io.*; class FileBuffered); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.flush(); System.out.println("File Created!"); bw.close(); } } FilterWriter FilterWriter is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. For more details visit: FilterWriter Aim Write a program which defines a IOException { // TODO code application logic here File f = new File("data.txt"); FileWriter fw = new FileWriter(f); FilterWriter mfw = new FilterWriter(fw){ @Override public void write(String str) throws IOException { int len = str.length(); String output = ""; if(len>15) { output = str.substring(0,5); output += "... "; output += str.substring(len-5,len); } super.write(output); }}; mfw.write("This is demo by Ankit"); mfw.flush(); mfw.close(); } } DataOputputStream import java.io.*; class DataOutputStreamDemo { public static void main(String[] s)throws Exception { FileOutputStream fos = new FileOutputStream(new File("db.txt")); DataOutputStream dos = new DataOutputStream(fos); dos.writeBytes("This is Test\n\n"); dos.writeDouble(1232.23); dos.writeInt(123); dos.flush(); dos.close(); System.out.println("File Written"); } } ObjectOputputStream import java.io.*; import java.util.*; class ObjectOutputStreamDemo { public static void main(String[] s)throws Exception { FileOutputStream fos = new FileOutputStream("test.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeInt(12345); oos.writeObject("Today"); oos.writeObject(new Date()); oos.flush(); oos.close(); System.out.println("Objects written!"); } } Recent Comments
http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file
CC-MAIN-2021-31
refinedweb
558
50.73
With the new release of Dart 2 we've updated the servicestack Dart packages to support Dart 2+. As this is a breaking change we've changed the major version number of servicestack Dart package to 1.0.5 which can be referenced with: 1.0.5 dependencies: servicestack: ^1.0.5 Where all non-Web (i.e. Flutter, Dart VM, Server and command-line tests) continue to use the same import and JsonServiceClient, i.e: JsonServiceClient import 'package:servicestack/client.dart'; var client = new JsonServiceClient(BaseUrl); Whilst Dart Web and Angular Dart projects instead use: import 'package:servicestack/web_client.dart'; var client = new JsonWebClient(BaseUrl); Both the HelloFlutter and HelloAngularDart example projects (and published docs) have been updated to use Dart 2+ and the latest servicestack Dart packages. Please refer to the Dart 2 migration guides for how to upgrade your Dart 1.x projects to Dart 2.x. At a minimum it requires changing the sdk restriction in your pubspec.yaml to: sdk pubspec.yaml sdk: '>=2.0.0-dev.61.0 <3.0.0' Normally all changes would be published in the next release notes but the next release is dependent on a new release of VS.NET as it contains support for Xamarin projects being able to the latest ServiceStack.Text which has been modified to use .NET's new efficient Span<T> types from the System.Memory NuGet package. Span<T> I'm on the flutter beta channel and it is running dev.58:The current Dart SDK version is 2.0.0-dev.58.0.flutter-f981f09760. and thus the servicestack 1.x release is a non-starter for now. The sdk: '>=2.0.0-dev.61.0 <3.0.0' was based on the Dart 2 migration guide for requiring Dart 2. The HelloFlutter project works with that constraint although I'm on the master channel which returns: master Dart VM version: 2.0.0 (Fri Aug 3 10:53:23 2018 +0200) on "windows_x64" Hopefully they'll release an update on the other channels soon.
https://forums.servicestack.net/t/servicestack-dart-packages-updated/6176
CC-MAIN-2018-43
refinedweb
343
69.38
system - issue a command #include <stdlib.h> int system(const char *command); command is a null pointer, the system() function shall determine whether the host environment has a command processor. If command is not a null pointer, the system() function shall pass the string pointed to by command to that command processor to be executed in an implementation-defined manner; this might then cause the program calling system() to behave in a non-conforming manner or to terminate. [CX] The environment of the executed command shall be as if a child process were created using fork(), and the child process invoked the sh utility using execl() as follows:The environment of the executed command shall be as if a child process were created using fork(), and the child process invoked the sh utility using execl() as follows:execl(<shell path>, "sh", "-c", command, (char *)0); where <shell path> is an unspecified pathname for the sh utility.. The system() function shall not affect the termination status of any child of the calling processes other than the process or processes it itself creates. The system() function shall not return until the child process has terminated. If command is a null pointer, system() shall return non-zero to indicate that a command processor is available, or zero if none is available. [CX] The system() function shall always return non-zero when command is NULL.The system() function shall always return non-zero when command is NULL. [CX]. [CX] The system() function may set errno values as described by fork().The system() function may set errno values as described by fork(). In addition, system() may fail if: - [ECHILD] - [CX] The status of the child process created by system() is no longer available.The status of the child process created by system() is no longer available. None. If the return value of system() is not -1, its value can be decoded through the use of the macros described in <sys/wait.h>. For convenience, these macros are also provided in <stdlib.h>. Note that, while system() must ignore SIGINT and SIGQUIT and block SIGCHLD while waiting for the child to terminate, the handling of signals in the executed command is as specified by fork() and exec. For example, if SIGINT is being caught or is set to SIG_DFL when system() is called, then the child is started with SIGINT handling set to SIG_DFL. Ignoring SIGINT and SIGQUIT in the parent process prevents coordination problems (two processes reading from the same terminal, for example) when the executed command ignores or catches one of the signals. It is also usually the correct action when the user has given a command to the application to be executed synchronously (as in the '!' command in many interactive applications). In either case, the signal should be delivered only to the child process, not to the application itself. There is one situation where ignoring the signals might have less than the desired effect. This is when the application uses system() to perform some task invisible to the user. If the user typed the interrupt character ( "^C", for example) while system() is being used in this way, one would expect the application to be killed, but only the executed command is killed. Applications that use system() in this way should carefully check the return status from system() to see if the executed command was successful, and should take appropriate action when the command fails. Blocking SIGCHLD while waiting for the child to terminate prevents the application from catching the signal and obtaining status from system()'s child process before system() can get the status itself. The context in which the utility is ultimately executed may differ from that in which system() was called. For example, file descriptors that have the FD_CLOEXEC flag set are closed, and the process ID and parent process ID are different. Also, if the executed utility changes its environment variables or its current working directory, that change is not reflected in the caller's context. There is no defined way for an application to find the specific path for the shell. However, confstr() can provide a value for PATH that is guaranteed to find the sh utility. The system(). There are three levels of specification for the system() function. The ISO C standard gives the most basic. It requires that the function exists, and defines a way for an application to query whether a command language interpreter exists. It says nothing about the command language or the environment in which the command is interpreted. IEEE Std 1003.1-2001 places additional restrictions on system(). It requires that if there is a command language interpreter, the environment must be as specified by fork() and exec. This ensures, for example, that close-on- exec works, that file locks are not inherited, and that the process ID is different. It also specifies the return value from system() when the command line can be run, thus giving the application some information about the command's completion status. Finally, IEEE Std 1003.1-2001 requires the command to be interpreted as in the shell command language defined in the Shell and Utilities volume of IEEE Std 1003.1-2001. Note that, system(NULL) is required to return non-zero, indicating that there is a command language interpreter. At first glance, this would seem to conflict with the ISO C standard which allows system(NULL) to return zero. There is no conflict, however. A system must have a command language interpreter, and is non-conforming if none is present. It is therefore permissible for the system() function on such a system to implement the behavior specified by the ISO C standard as long as it is understood that the implementation does not conform to IEEE Std 1003.1-2001 if system(NULL) returns zero. It was explicitly decided that when command is NULL, system() should not be required to check to make sure that the command language interpreter actually exists with the correct mode, that there are enough processes to execute it, and so on. The call system(NULL) could, theoretically, check for such problems as too many existing child processes, and return zero. However, it would be inappropriate to return zero due to such a (presumably) transient condition. If some condition exists that is not under the control of this application and that would cause any system() call to fail, that system has been rendered non-conforming. Early drafts required, or allowed, system() to return with errno set to [EINTR] if it was interrupted with a signal. This error return was removed, and a requirement that system() not return until the child has terminated was added. This means that if a waitpid() call in system() exits with errno set to [EINTR], system() must reissue the waitpid(). This change was made for two reasons: - There is no way for an application to clean up if system() returns [EINTR], short of calling wait(), and that could have the undesirable effect of returning the status of children other than the one started by system(). - While it might require a change in some historical implementations, those implementations already have to be changed because they use wait() instead of waitpid(). Note that if the application is catching SIGCHLD signals, it will receive such a signal before a successful system() call returns. To conform to IEEE Std 1003.1-2001, system() must use waitpid(), or some similar function, instead of wait(). The following code sample illustrates how system() might be implemented on an implementation conforming to IEEE Std 1003.1-2001.#include <signal.h> int system(const char *cmd) { int stat; pid_t pid; struct sigaction sa, savintr, savequit; sigset_t saveblock; if (cmd == NULL) return(1); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigemptyset(&savintr.sa_mask); sigemptyset(&savequit.sa_mask); sigaction(SIGINT, &sa, &savintr); sigaction(SIGQUIT, &sa, &savequit); sigaddset(&sa.sa_mask, SIGCHLD); sigprocmask(SIG_BLOCK, &sa.sa_mask, &saveblock); if ((pid = fork()) == 0) { sigaction(SIGINT, &savintr, (struct sigaction *)0); sigaction(SIGQUIT, &savequit, (struct sigaction *)0); sigprocmask(SIG_SETMASK, &saveblock, (sigset_t *)0); execl("/bin/sh", "sh", "-c", cmd, (char *)0); _exit(127); } if (pid == -1) { stat = -1; /* errno comes from fork() */ } else { while (waitpid(pid, &stat, 0) == -1) { if (errno != EINTR){ stat = -1; break; } } } sigaction(SIGINT, &savintr, (struct sigaction *)0); sigaction(SIGQUIT, &savequit, (struct sigaction *)0); sigprocmask(SIG_SETMASK, &saveblock, (sigset_t *)0); return(stat); } Note that, while a particular implementation of system() (such as the one above) can assume a particular path for the shell, such a path is not necessarily valid on another system. The above example is not portable, and is not intended to be. One reviewer suggested that an implementation of system() might want to use an environment variable such as SHELL to determine which command interpreter to use. The supposed implementation would use the default command interpreter if the one specified by the environment variable was not available. This would allow a user, when using an application that prompts for command lines to be processed using system(), to specify a different command interpreter. Such an implementation is discouraged. If the alternate command interpreter did not follow the command line syntax specified in the Shell and Utilities volume of IEEE Std 1003.1-2001, then changing SHELL would render system() non-conforming. This would affect applications that expected the specified behavior from system(), and since the Shell and Utilities volume of IEEE Std 1003.1-2001 does not mention that SHELL affects system(), the application would not know that it needed to unset SHELL . None. exec(), pipe(), waitpid(), the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <signal.h>, <stdlib.h>, <sys/wait.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, sh First released in Issue 1. Derived from Issue 1 of the SVID. Extensions beyond the ISO C standard are marked.
http://www.opengroup.org/onlinepubs/000095399/functions/system.html
crawl-002
refinedweb
1,637
52.19
While many developers recognize Python as an effective programming language, pure Python programs may run slower than their counterparts in compiled languages like C, Rust, and Java. Throughout this tutorial, you’ll see how to use a Python timer to monitor how fast your programs are running. In this tutorial, you’ll learn how to use: time.perf_counter()to measure time in Python - Classes to keep state - Context managers to work with a block of code - Decorators to customize a function You’ll also gain background knowledge into how classes, context managers, and decorators work. As you see examples of each concept, you’ll be inspired to use one or several of them in your code, both for timing code execution and other applications. Each method has its advantages, and you’ll learn which to use depending on the situation. Plus, you’ll have a working Python timer that you can use to monitor your programs! Decorators Q&A Transcript: Click here to get access to a 25-page chat log from our recent Python decorators Q&A session in the Real Python Community Slack where we discussed common decorator questions. Python Timers First, you’ll take a look at some example code that you’ll use throughout the tutorial. Later, you’ll add a Python timer to this code to monitor its performance. You’ll also see some of the simplest ways to measure the running time of this example. Python Timer Functions If you look at the built in time module in Python, then you’ll notice several functions that can measure time: Python 3.7 introduced several new functions, like thread_time(), as well as nanosecond versions of all the functions above, named with an _ns suffix. For example, perf_counter_ns() is the nanosecond version of perf_counter(). You’ll learn more about these functions later. For now, note what the documentation has to say about perf_counter(): Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. (Source) First, you’ll use perf_counter() to create a Python timer. Later, you’ll compare this with other Python timer functions and learn why perf_counter() is usually the best choice. Example: Download Tutorials To better compare the different ways you can add a Python timer to your code, you’ll apply different Python timer functions to the same code example throughout this tutorial. If you already have code you’d like to measure, then feel free to follow the examples with that instead. The example you’ll see in this tutorial is a short function that uses the realpython-reader package to download the latest tutorials available here on Real Python. To learn more about the Real Python Reader and how it works, check out How to Publish an Open-Source Python Package to PyPI. You can install realpython-reader on your system with pip: $ python -m pip install realpython-reader Then, you can import the package as reader. You’ll store the example in a file named latest_tutorial.py. The code consists of one function that downloads and prints the latest tutorial from Real Python: 1# latest_tutorial.py 2 3from reader import feed 4 5def main(): 6 """Download and print the latest tutorial from Real Python""" 7 tutorial = feed.get_article(0) 8 print(tutorial) 9 10if __name__ == "__main__": 11 main() realpython-reader handles most of the hard work: - Line 3 imports feedfrom realpython-reader. This module contains functionality for downloading tutorials from the Real Python feed. - Line 7 downloads the latest tutorial from Real Python. The number 0is an offset, where 0means the most recent tutorial, 1is the previous tutorial, and so on. - Line 8 prints the tutorial to the console. - Line 11 calls main()when you run the script. When you run this example, your output will typically look something like this: $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run slower than their counterparts in compiled languages like C, Rust, and Java. Throughout this tutorial, you’ll see how to use a Python timer to monitor how fast your programs are running. [ ... The full text of the tutorial ... ] The code may take a little while to run depending on the network, so you might want to use a Python timer to monitor the performance of the script. Your First Python Timer Let’s add a bare-bones Python timer to the example with time.perf_counter(). Again, this is a performance counter that’s well-suited for timing parts of your code. perf_counter() measures the time in seconds from some unspecified moment in time, which means that the return value of a single call to the function isn’t useful. However, when you look at the difference between two calls to perf_counter(), you can figure out how many seconds passed between the two calls: >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 In this example, you made two calls to perf_counter() almost 4 seconds apart. You can confirm this by calculating the difference between the two outputs: 32315.26 - 32311.49 = 3.77. You can now add a Python timer to the example code: 1# latest_tutorial.py 2 3import time 4from reader import feed 5 6def main(): 7 """Print the latest tutorial from Real Python""" 8 tic = time.perf_counter() 9 tutorial = feed.get_article(0) 10 toc = time.perf_counter() 11 print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds") 12 13 print(tutorial) 14 15if __name__ == "__main__": 16 main() Note that you call perf_counter() both before and after downloading the tutorial. You then print the time it took to download the tutorial by calculating the difference between the two calls. Note: In line 11, the f before the string indicates that this is an f-string, which is a convenient way to format a text string. :0.4f is a format specifier that says the number, toc - tic, should be printed as a decimal number with four decimals. f-strings are only available in Python 3.6 and later. For more information, check out Python 3’s f-Strings: An Improved String Formatting Syntax. Now, when you run the example, you’ll see the elapsed time before the tutorial: $ python latest_tutorial.py Downloaded the tutorial in 0.67 seconds # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] That’s it! You’ve covered the basics of timing your own Python code. In the rest of the tutorial, you’ll learn how you can wrap a Python timer into a class, a context manager, and a decorator to make it more consistent and convenient to use. A Python Timer Class Look back at how you added the Python timer to the example above. Note that you need at least one variable ( tic) to store the state of the Python timer before you download the tutorial. After staring at the code a little, you might also note that the three highlighted lines are added only for timing purposes! Now, you’ll create a class that does the same as your manual calls to perf_counter(), but in a more readable and consistent manner. Throughout this tutorial, you’ll create and update Timer, a class that you can use to time your code in several different ways. The final code is also available on PyPI under the name codetiming. You can install this to your system like so: $ python -m pip install codetiming You can find more information about codetiming later on in this tutorial, in the section named The Python Timer Code. Understanding Classes in Python Classes are the main building blocks of object-oriented programming. A class is essentially a template that you can use to create objects. While Python doesn’t force you to program in an object-oriented manner, classes are everywhere in the language. For a quick proof, let’s investigate the time module: >>> import time >>> type(time) <class 'module'> >>> time.__class__ <class 'module'> type() returns the type of an object. Here you can see that modules are in fact objects created from a module class. The special attribute .__class__ can be used to get access to the class that defines an object. In fact, almost everything in Python is a class: >>> type(3) <class 'int'> >>> type(None) <class 'NoneType'> >>> type(print) <class 'builtin_function_or_method'> >>> type(type) <class 'type'> In Python, classes are great when you need to model something that needs to keep track of a particular state. In general, a class is a collection of properties (called attributes) and behaviors (called methods). For more background on classes and object-oriented programming, check out Object-Oriented Programming (OOP) in Python 3 or the official docs. Creating a Python Timer Class Classes are good for tracking state. In a Timer class, you want to keep track of when a timer starts and how much time has passed since then. For the first implementation of Timer, you’ll add a ._start_time attribute, as well as .start() and .stop() methods. Add the following code to a file named timer.py: 1# timer.py 2 3import time 4 5class TimerError(Exception): 6 """A custom exception used to report errors in use of Timer class""" 7 8class Timer: 9 def __init__(self): 10 self._start_time = None 11 12 def start(self): 13 """Start a new timer""" 14 if self._start_time is not None: 15 raise TimerError(f"Timer is running. Use .stop() to stop it") 16 17 self._start_time = time.perf_counter() 18 19 def stop(self): 20 """Stop the timer, and report the elapsed time""" 21 if self._start_time is None: 22 raise TimerError(f"Timer is not running. Use .start() to start it") 23 24 elapsed_time = time.perf_counter() - self._start_time 25 self._start_time = None 26 print(f"Elapsed time: {elapsed_time:0.4f} seconds") A few different things are happening here, so let’s walk through the code step by step. In line 5, you define a TimerError class. The (Exception) notation means that TimerError inherits from another class called Exception. Python uses this built-in class for error handling. You don’t need to add any attributes or methods to TimerError. However, having a custom error will give you more flexibility to handle problems inside Timer. For more information, check out Python Exceptions: An Introduction. The definition of Timer itself starts on line 8. When you first create or instantiate an object from a class, your code calls the special method .__init__(). In this first version of Timer, you only initialize the ._start_time attribute, which you’ll use to track the state of your Python timer. It has the value None when the timer isn’t running. Once the timer is running, ._start_time keeps track of when the timer started. Note: The underscore prefix of ._start_time is a Python convention. It signals that ._start_time is an internal attribute that should not be manipulated by users of the Timer class. When you call .start() to start a new Python timer, you first check that the timer isn’t already running. Then you store the current value of perf_counter() in ._start_time. On the other hand, when you call .stop(), you first check that the Python timer is running. If it is, then you calculate the elapsed time as the difference between the current value of perf_counter() and the one you stored in ._start_time. Finally, you reset ._start_time so that the timer can be restarted, and print the elapsed time. Here’s how you use Timer: >>> from timer import Timer >>> t = Timer() >>> t.start() >>> t.stop() # A few seconds later Elapsed time: 3.8191 seconds Compare this to the earlier example where you used perf_counter() directly. The structure of the code is fairly similar, but now the code is more clear, and this is one of the benefits of using classes. By carefully choosing your class, method, and attribute names, you can make your code very descriptive! Using the Python Timer Class Let’s apply Timer to latest_tutorial.py. You only need to make a few changes to your previous code: # latest_tutorial.py from timer import Timer from reader import feed def main(): """Print the latest tutorial from Real Python""" t = Timer() t.start() tutorial = feed.get_article(0) t.stop() print(tutorial) if __name__ == "__main__": main() Notice that the code is very similar to what you saw earlier. In addition to making the code more readable, Timer takes care of printing the elapsed time to the console, which makes the logging of time spent more consistent. When you run the code, you’ll see pretty much the same output: $ python latest_tutorial.py Elapsed time: 0.64 seconds # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] Printing the elapsed time from Timer may be consistent, but it seems that this approach is not very flexible. In the next section, you’ll see how to customize your class. Adding More Convenience and Flexibility So far, you’ve seen that classes are suitable for when you want to encapsulate state and ensure consistent behavior in your code. In this section, you’ll add more convenience and flexibility to your Python timer: - Use adaptable text and formatting when reporting the time spent - Apply flexible logging, either to the screen, to a log file, or other parts of your program - Create a Python timer that can accumulate over several invocations - Build an informative representation of a Python timer First, let’s see how you can customize the text used to report the time spent. In the previous code, the text f"Elapsed time: {elapsed_time:0.4f} seconds" is hard-coded into .stop(). You can add flexibility to classes using instance variables. Their values are normally passed as arguments to .__init__() and stored as self attributes. For convenience, you can also provide reasonable default values. To add .text as a Timer instance variable, you’ll do something like this: def __init__(self, text="Elapsed time: {:0.4f} seconds"): self._start_time = None self.text = text Note that the default text, "Elapsed time: {:0.4f} seconds", is given as a regular string, not as an f-string. You can’t use an f-string here because they evaluate immediately, and when you instantiate Timer, your code has not yet calculated the elapsed time. Note: If you want to use an f-string to specify .text, then you need to use double curly braces to escape the curly braces that the actual elapsed time will replace. One example would be f"Finished {task} in {{:0.4f}} seconds". If the value of task is "reading", then this f-string would be evaluated as "Finished reading in {:0.4f} seconds". In .stop(), you use .text as a template and .format() to populate the template: def stop(self): """Stop the timer, and report the elapsed time""" if self._start_time is None: raise TimerError(f"Timer is not running. Use .start() to start it") elapsed_time = time.perf_counter() - self._start_time self._start_time = None print(self.text.format(elapsed_time)) After this update to timer.py, you can change the text as follows: >>> from timer import Timer >>> t = Timer(text="You waited {:.1f} seconds") >>> t.start() >>> t.stop() # A few seconds later You waited 4.1 seconds Next, assume that you don’t just want to print a message to the console. Maybe you want to save your time measurements so you can store them in a database. You can do this by returning the value of elapsed_time from .stop(). Then, the calling code can choose to either ignore that return value or save it for later processing. Perhaps you want to integrate Timer into your logging routines. To support logging or other outputs from Timer you need to change the call to print() so that the user can supply their own logging function. This can be done similar to how you customized the text earlier: def __init__(self, text="Elapsed time: {:0.4f} seconds", logger=print): self._start_time = None self.text = text self.logger = logger)) return elapsed_time Instead of using print() directly, you create another instance variable, self.logger, that should refer to a function that takes a string as an argument. In addition to print(), you can use functions like logging.info() or .write() on file objects. Also note the if test, which allows you to turn off printing completely by passing logger=None. Here are two examples that show the new functionality in action: >>> from timer import Timer >>> import logging >>> t = Timer(logger=logging.warning) >>> t.start() >>> t.stop() # A few seconds later WARNING:root:Elapsed time: 3.1610 seconds 3.1609658249999484 >>> t = Timer(logger=None) >>> t.start() >>> value = t.stop() # A few seconds later >>> value 4.710851433001153 When you run these examples in an interactive shell, Python prints the return value automatically. The third improvement you’ll add is the ability to accumulate time measurements. You may want to do this, for instance, when you’re calling a slow function in a loop. You’ll add a bit more functionality in the form of named timers with a dictionary that keeps track of every Python timer in your code. Assume that you’re expanding latest_tutorial.py to a latest_tutorials.py script that downloads and prints the ten latest tutorials from Real Python. The following is one possible implementation: # latest_tutorials.py from timer import Timer from reader import feed def main(): """Print the 10 latest tutorials from Real Python""" t = Timer(text="Downloaded 10 tutorials in {:0.2f} seconds") t.start() for tutorial_num in range(10): tutorial = feed.get_article(tutorial_num) print(tutorial) t.stop() if __name__ == "__main__": main() The code loops over the numbers from 0 to 9 and uses those as offset arguments to feed.get_article(). When you run the script, you’ll see a lot of information printed to your console: $ python latest_tutorials.py # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of ten tutorials ... ] Downloaded 10 tutorials in 0.67 seconds One subtle issue with this code is that you’re not only measuring the time it takes to download the tutorials, but also the time Python spends printing the tutorials to your screen. This might not be that important since the time spent printing should be negligible compared to the time spent downloading. Still, it would be good to have a way to precisely time what you’re after in these kinds of situations. Note: The time spent downloading ten tutorials is about the same as the time spent downloading one tutorial. This is not a bug in your code! Instead, reader caches the Real Python feed the first time get_article() is called, and reuses the information on later invocations. There are several ways you can work around this without changing the current implementation of Timer. However, supporting this use case will be quite useful, and can be done with just a few lines of code. First, you’ll introduce a dictionary called .timers as a class variable on Timer, which means that all instances of Timer will share it. You implement it by defining it outside any methods: class Timer: timers = dict() Class variables can be accessed either directly on the class, or through an instance of the class: >>> from timer import Timer >>> Timer.timers {} >>> t = Timer() >>> t.timers {} >>> Timer.timers is t.timers True In both cases, the code returns the same empty class dictionary. Next, you’ll add optional names to your Python timer. You can use the name for two different purposes: - Looking up the elapsed time later in your code - Accumulating timers with the same name To add names to your Python timer, you need to make two more changes to timer.py. First, Timer should accept the name as a parameter. Second, the elapsed time should be added to .timers when a timer stops: class Timer: timers = dict() def __init__( self, name=None, text="Elapsed time: {:0.4f} seconds", logger=print, ): self._start_time = None self.name = name self.text = text self.logger = logger # Add new named timers to dictionary of timers if name: self.timers.setdefault(name, 0) # Other methods are unchanged)) if self.name: self.timers[self.name] += elapsed_time return elapsed_time Note that you use .setdefault() when adding the new Python timer to .timers. This is a great feature that only sets the value if name is not already defined in the dictionary. If name is already used in .timers, then the value is left untouched. This allows you to accumulate several timers: >>> from timer import Timer >>> t = Timer("accumulate") >>> t.start() >>> t.stop() # A few seconds later Elapsed time: 3.7036 seconds 3.703554293999332 >>> t.start() >>> t.stop() # A few seconds later Elapsed time: 2.3449 seconds 2.3448921170001995 >>> Timer.timers {'accumulate': 6.0484464109995315} You can now revisit latest_tutorials.py and make sure only the time spent on downloading the tutorials is measured: # latest_tutorials.py from timer import Timer from reader import feed def main(): """Print the 10 latest tutorials from Real Python""" t = Timer("download", logger=None) for tutorial_num in range(10): t.start() tutorial = feed.get_article(tutorial_num) t.stop() print(tutorial) download_time = Timer.timers["download"] print(f"Downloaded 10 tutorials in {download_time:0.2f} seconds") if __name__ == "__main__": main() Rerunning the script will give similar output as earlier, although now you are only timing the actual download of the tutorials: $ python latest_tutorials.py # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of ten tutorials ... ] Downloaded 10 tutorials in 0.65 seconds The final improvement that you’ll make to Timer is to make it more informative when you’re working with it interactively. Try the following: >>> from timer import Timer >>> t = Timer() >>> t <timer.Timer object at 0x7f0578804320> That last line is the default way Python represents objects. While you can glean some information from it, it’s usually not very useful. Instead, it would be nice to see things like the name of the Timer, or how it will report on the timings. In Python 3.7, data classes were added to the standard library. These provide several conveniences to your classes, including a more informative representation string. Note: Data classes are included in Python only for version 3.7 and later. However, there is a backport available on PyPI for Python 3.6. You can install it using pip: $ python -m pip install dataclasses See The Ultimate Guide to Data Classes in Python 3.7 for more information. You convert your Python timer to a data class using the @dataclass decorator. You’ll learn more about decorators later in this tutorial. For now, you can think of this as a notation that tells Python that Timer is a data class: 1from dataclasses import dataclass, field 2from typing import Any, ClassVar 3 4@dataclass 5class Timer: 6 timers: ClassVar = dict() 7 name: Any = None 8 text: Any = "Elapsed time: {:0.4f} seconds" 9 logger: Any = print 10 _start_time: Any = field(default=None, init=False, repr=False) 11 12 def __post_init__(self): 13 """Initialization: add timer to dict of timers""" 14 if self.name: 15 self.timers.setdefault(self.name, 0) 16 17 # The rest of the code is unchanged This code replaces your earlier .__init__() method. Note how data classes use syntax that looks similar to the class variable syntax you saw earlier for defining all variables. In fact, .__init__() is created automatically for data classes, based on annotated variables in the definition of the class. You need to annotate your variables to use a data class. You can use this to add type hints to your code. If you don’t want to use type hints, then you can instead annotate all variables with Any, just like you did above. You’ll soon see how to add actual type hints to your data class. Here are a few notes about the Timer data class: Line 4: The @dataclassdecorator defines Timerto be a data class. Line 6: The special ClassVarannotation is necessary for data classes to specify that .timersis a class variable. Lines 7 to 9: .name, .text, and .loggerwill be defined as attributes on Timer, whose values can be specified when creating Timerinstances. They all have the given default values. Line 10: Recall that ._start_timeis a special attribute that’s used to keep track of the state of the Python timer, but should be hidden from the user. Using dataclasses.field()you say that ._start_timeshould be removed from .__init__()and the representation of Timer. Lines 12 to 15: You can use the special .__post_init__()method for any initialization you need to do apart from setting the instance attributes. Here, you use it to add named timers to .timers. Your new Timer data class works just like your previous regular class, except that it now has a nice representation: >>> from timer import Timer >>> t = Timer() >>> t Timer(name=None, text='Elapsed time: {:0.4f} seconds', logger=<built-in function print>) >>> t.start() >>> t.stop() # A few seconds later Elapsed time: 6.7197 seconds 6.719705373998295 Now you have a pretty neat version of Timer that’s consistent, flexible, convenient, and informative! Many of the improvements you’ve seen in this section can be applied to other types of classes in your projects as well. Before ending this section, let’s have a look at the complete source code of Timer as it currently stands. You’ll notice the addition of type hints to the code for extra documentation: # timer.py from dataclasses import dataclass, field import time from typing import Callable, ClassVar, Dict, Optional class TimerError(Exception): """A custom exception used to report errors in use of Timer class""" @dataclass class Timer: timers: ClassVar[Dict[str, float]] = dict() name: Optional[str] = None text: str = "Elapsed time: {:0.4f} seconds" logger: Optional[Callable[[str], None]] = print _start_time: Optional[float] = field(default=None, init=False, repr=False) def __post_init__(self) -> None: """Add timer to dict of timers after initialization""" if self.name is not None: Using a class to create a Python timer has several benefits: - Readability: Your code will read more naturally if you carefully choose class and method names. - Consistency: Your code will be easier to use if you encapsulate properties and behaviors into attributes and methods. - Flexibility: Your code will be reusable if you use attributes with default values instead of hardcoded values. This class is very flexible, and you can use it in almost any situation where you want to monitor the time it takes for code to run. However, in the next sections, you’ll learn about using context managers and decorators, which will be more convenient for timing code blocks and functions. A Python Timer Context Manager Your Python Timer class has come a long way! Compared with the first Python timer you created, your code has gotten quite powerful. However, there’s still a bit of boilerplate code necessary to use your Timer: - First, instantiate the class. - Call .start()before the code block that you want to time. - Call .stop()after the code block. Luckily, Python has a unique construct for calling functions before and after a block of code: the context manager. In this section, you’ll learn what context managers are and how you can create your own. Then you’ll see how to expand Timer so that it can work as a context manager as well. Finally, you’ll see how using Timer as a context manager can simplify your code. Understanding Context Managers in Python Context managers have been a part of Python for a long time. They were introduced by PEP 343 in 2005, and first implemented in Python 2.5. You can recognize context managers in code by the use of the with keyword: with EXPRESSION as VARIABLE: BLOCK EXPRESSION is some Python expression that returns a context manager. The context manager is optionally bound to the name VARIABLE. Finally, BLOCK is any regular Python code block. The context manager will guarantee that your program calls some code before BLOCK and some other code after BLOCK executes. The latter will happen, even if BLOCK raises an exception. The most common use of context managers is probably handling different resources, like files, locks, and database connections. The context manager is then used to free and clean up the resource after you’ve used it. The following example reveals the fundamental structure of timer.py by only printing lines that contain a colon. More importantly, it shows the common idiom for opening a file in Python: >>> with open("timer.py") as fp: ... print("".join(ln for ln in fp if ":" in ln)) ... class TimerError(Exception): class Timer: timers: ClassVar[Dict[str, float]] = dict() name: Optional[str] = None text: str = "Elapsed time: {:0.4f} seconds" logger: Optional[Callable[[str], None]] = print _start_time: Optional[float] = field(default=None, init=False, repr=False) def __post_init__(self) -> None: if self.name is not None: def start(self) -> None: if self._start_time is not None: def stop(self) -> float: if self._start_time is None: if self.logger: if self.name: Note that fp, the file pointer, is never explicitly closed because you used open() as a context manager. You can confirm that fp has closed automatically: >>> fp.closed True In this example, open("timer.py") is an expression that returns a context manager. That context manager is bound to the name fp. The context manager is in effect during the execution of print(). This one-line code block executes in the context of fp. What does it mean that fp is a context manager? Technically, it means that fp implements the context manager protocol. There are many different protocols underlying the Python language. You can think of a protocol as a contract that states what specific methods your code must implement. The context manager protocol consists of two methods: - Call .__enter__()when entering the context related to the context manager. - Call .__exit__()when exiting the context related to the context manager. In other words, to create a context manager yourself, you need to write a class that implements .__enter__() and .__exit__(). No more, no less. Let’s try a Hello, World! context manager example: # greeter.py class Greeter: def __init__(self, name): self.name = name def __enter__(self): print(f"Hello {self.name}") return self def __exit__(self, exc_type, exc_value, exc_tb): print(f"See you later, {self.name}") Greeter is a context manager because it implements the context manager protocol. You can use it like this: >>> from greeter import Greeter >>> with Greeter("Nick"): ... print("Doing stuff ...") ... Hello Nick Doing stuff ... See you later, Nick First, note how .__enter__() is called before you’re doing stuff, while .__exit__() is called after. In this simplified example, you’re not referencing the context manager. In such cases, you don’t need to give the context manager a name with as. Next, notice how .__enter__() returns self. The return value of .__enter__() is what is bound by as. You usually want to return self from .__enter__() when creating context managers. You can use that return value as follows: >>> from greeter import Greeter >>> with Greeter("Emily") as grt: ... print(f"{grt.name} is doing stuff ...") ... Hello Emily Emily is doing stuff ... See you later, Emily Finally, .__exit__() takes three arguments: exc_type, exc_value, and exc_tb. These are used for error handling within the context manager, and mirror the return values of sys.exc_info(). If an exception happens while the block is being executed, then your code calls .__exit__() with the type of the exception, an exception instance, and a traceback object. Often, you can ignore these in your context manager, in which case .__exit__() is called before the exception is reraised: >>> from greeter import Greeter >>> with Greeter("Rascal") as grt: ... print(f"{grt.age} does not exist") ... Hello Rascal See you later, Rascal Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: 'Greeter' object has no attribute 'age' You can see that "See you later, Rascal" is printed, even though there is an error in the code. Now you know what context managers are and how you can create your own. If you want to dive deeper, then check out contextlib in the standard library. It includes convenient ways for defining new context managers, as well as ready-made context managers that can be used to close objects, suppress errors, or even do nothing! For even more information, check out Python Context Managers and the “with” Statement and the accompanying tutorial. Creating a Python Timer Context Manager You’ve seen how context managers work in general, but how can they help with timing code? If you can run certain functions before and after a block of code, then you can simplify how your Python timer works. So far, you’ve needed to call .start() and .stop() explicitly when timing your code, but a context manager can do this automatically. Again, for Timer to work as a context manager, it needs to adhere to the context manager protocol. In other words, it must implement .__enter__() and .__exit__() to start and stop the Python timer. All the necessary functionality is already available, so there’s not much new code you need to write. Just add the following methods to your Timer class: def __enter__(self): """Start a new timer as a context manager""" self.start() return self def __exit__(self, *exc_info): """Stop the context manager timer""" self.stop() Timer is now a context manager. The important part of the implementation is that .__enter__() calls .start() to start a Python timer when the context is entered, and .__exit__() uses .stop() to stop the Python timer when the code leaves the context. Try it out: >>> from timer import Timer >>> import time >>> with Timer(): ... time.sleep(0.7) ... Elapsed time: 0.7012 seconds You should also note two more subtle details: .__enter__()returns self, the Timerinstance, which allows the user to bind the Timerinstance to a variable using as. For example, with Timer() as t:will create the variable tpointing to the Timerobject. .__exit__()expects a triple of arguments with information about any exception that occurred during the execution of the context. In your code, these arguments are packed into a tuple called exc_infoand then ignored, which means that Timerwill not attempt any exception handling. .__exit__() doesn’t do any error handling in this case. Still, one of the great features of context managers is that they’re guaranteed to call .__exit__(), no matter how the context exits. In the following example, you purposely create an error by dividing by zero: >>> from timer import Timer >>> with Timer(): ... for num in range(-3, 3): ... print(f"1 / {num} = {1 / num:.3f}") ... 1 / -3 = -0.333 1 / -2 = -0.500 1 / -1 = -1.000 Elapsed time: 0.0001 seconds Traceback (most recent call last): File "<stdin>", line 3, in <module> ZeroDivisionError: division by zero Note that Timer prints out the elapsed time, even though the code crashed. It’s possible to inspect and suppress errors in .__exit__(). See the documentation for more information. Using the Python Timer Context Manager Let’s see how to use the Timer context manager to time the download of Real Python tutorials. Recall how you used Timer earlier: # latest_tutorial.py from timer import Timer from reader import feed def main(): """Print the latest tutorial from Real Python""" t = Timer() t.start() tutorial = feed.get_article(0) t.stop() print(tutorial) if __name__ == "__main__": main() You’re timing the call to feed.get_article(). You can use the context manager to make the code shorter, simpler, and more readable: # latest_tutorial.py from timer import Timer from reader import feed def main(): """Print the latest tutorial from Real Python""" with Timer(): tutorial = feed.get_article(0) print(tutorial) if __name__ == "__main__": main() This code does virtually the same as the code above. The main difference is that you don’t define the extraneous variable t, which keeps your namespace cleaner. Running the script should give a familiar result: $ python latest_tutorial.py Elapsed time: 0.71 seconds # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] There are a few advantages to adding context manager capabilities to your Python timer class: - Low effort: You only need one extra line of code to time the execution of a block of code. - Readability: Invoking the context manager is readable, and you can more clearly visualize the code block you’re timing. Using Timer as a context manager is almost as flexible as using .start() and .stop() directly, while it has less boilerplate code. In the next section, you’ll see how Timer can be used as a decorator as well. This will make it easier to monitor the runtime of complete functions. A Python Timer Decorator Your Timer class is now very versatile. However, there’s one use case where it could be even more streamlined. Say that you want to track the time spent inside one given function in your codebase. Using a context manager, you have essentially two different options: Use Timerevery time you call the function: with Timer("some_name"): do_something() If you call do_something()in many places, then this will become cumbersome and hard to maintain. Wrap the code in your function inside a context manager: def do_something(): with Timer("some_name"): ... The Timeronly needs to be added in one place, but this adds a level of indentation to the whole definition of do_something(). A better solution is to use Timer as a decorator. Decorators are powerful constructs that you use to modify the behavior of functions and classes. In this section, you’ll learn a little about how decorators work, how Timer can be extended to be a decorator, and how that will simplify timing functions. For a more in-depth explanation of decorators, see Primer on Python Decorators. Understanding Decorators in Python A decorator is a function that wraps another function to modify its behavior. This technique is possible because functions are first-class objects in Python. In other words, functions can be assigned to variables and used as arguments to other functions, just like any other object. This gives you a lot of flexibility and is the basis for several of Python’s more powerful features. As a first example, you’ll create a decorator that does nothing: def turn_off(func): return lambda *args, **kwargs: None First, note that turn_off() is just a regular function. What makes this a decorator is that it takes a function as its only argument and returns a function. You can use this to modify other functions like this: >>> print("Hello") Hello >>> print = turn_off(print) >>> print("Hush") >>> # Nothing is printed The line print = turn_off(print) decorates the print statement with the turn_off() decorator. Effectively, it replaces print() with lambda *args, **kwargs: None returned by turn_off(). The lambda statement represents an anonymous function that does nothing except return None. For you to define more interesting decorators, you need to know about inner functions. An inner function is a function defined inside another function. One common use of inner functions is to create function factories: def create_multiplier(factor): def multiplier(num): return factor * num return multiplier multiplier() is an inner function, defined inside create_multiplier(). Note that you have access to factor inside multiplier(), while multiplier() is not defined outside create_multiplier(): >>> multiplier Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'multiplier' is not defined Instead you use create_multiplier() to create new multiplier functions, each based on a different factor: >>> double = create_multiplier(factor=2) >>> double(3) 6 >>> quadruple = create_multiplier(factor=4) >>> quadruple(7) 28 Similarly, you can use inner functions to create decorators. Remember, a decorator is a function that returns a function: 1def triple(func): 2 def wrapper_triple(*args, **kwargs): 3 print(f"Tripled {func.__name__!r}") 4 value = func(*args, **kwargs) 5 return value * 3 6 return wrapper_triple triple() is a decorator, because it’s a function that expects a function as it’s only argument, func(), and returns another function, wrapper_triple(). Note the structure of triple() itself: - Line 1 starts the definition of triple()and expects a function as an argument. - Lines 2 to 5 define the inner function wrapper_triple(). - Line 6 returns wrapper_triple(). This pattern is prevalent for defining decorators. The interesting parts are those happening inside the inner function: - Line 2 starts the definition of wrapper_triple(). This function will replace whichever function triple()decorates. The parameters are *argsand **kwargs, which collect whichever positional and keyword arguments you pass to the function. This gives you the flexibility to use triple()on any function. - Line 3 prints out the name of the decorated function, and note that triple()has been applied to it. - Line 4 calls func(), the function that has been decorated by triple(). It passes on all arguments passed to wrapper_triple(). - Line 5 triples the return value of func()and returns it. Let’s try it out! knock() is a function that returns the word Penny. See what happens if it’s tripled: >>> def knock(): ... return "Penny! " ... >>> knock = triple(knock) >>> result = knock() Tripled 'knock' >>> result 'Penny! Penny! Penny! ' Multiplying a text string by a number is a form of repetition, so Penny repeats three times. The decoration happens at knock = triple(knock). It feels a bit clunky to keep repeating knock. Instead, PEP 318 introduced a more convenient syntax for applying decorators. The following definition of knock() does the same as the one above: >>> @triple ... def knock(): ... return "Penny! " ... >>> result = knock() Tripled 'knock' >>> result 'Penny! Penny! Penny! ' The @ symbol is used to apply decorators. In this case, @triple means that triple() is applied to the function defined just after it. One of the few decorators defined in the standard library is @functools.wraps. This one is quite helpful when defining your own decorators. Since decorators effectively replace one function with another, they create a subtle issue with your functions: >>> knock <function triple.<locals>.wrapper_triple at 0x7fa3bfe5dd90> @triple decorates knock(), which is then replaced by the wrapper_triple() inner function, as the output above confirms. This will also replace the name, docstring, and other metadata. Often, this will not have much effect, but it can make introspection difficult. Sometimes, decorated functions must have correct metadata. @functools.wraps fixes exactly this issue: import functools def triple(func): @functools.wraps(func) def wrapper_triple(*args, **kwargs): print(f"Tripled {func.__name__!r}") value = func(*args, **kwargs) return value * 3 return wrapper_triple With this new definition of @triple, metadata are preserved: >>> @triple ... def knock(): ... return "Penny! " ... >>> knock <function knock at 0x7fa3bfe5df28> Note that knock() now keeps its proper name, even after being decorated. It’s good form to use @functools.wraps whenever you define a decorator. A blueprint you can use for most of your decorators is the following: import functools def decorator(func): @functools.wraps(func) def wrapper_decorator(*args, **kwargs): # Do something before value = func(*args, **kwargs) # Do something after return value return wrapper_decorator To see more examples of how to define decorators, check out the examples listed in Primer on Python Decorators. Creating a Python Timer Decorator In this section, you’ll learn how to extend your Python timer so that you can use it as a decorator as well. However, as a first exercise, let’s create a Python timer decorator from scratch. Based on the blueprint above, you only need to decide what to do before and after you call the decorated function. This is similar to the considerations about what to do when entering and exiting the context manager. You want to start a Python timer before calling the decorated function, and stop the Python timer after the call finishes. A @timer decorator can be defined as follows: import functools import time def timer(func): @functools.wraps(func) def wrapper_timer(*args, **kwargs): tic = time.perf_counter() value = func(*args, **kwargs) toc = time.perf_counter() elapsed_time = toc - tic print(f"Elapsed time: {elapsed_time:0.4f} seconds") return value return wrapper_timer Note how much wrapper_timer() resembles the early pattern you established for timing Python code. You can apply @timer as follows: >>> @timer ... def latest_tutorial(): ... tutorial = feed.get_article(0) ... print(tutorial) ... >>> latest_tutorial() # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] Elapsed time: 0.5414 seconds Recall that you can also apply a decorator to a previously defined function: >>> feed.get_article = timer(feed.get_article) Since @ applies when functions are defined, you need to use the more basic form in these cases. One advantage of using a decorator is that you only need to apply it once, and it’ll time the function every time: >>> tutorial = feed.get_article(0) Elapsed time: 0.5512 seconds @timer does the job. However, in a sense, you’re back to square one, since @timer does not have any of the flexibility or convenience of Timer. Can you also make your Timer class act like a decorator? So far, you’ve used decorators as functions applied to other functions, but that’s not entirely correct. Decorators must be callables. There are many callable types in Python. You can make your own objects callable by defining the special .__call__() method in their class. The following function and class behave similarly: >>> def square(num): ... return num ** 2 ... >>> square(4) 16 >>> class Squarer: ... def __call__(self, num): ... return num ** 2 ... >>> square = Squarer() >>> square(4) 16 Here, square is an instance that is callable and can square numbers, just like the square() function in the first example. This gives you a way of adding decorator capabilities to the existing Timer class: def __call__(self, func): """Support using Timer as a decorator""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper_timer Timer is already a context manager to take advantage of the conveniences you’ve already defined there. Make sure you also import functools at the top of timer.py. You can now use Timer as a decorator: >>> @Timer(text="Downloaded the tutorial in {:.2f} seconds") ... def latest_tutorial(): ... tutorial = feed.get_article(0) ... print(tutorial) ... >>> latest_tutorial() # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] Downloaded the tutorial in 0.72 seconds Before rounding out this section, know that there’s a more straightforward way of turning your Python timer into a decorator. You’ve already seen some of the similarities between context managers and decorators. They’re both typically used to do something before and after executing some given code. Based on these similarities, there’s a mixin class defined in the standard library called ContextDecorator. You can add decorator abilities to your context manager classes simply by inheriting ContextDecorator: from contextlib import ContextDecorator class Timer(ContextDecorator): # Implementation of Timer is unchanged When you use ContextDecorator this way, there’s no need to implement .__call__() yourself, so you can safely delete it from the Timer class. Using the Python Timer Decorator Let’s redo the latest_tutorial.py example one last time, using the Python timer as a decorator: 1# latest_tutorial.py 2 3from timer import Timer 4from reader import feed 5 6@Timer() 7def main(): 8 """Print the latest tutorial from Real Python""" 9 tutorial = feed.get_article(0) 10 print(tutorial) 11 12if __name__ == "__main__": 13 main() If you compare this implementation with the original implementation without any timing, then you’ll notice that the only differences are the import of Timer on line 3 and the application of @Timer() on line 6. A significant advantage of using decorators is that they’re usually straightforward to apply, as you see here. However, the decorator still applies to the whole function. This means your code is taking into account the time it takes to print the tutorial, in addition to the time it takes to download. Let’s run the script one final time: $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code [ ... The full text of the tutorial ... ] Elapsed time: 0.69 seconds The location of the elapsed time output is a tell-tale sign that your code is considering the time it takes to print time as well. As you see here, your code prints the elapsed time after the tutorial. When you use Timer as a decorator, you’ll see similar advantages as you did with context managers: - Low effort: You only need one extra line of code to time the execution of a function. - Readability: When you add the decorator, you can note more clearly that your code will time the function. - Consistency: You only need to add the decorator when the function is defined. Your code will consistently time it every time it’s called. However, decorators are not as flexible as context managers. You can only apply them to complete functions. It’s possible to add decorators to already defined functions, but this is a bit clunky and less common. The Python Timer Code You can expand the code block below to view the final source code for your Python timer: # timer.py from contextlib import ContextDecorator from dataclasses import dataclass, field import time from typing import Any, Callable, ClassVar, Dict, Optional class TimerError(Exception): """A custom exception used to report errors in use of Timer class""" @dataclass class Timer(ContextDecorator): """Time your code using a class, context manager, or decorator""" timers: ClassVar[Dict[str, float]] = dict() name: Optional[str] = None text: str = "Elapsed time: {:0.4f} seconds" logger: Optional[Callable[[str], None]] = print _start_time: Optional[float] = field(default=None, init=False, repr=False) def __post_init__(self) -> None: """Initialization: add timer to dict of timers""" if self.name: def __enter__(self) -> "Timer": """Start a new timer as a context manager""" self.start() return self def __exit__(self, *exc_info: Any) -> None: """Stop the context manager timer""" self.stop() The code is also available in the codetiming repository on GitHub. You can use the code yourself by saving it to a file named timer.py and importing it into your program: >>> from timer import Timer Timer is also available on PyPI, so an even easier option is to install it using pip: $ python -m pip install codetiming Note that the package name on PyPI is codetiming. You’ll need to use this name both when you install the package and when you import Timer: >>> from codetiming import Timer Apart from this, codetiming.Timer works exactly as timer.Timer. To summarize, you can use Timer in three different ways: As a class: t = Timer(name="class") t.start() # Do something t.stop() As a context manager: with Timer(name="context manager"): # Do something As a decorator: @Timer(name="decorator") def stuff(): # Do something This kind of Python timer is mainly useful for monitoring the time your code spends at individual key code blocks or functions. In the next section, you’ll get a quick overview of alternatives you can use if you’re looking to optimize your code. Other Python Timer Functions There are many options for timing your code with Python. In this tutorial, you’ve learned how to create a flexible and convenient class that you can use in several different ways. A quick search on PyPI shows that there are already many projects available that offer Python timer solutions. In this section, you’ll first learn more about the different functions available in the standard library for measuring time, and why perf_counter() is preferable. Then, you’ll see alternatives for optimizing your code, for which Timer is not well-suited. Using Alternative Python Timer Functions You’ve been using perf_counter() throughout this tutorial to do the actual time measurements, but Python’s time library comes with several other functions that also measure time. Here are some alternatives: One of the reasons why there are several functions is that Python represents time as a float. Floating-point numbers are inaccurate by nature. You may have seen results like these before: >>> 0.1 + 0.1 + 0.1 0.30000000000000004 >>> 0.1 + 0.1 + 0.1 == 0.3 False Python’s float follows the IEEE 754 Standard for Floating-Point Arithmetic, which tries to represent all floating-point numbers in 64 bits. Since there are infinitely many floating-point numbers, you can’t express them all with a finite number of bits. IEEE 754 prescribes a system where the density of numbers that you can represent varies. The closer you are to 1, the more numbers you can represent. For larger numbers, there’s more space between the numbers that you can express. This has some consequences when you use a float to represent time. Consider time(). The main purpose of this function is to represent the actual time right now. It does this as the number of seconds since a given point in time, called the epoch. The number returned by time() is quite big, which means that there are fewer numbers available, and the resolution suffers. Specifically, time() is not able to measure nanosecond differences: >>> import time >>> t = time.time() >>> t 1564342757.0654016 >>> t + 1e-9 1564342757.0654016 >>> t == t + 1e-9 True A nanosecond is one-billionth of a second. Note that adding a nanosecond to t does not affect the result. perf_counter(), on the other hand, uses some undefined point in time as its epoch, allowing it to work with smaller numbers and therefore obtain a better resolution: >>> import time >>> p = time.perf_counter() >>> p 11370.015653846 >>> p + 1e-9 11370.015653847 >>> p == p + 1e-9 False Here, you see that adding a nanosecond to p actually affects the outcome. For more information about how to work with time(), see A Beginner’s Guide to the Python time Module. The challenges with representing time as a float are well known, so Python 3.7 introduced a new option. Each time measurement function now has a corresponding _ns function that returns the number of nanoseconds as an int instead of the number of seconds as a float. For instance, time() now has a nanosecond counterpart called time_ns(): >>> import time >>> time.time_ns() 1564342792866601283 Integers are unbounded in Python, so this allows time_ns() to give nanosecond resolution for all eternity. Similarly, perf_counter_ns() is a nanosecond variant of perf_counter(): >>> import time >>> time.perf_counter() 13580.153084446 >>> time.perf_counter_ns() 13580765666638 Since perf_counter() already provides nanosecond resolution, there are fewer advantages to using perf_counter_ns(). Note: perf_counter_ns() is only available in Python 3.7 and later. In this tutorial, you’ve used perf_counter() in your Timer class. That way, Timer can be used on older Python versions as well. For more information about the _ns functions in time, check out Cool New Features in Python 3.7. There are two functions in time that do not measure the time spent sleeping. These are process_time() and thread_time(), which are useful in some settings. However, for Timer, you typically want to measure the full time spent. The final function in the list above is monotonic(). The name alludes to this function being a monotonic timer, which is a Python timer that can never move backward. All these functions are monotonic except time(), which can go backward if the system time is adjusted. On some systems, monotonic() is the same function as perf_counter(), and you can use them interchangeably. However, this is not always the case. You can use time.get_clock_info() to get more information about a Python timer function. Using Python 3.7 on Linux I get the following information: >>> import time >>>) The results could be different on your system. PEP 418 describes some of the rationale behind introducing these functions. It includes the following short descriptions: As you can see, it’s usually the best choice for you to use perf_counter() for your Python timer. Estimating Running Time With timeit Say you’re trying to squeeze the last bit of performance out of your code, and you’re wondering about the most effective way to convert a list to a set. You want to compare using set() and the set literal, {...}. You can use your Python timer for this: >>> from timer import Timer >>> numbers = [7, 6, 1, 4, 1, 8, 0, 6] >>> with Timer(text="{:.8f}"): ... set(numbers) ... {0, 1, 4, 6, 7, 8} 0.00007373 >>> with Timer(text="{:.8f}"): ... {*numbers} ... {0, 1, 4, 6, 7, 8} 0.00006204 This test seems to indicate that the set literal might be slightly faster. However, these results are quite uncertain, and if you rerun the code, you might get wildly different results. That’s because you’re only trying the code once. You could, for instance, get unlucky and run the script just as your computer is becoming busy with other tasks. A better way is to use the timeit standard library. It’s designed precisely to measure the execution time of small code snippets. While you can import and call timeit.timeit() from Python as a regular function, it is usually more convenient to use the command-line interface. You can time the two variants as follows: $ python -m timeit --setup "nums = [7, 6, 1, 4, 1, 8, 0, 6]" "set(nums)" 2000000 loops, best of 5: 163 nsec per loop $ python -m timeit --setup "nums = [7, 6, 1, 4, 1, 8, 0, 6]" "{*nums}" 2000000 loops, best of 5: 121 nsec per loop timeit automatically calls your code many times to average out noisy measurements. The results from timeit confirm that the set literal is faster than set(). You can find more information about this particular issue at Michael Bassili’s blog. Note: Be careful when you’re using timeit on code that can download files or access databases. Since timeit automatically calls your program several times, you could unintentionally end up spamming the server with requests! Finally, the IPython interactive shell and the Jupyter notebook have extra support for this functionality with the %timeit magic command: In [1]: numbers = [7, 6, 1, 4, 1, 8, 0, 6] In [2]: %timeit set(numbers) 171 ns ± 0.748 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [3]: %timeit {*numbers} 147 ns ± 2.62 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) Again, the measurements indicate that using a set literal is faster. In Jupyter Notebooks you can also use the %%timeit cell-magic to measure the time of running a whole cell. Finding Bottlenecks in Your Code With Profilers timeit is excellent for benchmarking a particular snippet of code. However, it would be very cumbersome to use it to check all parts of your program and locate which sections take the most time. Instead, you can use a profiler. cProfile is a profiler that you can access at any time from the standard library. You can use it in several ways, although it’s usually most straightforward to use it as a command-line tool: $ python -m cProfile -o latest_tutorial.prof latest_tutorial.py This command runs latest_tutorial.py with profiling turned on. You save the output from cProfile in latest_tutorial.prof, as specified by the -o option. The output data is in a binary format that needs a dedicated program to make sense of it. Again, Python has an option right in the standard library! Runnin the pstats module on your .prof file opens an interactive profile statistics browser: $ python -m pstats latest_tutorial.prof Welcome to the profile statistics browser. latest_tutorial.prof% help Documented commands (type help <topic>): ======================================== EOF add callees callers help quit read reverse sort stats strip To use pstats you type commands at the prompt. Here you can see the integrated help system. Typically you’ll use the sort and stats commands. To get a cleaner output, strip can be useful: latest_tutorial.prof% strip latest_tutorial.prof% sort cumtime latest_tutorial.prof% stats 10 1393801 function calls (1389027 primitive calls) in 0.586 seconds Ordered by: cumulative time List reduced from 1443 to 10 due to restriction <10> ncalls tottime percall cumtime percall filename:lineno(function) 144/1 0.001 0.000 0.586 0.586 {built-in method builtins.exec} 1 0.000 0.000 0.586 0.586 latest_tutorial.py:3(<module>) 1 0.000 0.000 0.521 0.521 contextlib.py:71(inner) 1 0.000 0.000 0.521 0.521 latest_tutorial.py:6(read_latest_tutorial) 1 0.000 0.000 0.521 0.521 feed.py:28(get_article) 1 0.000 0.000 0.469 0.469 feed.py:15(_feed) 1 0.000 0.000 0.469 0.469 feedparser.py:3817(parse) 1 0.000 0.000 0.271 0.271 expatreader.py:103(parse) 1 0.000 0.000 0.271 0.271 xmlreader.py:115(parse) 13 0.000 0.000 0.270 0.021 expatreader.py:206(feed) This output shows that the total runtime was 0.586 seconds. It also lists the ten functions where your code spent most of its time. Here you’ve sorted by cumulative time ( cumtime), which means that your code counts time when the given function has called another function. You can see that your code spends virtually all its time inside the latest_tutorial module, and in particular, inside read_latest_tutorial(). While this might be useful confirmation of what you already know, it’s often more interesting to find where your code actually spends time. The total time ( tottime) column indicates how much time your code spent inside a function, excluding time in sub-functions. You can see that none of the functions above really spend any time doing this. To find where the code spent most of its time, issue another sort command: latest_tutorial.prof% sort tottime latest_tutorial.prof% stats 10 1393801 function calls (1389027 primitive calls) in 0.586 seconds Ordered by: internal time List reduced from 1443 to 10 due to restriction <10> ncalls tottime percall cumtime percall filename:lineno(function) 59 0.091 0.002 0.091 0.002 {method 'read' of '_ssl._SSLSocket'} 114215 0.070 0.000 0.099 0.000 feedparser.py:308(__getitem__) 113341 0.046 0.000 0.173 0.000 feedparser.py:756(handle_data) 1 0.033 0.033 0.033 0.033 {method 'do_handshake' of '_ssl._SSLSocket'} 1 0.029 0.029 0.029 0.029 {method 'connect' of '_socket.socket'} 13 0.026 0.002 0.270 0.021 {method 'Parse' of 'pyexpat.xmlparser'} 113806 0.024 0.000 0.123 0.000 feedparser.py:373(get) 3455 0.023 0.000 0.024 0.000 {method 'sub' of 're.Pattern'} 113341 0.019 0.000 0.193 0.000 feedparser.py:2033(characters) 236 0.017 0.000 0.017 0.000 {method 'translate' of 'str'} You can now see that latest_tutorial.py actually spends most of its time working with sockets or handling data inside feedparser. The latter is one of the dependencies of the Real Python Reader that’s used to parse the tutorial feed. You can use pstats to get some idea on where your code is spending most of its time and see if you can optimize any bottlenecks you find. You can also use the tool to understand the structure of your code better. For instance, the commands callees and callers will show you which functions call and are called by a given function. You can also investigate certain functions. Let’s see how much overhead Timer causes by filtering the results with the phrase timer: latest_tutorial.prof% stats timer 1393801 function calls (1389027 primitive calls) in 0.586 seconds Ordered by: internal time List reduced from 1443 to 8 due to restriction <'timer'> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 timer.py:13(Timer) 1 0.000 0.000 0.000 0.000 timer.py:35(stop) 1 0.000 0.000 0.003 0.003 timer.py:3(<module>) 1 0.000 0.000 0.000 0.000 timer.py:28(start) 1 0.000 0.000 0.000 0.000 timer.py:9(TimerError) 1 0.000 0.000 0.000 0.000 timer.py:23(__post_init__) 1 0.000 0.000 0.000 0.000 timer.py:57(__exit__) 1 0.000 0.000 0.000 0.000 timer.py:52(__enter__) Luckily, Timer causes only minimal overhead. Use quit to leave the pstats browser when you’re done investigating. For a more powerful interface into profile data, check out KCacheGrind. It uses its own data format, but you can convert data from cProfile using pyprof2calltree: $ pyprof2calltree -k -i latest_tutorial.prof This command will convert latest_tutorial.prof and open KCacheGrind to analyze the data. The last option you’ll see here for timing your code is line_profiler. cProfile can tell you which functions your code spends the most time in, but it won’t give you insights into which lines inside that function are the slowest. That’s where line_profiler can help you. Note: You can also profile the memory consumption of your code. This falls outside the scope of this tutorial. However, you can have a look at memory-profiler if you need to monitor the memory consumption of your programs. Note that line profiling takes time and adds a fair bit of overhead to your runtime. A more standard workflow is first to use cProfile to identify which functions to look at and then run line_profiler on those functions. line_profiler is not part of the standard library, so you should first follow the installation instructions to set it up. Before you run the profiler, you need to tell it which functions to profile. You do this by adding a @profile decorator inside your source code. For example, to profile Timer.stop() you add the following inside timer.py: @profile def stop(self) -> float: # The rest of the code is unchanged Note that you don’t import profile anywhere. Instead, it’s automatically added to the global namespace when you run the profiler. You need to delete the line when you’re done profiling, though. Otherwise, you’ll get a NameError. Next, run the profiler using kernprof, which is part of the line_profiler package: $ kernprof -l latest_tutorial.py This command automatically saves the profiler data in a file called latest_tutorial.py.lprof. You can see those results using line_profiler: $ python -m line_profiler latest_tutorial.py.lprof Timer unit: 1e-06 s Total time: 1.6e-05 s File: /home/realpython/timer.py Function: stop at line 35 # Hits Time PrHit %Time Line Contents ===================================== 35 @profile 36 def stop(self) -> float: 37 """Stop the timer, and report the elapsed time""" 38 1 1.0 1.0 6.2 if self._start_time is None: 39 raise TimerError(f"Timer is not running. ...") 40 41 # Calculate elapsed time 42 1 2.0 2.0 12.5 elapsed_time = time.perf_counter() - self._start_time 43 1 0.0 0.0 0.0 self._start_time = None 44 45 # Report elapsed time 46 1 0.0 0.0 0.0 if self.logger: 47 1 11.0 11.0 68.8 self.logger(self.text.format(elapsed_time)) 48 1 1.0 1.0 6.2 if self.name: 49 1 1.0 1.0 6.2 self.timers[self.name] += elapsed_time 50 51 1 0.0 0.0 0.0 return elapsed_time First, note that the time unit in this report is microseconds ( 1e-06 s). Usually, the most accessible number to look at is %Time, which tells you the percentage of the total time your code spends inside a function at each line. In this example, you can see that your code spends almost 70% of the time on line 47, which is the line that formats and prints the result of the timer. Conclusion In this tutorial, you’ve seen several different approaches to adding a Python timer to your code: You used a class to keep state and add a user-friendly interface. Classes are very flexible, and using Timerdirectly gives you full control over how and when to invoke the timer. You used a context manager to add features to a block of code and, if necessary, to clean up afterward. Context managers are straightforward to use, and adding with Timer()can help you more clearly distinguish your code visually. You used a decorator to add behavior to a function. Decorators are concise and compelling, and using @Timer()is a quick way to monitor your code’s runtime. You’ve also seen why you should prefer time.perf_counter() over time.time() when benchmarking code, as well as what other alternatives are useful when you’re optimizing your code. Now you can add Python timer functions to your own code! Keeping track of how fast your program runs in your logs will help you monitor your scripts. Do you have ideas for other use cases where classes, context managers, and decorators play well together? Leave a comment down below! Resources For a deeper dive into Python timer functions, check out these resources: codetimingis the Python timer available on PyPI. time.perf_counter()is a performance counter for precise timings. timeitis a tool for comparing the runtimes of code snippets. cProfileis a profiler for finding bottlenecks in scripts and programs. pstatsis a command-line tool for looking at profiler data. - KCachegrind is a GUI for looking at profiler data. line_profileris a profiler for measuring individual lines of code. memory-profileris a profiler for monitoring memory usage.
https://realpython.com/python-timer/
CC-MAIN-2022-05
refinedweb
11,524
66.54
while developing my personal library I stumbled upon what I think is an error inside libstdc++6. Because I'm quite sure this library has been reviewed by a lot of much higher skilled people than I am I came here to validate my finding and get assistance on further steps. Consider the following code: #include <regex> #include <iostream> int main() { std::string uri = ""; std::regex reg(...); std::smatch match; std::regex_match(uri, match, reg); for(auto& e: match) { std::cout<<e.str() <<std::endl; } } std::regex reg("^(.+):\\/\\/(.+@)?([a-zA-Z\\.\\-0-9]+)(:\\d{1,5})?([^?\\n\\#]*)(\\?[^#\\n]*)?(\\#.*)?$"); g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609 libstdc++6:amd64 5.4.0-6ubuntu1~16.04.2 std::regex reg("^(.+):\\/\\/(.+@)?([a-zA-Z\\.0-9\\-]+)(:\\d{1,5})?([^?\\n\\#]*)(\\?[^#\\n]*)?(\\#.*)?$"); [a-zA-Z\\.\\-0-9] // not working [a-zA-Z\\.0-9\\-] // working This is clearly a bug because "[.\\-0]" should be parsed as a character class matching a character that is either . or - (since the hyphen is escaped with a literal \) or a 0. For an unknown reason, the hyphen is parsed as a range operator and the [a-zA-Z\\.\\-0-9]+ subexpression becomes equal to [a-zA-Z.-0-9]+. See this regex demo. The second expression works because a - at the end of the character class (and at its start) is always parsed as a literal hyphen. Another example of the same bug: std::string uri = "%"; std::regex reg(R"([$\-&])"); std::smatch match; std::regex_match(uri, match, reg); for(auto& e: match) { std::cout<< e.str() <<std::endl; } The [$\-&] regex should not match %, it should match $, - or &, but for whatever reason, the % (that is between $ and & in the ASCII table) is still matched.
https://codedump.io/share/ZQDGopqRDw3A/1/validation-for-error
CC-MAIN-2017-13
refinedweb
291
76.32
I'm working on a problem where I need to use a one-dimensional array to write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, it displays it only if it is not a duplicate of a number already read. The program should keep asking for input until 5 unique numbers are input. Use the smallest possible array to solve this program. Display the complete set of unique values input after the user enters each new value. I'm stuck. Everything works correctly except for the nested if loop. It always accepts this for true. Any ideas on how I might rearrange my code to make this work properly? Thanks in advance! Also, I apologize for the sloppy code. I don't know how to make it translate to look pretty on here. import java.util.Scanner; public class UniqueTest { public static void main(String[] args) { //declare an array with 5 elements int num[] = new int[5]; int index = 0; Scanner input = new Scanner(System.in); //declare the input object (she didn't do this for us) while(index < num.length){ System.out.println("Enter an integer between 10 and 100: "); //accept a keyboard input and assign it to a variable int number = input.nextInt(); if (number>=10&&number<=100) { ++index; num[index] += number; System.out.printf("%d\n", num[index]); if (number == num[index]) { System.out.println("Value has already been entered."); } } else { System.out.println("Error: You did not enter a number between 10 and 100."); } } } }
https://www.daniweb.com/programming/software-development/threads/158183/question-about-arrays
CC-MAIN-2016-50
refinedweb
257
58.89
In software, a processing "pipeline" is one of the few examples of a real, physical concept having a useful counterpart in software. Another popular example is thinking of software in terms of "objects." One of the advantages of these types of concepts is that because we understand their physical counterparts, we know how to use and can easily grasp them. Although there is certainly more to object-oriented programming than understanding the concept of a physical object, a pipeline really is just about that simple. A pipeline, as defined here, is simply a collection of pipe segments connected together in different ways, according to pre-specified rules, in order to accomplish a task. In its simplest form, a pipeline only requires a head and a tail, and they can be one and the same (although this typically defeats the purpose). A software pipeline can be used in a lot of ways. Some examples I've seen are: performing long scientific algorithms, where each step is well-delineated; performing abstracted device reads/writes, as in the case of buffered I/O (network, harddrive, etc.); and in graphical processing. As a big fan of the interface-as-a-contract school of thought, when I sat down to design the pipeline, I wanted to establish a simple means by which to connect two objects, while also affording interface-level freedom throughout. Connecting one object to another object in this context - via the object1.connectTo(&object2) method, or with the overloaded object1 += object2 operator - is synonymous with telling one object(object1) to send its output to another (object2). object1.connectTo(&object2) object1 += object2 object1 object2 In the event that you are unfamiliar with the interface-as-a-contract paradigm, I'll give you my brief synopsis. It says that one of the things you consider when you start a software development project is interface definition. Define interfaces in areas that you believe will be changed/expanded - in other words (not mine), "encapsulate the variation." If you incorporate good interfaces into your software design, you will reap the benefits many times over. This is particularly useful in a pipelined design, where it's typically prudent to define an interface at each connection-point. Then, users can implement a particular interface (agree to a contract) they are interested in working on and connect it right into the pipeline seamlessly. This framework provides a single class that defines a segment in the pipe, and can determine, at compile time, whether or not it can successfully connect to another pipe segment. The user can specify a class, base-class, or interface (abstract class), that defines the types of classes that his/her pipe segment(s) can connect to. A pipe segments may be simultaneously connected to other pipe segments, as well as having other pipe segments simultaneously connected to it. abstract Since the demo application provided is about the most boring application ever written, and I am not interested in praise for this article on the grounds of its ability to cure insomnia, I'll show how to use the framework to construct a marginally more interesting, purely hypothetical, HTTP server request processing pipeline. Please take note of the fact that there will not be any implementation of a server here (this code will not compile), just the following grossly over simplified four step pipeline: Our HTTP server processing pipeline will contain a pipe segment for each of these steps: HTTPRequestHandler HTTPRequest HTTPRequestAuthenticator HTTPRequestAuthorizer HTTPRequestResponder The terrific thing about this example is that, in order to accomplish this enormous feat of coding prowress, we will only need to define one interface, which each of the above classes will implement: IHTTPRequestHandler HandleHTTPRequest(HTTPRequest *theRequest) I'm not going to discuss the innards of the HTTPRequest class, I'm just going to assume it already exists, nor will I wax eloquent on the proper methodologies for doing HTTP request authentication or anything similar. Please, do not write to me to let me know this is not the right way to code an HTTP server. I'm sure there's a lot more to it. What we're working towards here is for the following code to be executed prior to the first request handled by the HTTP server. This is where we're building the pipeline. I realize this would probably cause some scoping problems if implemented cut-n-paste from here - again, this is only an example to give you a feel for things. I'll let you figure out how to get around scoping/variable lifetime issues: ... //Build the individual pipeline segments HTTPRequestHandler theRequestHandler; HTTPRequestAuthenticator theAuthenticator; HTTPRequestAuthorizer theAuthorizer; HTTPRequestResponder theResponder; //Attach the individual pipeline segments theRequestHandler += theAuthenticator; theAuthenticator += theAuthorizer; theAuthorizer += theResponder; //Or, you can attach them all in one line if you like theRequestHandler.connectTo(theAuthenticator.connectTo (theAuthorizer.connectTo(theResponder))); ... Hopefully, that's pretty self-explanatory. Now, how do we get there? Well first we'll write the IHTTPRequestHandler interface and define it something like this: IHTTPRequestHandler #include "HTTPRequest.h" #include "PipeSegmentBaseAdapter.h" class IHTTPRequestHandler : public PipeLineProcessing::PipeSegmentBaseAdapter { public: virtual void HandleHTTPRequest(HTTPRequest *request)=0; }; With that interface defined, we can start writing the pipe segment objects. They might look like this: #include "HTTPRequest.h" #include "PipeSegment.h" class HTTPRequestHandler : public IHTTPRequestHandler, //the object itself "is a" IHTTPRequestHandler //and it only outputs to IHTTPRequestHandler objects public PipeLineProcessing::PipeSegment<IHTTPRequestHandler> { public: virtual void HandleHTTPRequest(HTTPRequest *request) { //Since the HTTPRequestHandler object does nothing besides //send the request off to any connected request handlers, //this method simply iterates over the collection of output //handlers currently "connected to" this object. for (int i=0; i < (int)this->theOutput.size(); i++) { IHTTPRequestHandler *anOutputHandler = (IHTTPRequestHandler *)this->theOutput.at(i); anOutputHandler->HandleHTTPRequest(request); } }; }; class HTTPRequestAuthenticator : public IHTTPRequestHandler, //the object itself "is a" IHTTPRequestHandler //and it only outputs to IHTTPRequestHandler objects public PipeLineProcessing::PipeSegment<IHTTPRequestHandler> { private: bool requestIsAuthentic(HTTPRequest *request) { return true; }; //everyone's authenticated! public: virtual void HandleHTTPRequest(HTTPRequest *request) { //This object only passes the HTTPRequest down the //pipeline if the request is successfully authenticated if (requestIsAuthentic(request)) { for (int i=0; i < (int)this->theOutput.size(); i++) { IHTTPRequestHandler *anOutputHandler = (IHTTPRequestHandler *)this->theOutput.at(i); anOutputHandler->HandleHTTPRequest(request); } } } }; Above we've defined the first two pipeline segments. Hopefully they are readable enough that you can see they both have the same hierarchy tree. In pipeline terms, they both output to and serve as input for IHTTPRequestHandler type objects. The convention here is that the first type listed in the inheritance definition specifies the interface you are implementing, if any. Secondly, you use the PipeSegment to specify which type of objects you will output to. If you haven't been sleeping well the last few nights and/or you have deep questions at this point, look at the code in the demo app supplied. It should clear things up -- or put you to sleep, whichever your ailment. PipeSegment Please also notice the for loop that is in each class. This will be discussed in more detail later. for So, the other two classes will look similar -- maybe like this: class HTTPRequestAuthorizer : public IHTTPRequestHandler, //the object itself "is a" IHTTPRequestHandler //and it only outputs to IHTTPRequestHandler objects public PipeLineProcessing::PipeSegment<IHTTPRequestHandler> { private: bool requestIsAuthorized(HTTPRequest *request) { return true; }; //everyone's authorized! public: virtual void HandleHTTPRequest(HTTPRequest *request) { //This object only passes the HTTPRequest down the //pipeline if the request is successfully authorized if (requestIsAuthorized(request)) { for (int i=0; i < (int)this->theOutput.size(); i++) { IHTTPRequestHandler *anOutputHandler = (IHTTPRequestHandler *)this->theOutput.at(i); anOutputHandler->HandleHTTPRequest(request); } } } }; class HTTPRequestResponder : public IHTTPRequestHandler, //the object itself "is a" IHTTPRequestHandler //and it is the end of the tail -- it has no output objects public PipeLineProcessing::IPipeTail { private: void respondToRequest(HTTPRequest *request) { /* umm, nothing here. */ }; public: virtual void HandleHTTPRequest(HTTPRequest *request) { respondToRequest(request); } }; And that's it! Now you can execute the code we first started with, and send the HTTPRequest to the HTTPRequestHandler. The HTTPRequest object will be authenticated, authorized and responded to via our sweet little pipeline -- all automatically! HTTPRequestHandler The only remaining question is, "what's with the for loop?" Well, this was the one evil part of the whole thing. I could not devise a means by which to automatically determine and invoke which method of the output objects to call without complicating things enormously, adding extra library dependencies, and/or possibly using functors/delegates, with which I am not yet too friendly. I didn't want to do that, so I kept things simple and levied the requirement on the user to actually spell out when he/she wants to send the output down the rest of the pipeline. The for loop iterates over the theOutput STL vector inherited from the PipeLineProcessing::PipeSegmentBase base class. This vector stores pointers to all of the pipe segment objects this pipe segment connects to (that is, sends its output to). As it iterates over these output handlers, it downcasts them to pointers of the type specified in the class' definition (as this type of pipe segment's template parameter). By calling the desired method on that type, the pipeline is continued. theOutput PipeLineProcessing::PipeSegmentBase The astute programmer should've woken up when he/she saw the word "downcast" since this is considered an unsafe, dangerous casting. Unlike an upcast which casts a derived object as a base class type, and is therefore always safe, a downcast casts a base class as a derived class. This is dangerous because, in general, one never knows if the object being executed at run-time will be of the derived type, whereas one always knows that a derived type can be treated as a base type. To use a physical example, all soccer balls are balls(upcast), but not all balls are soccer balls(downcast). So, how can we safely downcast a ball to a soccer ball? Only if we are certain that it is one. In this framework, that certainty is accomplished through the methods that add objects to the theOutput vector. While they are generic internally, the only methods exposed to clients to facilitate connections, the += operator and the connectTo method, only accept the appropriate types of objects. In other words, we let the compiler do our checking; unless the object being added on to the end of the pipe is, or can safely be addressed as (that is, upcast to), the type specified in the output defining portion of this class's definition, it will be flagged at compile time. This is one of the cooler tricks in this little project, and it is mostly thanks to the Kevlin Henney trick I found. I show examples of this in my boring demo. += connectTo This is my first submission to CodeProject, so please give it a try and leave comments. G & A Technical Software (GATS) has released this code to the public domain. This means that you are allowed to take this code and use it with almost no legal obligations whatsoever. No copy left nonsense, no requirement that you keep the header in-tact, nothing. The only stipulation, in fact, is that by using the software you release GATS from any and all liability -- neither of us will be held responsible for any difficulties that might arise from you or your company's use of the code. For more details, read the header on any file in the source. Like all open source software, this framework could be extended (hopefully easily) to provide even more power to the developer using it. Some of my ideas are: Pipeline Obviously, if you make any improvements that you would like to share, send them to me, and if I think they're good, I'll add them here for sure. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) tamasan wrote:I have a big problem with my program. When i run it with Debug file, it run normaly. But, when i build it to exe in Release directory. It run with error: Unhandled exception in VISIODT.exe (COMCTL32.DLL): 0xC0000005: Access Violation. What proplem is it? General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/15682/A-Generic-Pipeline-Framework-for-C?PageFlow=FixedWidth
CC-MAIN-2015-18
refinedweb
2,041
50.67
Your Account PRESS QUERIES ONLY O'Reilly Media (707) 827-7000 July 1, 2002 Sebastopol, CA--So rapidly evolving is the world of XML that it shifted from its position as a new technology to an established technology while many people were still trying to understand just what it was. "XML has become the lingua franca of data formats," says Elliotte Rusty Harold, coauthor with W. Scott Means of the just-released second edition of "XML in a Nutshell" (O'Reilly, US $39.95). "While there are still many non-XML legacy applications out there, most new applications are choosing to use XML as their native data format. Sun's StarOffice 6.0 is just one public example, but there's even more work going on in the non-shrink-wrapped, custom business software in enterprises of all sizes." XML, the Extensible Markup Language, is a W3C-endorsed standard for document markup. It defines a generic syntax used to mark up data with simple, human-readable tags, and it provides a standard format for computer documents. Because of its flexibility, XML has become the syntax of choice for newly designed document formats across almost all computer applications. As Harold and Means tell us, "XML is simply the most robust, reliable, and flexible document syntax ever invented." The new edition of "XML in a Nutshell" provides developers with a comprehensive guide to all aspects of XML, from the most basic syntax rules, to the details of DTD and schema creation, to the APIs used to read and write XML documents in a variety of programming languages. With updated sections on standards still in development, and extra coverage of Unicode, the book provides an easy-to-use reference to the fundamental rules to which all XML documents and authors must adhere. "XML in a Nutshell, Second Edition" helps readers quickly develop an understanding of well-formed XML, namespaces, Unicode and W3C XML Schema. The authors tackle the key technologies used mainly for narrative XML documents, such as web pages, books, and articles, offering readers a working knowledge of XSLT, Xpath, XLink, XPointer, CSS, and XSL-FO. The book also covers the technologies use for building data-intensive XML applications and for processing XML documents of any kind. The core of the book, as with any "Nutshell" book, is the quick-reference guide that details syntax rules and usage examples for key XML technologies. This book is an essential guide for developers who need to create XML-based file formats and data structures for use in XML documents. As Harold says: "'XML in a Nutshell' is the best introduction to XML out there. Very few XML books even attempt to cover this much material. It is the most concentrated, cost-effective way to educate yourself about XML." What the critics said about the first edition: "Best of 2001: Customers' Picks," amazon.com "This book is the one you won't want to let out of your sight." --IT Training, August, 2001 "A solid and useful reference for XML developers. The value of 'XML in a Nutshell' should be readily apparent to XML developers. The material is well organized and concise. It's a quintessential Nutshell book, upholding a tradition of utility and quality. Readers who've already been exposed to the presented material will likely keep this book close at hand."--chromatic, slashdot.com, September 13, 2001 "These ('Learning XML' and 'XML in a Nutshell') are the most accessible books on XML that I have come across and I would certainly use 'Learning XML' as a recommended text for any course on it that I gave. If you work with XML, or are going to, then you probably ought to have both these books"--Lindsay Marshall, news@UK, June 2001 "Not just a reference...a remarkable comprehensive book. Harold and Means' book offers two advantages over the others: It's clearer than previous books...and it's the most recent, and hence up-to-date book currently on the market."--Eugene Eric Kim, Web Techniques, July 2001 "If you're using XML on a regular basis, then you should have this reference book on your desk. There is a lot to know about XML, but with this excellent reference manual, you don't have to know it, just where to look it up. Once you're comfortable with XML, you will want this book as part of your library."--Jennifer Kyrnin, Focus on HTML/XML Additional resources: Chapter 9, "XPath," is available free online at: For more information about the book, including Table of Contents, index, author bios, and samples, see:.
http://www.oreilly.com/pub/pr/1028
CC-MAIN-2015-48
refinedweb
768
59.43
Introduction Object class has got very prominence in Java programming. In inheritance, it sits at the top of the hierarchy. That is, any Java class, either you write or predefined, should be a subclass of Object class. If you write any class, Java implicitly extends Object class. Why this? Java designers thought that some methods are useful for every Java program. They placed these methods in Object class and extends class Object so that every Java program can make use of them. To say simply, Object class is the super class of all classes of Java. It is the root class of all classes. Any Java class you write implicitly inherits Object and for this reason it is placed at the top of each class in the hierarchy. That is the class public class Test { } you write, implicitly becomes public class Test extends Object { } a subclass of class Object. The class Object includes only one default constructor and comes with methods like getClass(), hashCode(), clone(), toString(), wait(), notify(), notifyAll() and finalize() etc. wait() and notify() are in synchronization. Practicing class Object methods is very important to get confidence in coding. Pass comments and suggestions on this tutorial "class Object" to improve the quality.
https://way2java.com/java-lang/object-class/
CC-MAIN-2020-40
refinedweb
203
65.22
Hey guys! I had a question on two things. First, can you explain the parameters part of public void paint(Graphics g){} ? I don't understand graphics g? Is it an object? It doesn't have an instance created... Also, for the next question I need to show my code. The question is, I don't understand how the method paint is called. Does the method implicitly execute? I've seen where theres multiple methods and they are never called in the main method... Also, why is it necessary to say "new Carz"? Why must we create an instance of the Carz constructer? Thanks to all. Code : import javax.swing.*; import java.awt.*; class Carz extends JFrame { Carz() { super("Cars"); setSize(1000,1000); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } Car Ferrari = new Car(20, 200, "Red"); Car Lexus = new Car(30, 160, "White"); Car Honda = new Car(25, 150, "Blue"); public void paint(Graphics m) { m.setFont(new Font( "Helvetica", Font.PLAIN, 16)); m.drawRect(20, 50, 960, 460); m.setColor(Color.BLACK); m.fillRect(20, 50, 960, 460); m.setColor(Color.WHITE); m.drawString("We have a " + Ferrari.color + "that gets " + Ferrari.mpg + "and can go as fast as " + Ferrari.mph + ".", 30,70); m.drawString("We have a " + Honda.color + "that gets " + Honda.mpg + "and can go as fast as " + Honda.mph + ".", 30,100); m.drawString("We have a " + Lexus.color + "that gets " + Lexus.mpg + "and can go as fast as " + Lexus.mph + ".", 30,130); } public static void main(String[] args) { new Carz(); } } class Car{ int mpg; int mph; String color; Car(int mpg, int mph, String color){ this.mpg = mpg; this.mph = mph; this.color = color; } }
http://www.javaprogrammingforums.com/%20java-theory-questions/22068-objects-parameters-implicit-calling-i-printingthethread.html
CC-MAIN-2015-40
refinedweb
276
72.32
Hello guys, I am testing Idea with a Lift project in maven. The project compiles and works perfect in the command line, but IDEA marks many syntax errors with java related classes within the scala code. For instance, in this line: import _root_.java.sql.{Connection, DriverManager} I receive a "cannot resolve symbol Connection" in the editor, but the line compiles and works just fine with maven in the command line. I guess I am setting something wrongly, but everything seems to be ok in the module setup. Any suggestions? Thanks in advance, GA Hello guys, Should I add something about the JDK in the pom.xml file? The JDK is informed in the Module Settings, but it is not recognized, I think. Apparently was an error in the JDK setup. I have reconfigured it and now it seems to work fine.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206641935-Many-syntax-errors-highlighted-in-the-IDE-but-compiling-perfectly-in-command-line?page=1
CC-MAIN-2020-16
refinedweb
142
72.87
This section demonstrates you the use of method list(). You can get the list of files and directories in two ways. Either by using listFiles() method or by list() method. Here we will discuss the method list() of File class. You can see in the given example, we have created an instance of File class and specify the directory path in the constructor of the File class. Then we have called the list( ) method through the File object. This method will return the array of string consisting of files and subdirectories of the given directory. list(): This method of Files class returns an array of strings naming the files and directories in the directory. Here is the code: import java.io.*; public class FileList { public static void main(String[] args) { File f = new File("C:/Text"); String str[] = f.list(); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } } Through the above code, it will be easier for you to understand the use of method list(). Advertisements Posted on: June
http://www.roseindia.net/tutorial/java/core/files/filelistmethod.html
CC-MAIN-2017-04
refinedweb
174
76.52
Flask is a Python micro web framework used to run major websites including Pintrest, Twilio, and Linkedin. This topic explains and demonstrates the variety of features Flask offers for both front and back end web development. The following example is an example of a basic server: # Imports the Flask class from flask import Flask # Creates an app and checks if its the main or imported app = Flask(__name__) # Specifies what URL triggers hello_world() @app.route('/') # The function run on the index route def hello_world(): # Returns the text to be displayed return "Hello World!" # If this script isn't an import if __name__ == "__main__": # Run the app until stopped app.run() Running this script (with all the right dependencies installed) should start up a local server. The host is 127.0.0.1 commonly known as localhost. This server by default runs on port 5000. To access your webserver, open a web browser and enter the URL localhost:5000 or 127.0.0.1:5000 (no difference). Currently, only your computer can access the webserver. app.run() has three parameters, host, port, and debug. The host is by default 127.0.0.1, but setting this to 0.0.0.0 will make your web server accessible from any device on your network using your private IP address in the URL. the port is by default 5000 but if the parameter is set to port 80, users will not need to specify a port number as browsers use port 80 by default. As for the debug option, during the development process (never in production) it helps to set this parameter to True, as your server will restart when changes made to your Flask project. if __name__ == "__main__": app.run(host="0.0.0.0", port=80, debug=True) With Flask, URL routing is traditionally done using decorators. These decorators can be used for static routing, as well as routing URLs with parameters. For the following example, imagine this Flask script is running the website. @app.route("/") def index(): return "You went to" @app.route("/about") def about(): return "You went to" @app.route("/users/guido-van-rossum") return "You went to" With that last route, you can see that given a URL with /users/ and the profile name, we could return a profile. Since it would be horribly inefficient and messy to include a @app.route() for every user, Flask offers to take parameters from the URL: @app.route("/users/<username>") def profile(username): return "Welcome to the profile of " + username cities = ["OMAHA", "MELBOURNE", "NEPAL", "STUTTGART", "LIMA", "CAIRO", "SHANGHAI"] @app.route("/stores/locations/<city>") def storefronts(city): if city in cities: return "Yes! We are located in " + city else: return "No. We are not located in " + city The two most common HTTP methods are GET and POST. Flask can run different code from the same URL dependent on the HTTP method used. For example, in a web service with accounts, it is most convenient to route the sign in page and the sign in process through the same URL. A GET request, the same that is made when you open a URL in your browser should show the login form, while a POST request (carrying login data) should be processed separately. A route is also created to handle the DELETE and PUT HTTP method. @app.route("/login", methods=["GET"]) def login_form(): return "This is the login form" @app.route("/login", methods=["POST"]) def login_auth(): return "Processing your data" @app.route("/login", methods=["DELETE", "PUT"]) def deny(): return "This method is not allowed" To simplify the code a bit, we can import the request package from flask. from flask import request @app.route("/login", methods=["GET", "POST", "DELETE", "PUT"]) def login(): if request.method == "DELETE" or request.method == "PUT": return "This method is not allowed" elif request.method == "GET": return "This is the login forum" elif request.method == "POST": return "Processing your data" To retrieve data from the POST request, we must use the request package: from flask import request @app.route("/login", methods=["GET", "POST", "DELETE", "PUT"]) def login(): if request.method == "DELETE" or request.method == "PUT": return "This method is not allowed" elif request.method == "GET": return "This is the login forum" elif request.method == "POST": return "Username was " + request.form["username"] + " and password was " + request.form["password"] Instead of typing our HTML markup into the return statements, we can use the render_template() function: from flask import Flask from flask import render_template app = Flask(__name__) @app.route("/about") def about(): return render_template("about-us.html") if __name__ == "__main__": app.run(host="0.0.0.0", port=80, debug=True) This will use our template file about-us.html. To ensure our application can find this file we must organize our directory in the following format: - application.py /templates - about-us.html - login-form.html /static /styles - about-style.css - login-style.css /scripts - about-script.js - login-script.js Most importantly, references to these files in the HTML must look like this: <link rel="stylesheet" type="text/css", which will direct the application to look for about-style.css in the styles folder under the static folder. The same format of path applies to all references to images, styles, scripts, or files. Similar to Meteor.js, Flask integrates well with front end templating services. Flask uses by default Jinja Templating. Templates allow small snippets of code to be used in the HTML file such as conditionals or loops. When we render a template, any parameters beyond the template file name are passed into the HTML templating service. The following route will pass the username and joined date (from a function somewhere else) into the HTML. @app.route("/users/<username>) def profile(username): joinedDate = get_joined_date(username) # This function's code is irrelevant awards = get_awards(username) # This function's code is irrelevant # The joinDate is a string and awards is an array of strings return render_template("profile.html", username=username, joinDate=joinDate, awards=awards) When this template is rendered, it can use the variables passed to it from the render_template() function. Here are the contents of profile.html: <!DOCTYPE html> <html> <head> # if username <title>Profile of {{ username }}</title> # else <title>No User Found</title> # endif <head> <body> {% if username %} <h1>{{ username }} joined on the date {{ date }}</h1> {% if len(awards) > 0 %} <h3>{{ username }} has the following awards:</h3> <ul> {% for award in awards %} <li>{{award}}</li> {% endfor %} </ul> {% else %} <h3>{{ username }} has no awards</h3> {% endif %} {% else %} <h1>No user was found under that username</h1> {% endif %} {# This is a comment and doesn't affect the output #} </body> </html> The following delimiters are used for different interpretations: {% ... %}denotes a statement {{ ... }}denotes an expression where a template is outputted {# ... #}denotes a comment (not included in template output) {# ... ##implies the rest of the line should be interpreted as a statement The request object provides information on the request that was made to the route. To utilize this object, it must be imported from the flask module: from flask import request In previous examples request.method and request.form were used, however we can also use the request.args property to retrieve a dictionary of the keys/values in the URL parameters. @app.route("/api/users/<username>") def user_api(username): try: token = request.args.get("key") if key == "pA55w0Rd": if isUser(username): # The code of this method is irrelevant joined = joinDate(username) # The code of this method is irrelevant return "User " + username + " joined on " + joined else: return "User not found" else: return "Incorrect key" # If there is no key parameter except KeyError: return "No key provided" To correctly authenticate in this context, the following URL would be needed (replacing the username with any username: If a file upload was part of the submitted form in a POST request, the files can be handled using the request object: @app.route("/upload", methods=["POST"]) def upload_file(): f = request.files["wordlist-upload"] f.save("/var/www/uploads/" + f.filename) # Store with the original filename The request may also include cookies in a dictionary similar to the URL parameters. @app.route("/home") def home(): try: username = request.cookies.get("username") return "Your stored username is " + username except KeyError: return "No username cookies was found")
https://sodocumentation.net/python/topic/8682/flask
CC-MAIN-2021-10
refinedweb
1,366
57.06
bca...@nvidia.com wrote on Mon, 17 Jun 2013 18:40 -0700: > From: Brandon Casey <draf...@gmail.com> > > Prior to commit fa83a33b, the 'git checkout' DWIMery would create a > new local branch if the specified branch name did not exist and it > matched exactly one ref in the "remotes" namespace. It searched > the "remotes" namespace for matching refs using a simple comparison > of the trailing portion of the remote ref names. This approach > could sometimes produce false positives or negatives. > > Since fa83a33b, the DWIMery more strictly excludes the remote name > from the ref comparison by iterating through the remotes that are > configured in the .gitconfig file. This has the side-effect that > any refs that exist in the "remotes" namespace, but do not match > the destination side of any remote refspec, will not be used by > the DWIMery. > > This change in behavior breaks the tests in t9802 which relied on > the old behavior of searching all refs in the remotes namespace, > since the git-p4 script does not configure any remotes in the > .gitconfig. Let's work around this in these tests by explicitly > naming the upstream branch to base the new local branch on when > calling 'git checkout'. Advertising Thanks for finding and fixing this. Great explanation. I tested it locally too. Acked-by: Pete Wyckoff <p...@padd.com> -- Pete -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg30006.html
CC-MAIN-2017-17
refinedweb
246
61.87
This is a Java Program to Convert a Given Number of Days in terms of Years, Weeks & Days. Enter any integer number as an input. After that we first divide the input by 365 to get number of years. After that we use modulus opeartion and division by 7 to get number of weeks. Finally we use modulo operation to get the number of days. Here is the source code of the Java Program to Convert a Given Number of Days in terms of Years, Weeks & Days. The Java program is successfully compiled and run on a Windows system. The program output is also shown below. import java.util.Scanner; public class Year_Week_Day { public static void main(String args[]) { int m, year, week, day; Scanner s = new Scanner(System.in); System.out.print("Enter the number of days:"); m = s.nextInt(); year = m / 365; m = m % 365; System.out.println("No. of years:"+year); week = m / 7; m = m % 7; System.out.println("No. of weeks:"+week); day = m; System.out.println("No. of days:"+day); } } Output: $ javac Year_Week_Day.java $ java Year_Week_Day Enter the number of days:756 No. of years:2 No. of weeks:3 No. of days:5 Sanfoundry Global Education & Learning Series – 1000 Java Programs. Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.
https://www.sanfoundry.com/java-program-convert-given-number-days-terms-years-weeks-days/
CC-MAIN-2018-13
refinedweb
223
69.48
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. ValueError: Invalid field 'is_template' in leaf "<osv.ExtendedLeaf: ('is_template', '=', True) on sale_order (ctx: )>" How can i I have created a Database with openerp-7. I have installed many csutom modules in this DB. Rescently i have downloaded odoo-7.0. When i click on sales menu, i am getting this error. Please help me. Here is a methode to patch your system if any field is missing. I used this offen before :-) 1. create new folder in your addons. Nem like repair_temp 2. create a 3 new file. - __init.__.py import sale - openerp.py { "name" : "Missing field", "version" : "0.1", "author" : "You name", "website" : "", "category" : "Generic Modules/Others", "depends" : ["base",'sale'], "description" : """repair missing field""", "init_xml" : [], "demo_xml" : [], 'update_xml': [], "images" : [], "installable": True } - sale.py class sale_order(osv.osv): _name = 'sale_order' _inherit = 'sale_order' _columns = { 'is_template':fields.boolean('Template?'), } sale_order() 3. Install your patch module >refresh the modules list in technical section, or Settings Install your new module, which name must be the folder name. Please note I didn't test it, just wrote down, please note that I use 6.1 so may it not works as well in 7.0 or 8.0. if you have any problem, please comment the trouble. U can get more info about the system if you start the Erp with --debug key. Check if you have is_template field in that model or that field doesn't exist. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now download and install this module, it will resolve that issue. quotation_template
https://www.odoo.com/forum/help-1/question/valueerror-invalid-field-is-template-in-leaf-osv-extendedleaf-is-template-true-on-sale-order-ctx-how-can-i-60085
CC-MAIN-2017-17
refinedweb
299
69.68
Really Simple Tricks to Speed up Your CLIs 10 Times Using vSphere Java API I recently had a short discussion with my colleague on implementing CLIs with vSphere Java API. One problem is that if you have multiple commands to run, each of them connects to the server and authenticate over and over. You’d better remember to logout the connection each time after you are done, or leave many un-used connections on the server that could significantly slow down your ESX or vCenter server (read this blog for details). You can have two solutions to this problem. The first one is to have your own “interpreter” command. After you type the command, it shows you prompt for more sub-commands. It’s very much like the “ftp” command in that sense. You can have subcommands like “login” or “open” or “connect” for connecting to a server, and other commands. The “interpreter” command can then hold the ServiceInstance object until it’s closed in the end. You can save about 0.3 to 0.5 second on creating new HTTPS connection and login for each command after the first one. It’s not a big deal given that vSphere Java API has hugely reduced that time from 3 to 4 seconds with Apache AXIS. So if you switch to vSphere Java API, you get instant 10 time performance gain. Still, if you have many commands to run, it could be a decent saving. With this solution, you can also implement batch mode in which you can save all your commands into a file and then execute them all with one command. You can find many examples like PowerShell which support interactive mode and batch mode. Another solution is just having normal commands. The problem becomes how to avoid the authentication for each command after the first. Luckily we have something for you in the API. The ServiceInstance type has a constructor like the following. It was originally designed for vSphere Client Plug-in which reuses the same session ID of the vSphere Client. public ServiceInstance(URL url, String sessionStr, boolean ignoreCert, String namespace) The expected session string is as follows. Note that you have to escape the ” if you include it in your Java source code. vmware_soap_session="B3240D15-34DF-4BB8-B902-A844FDF42E85" What you can do is to get the session ID and save it to a well-known temporary file. Each command checks if the file exists. If yes, it loads the session string and pass into the above constructor. By default a session expires for 30 minutes on server side. You have to guide against this in your code with normal login if that happens. “But wait, how can I get the session ID from an existing ServiceInstance?” you may ask. It’s in fact pretty easy. From any ManagedObject like ServiceInstance, you can have one line like this: String sessionStr = si.getServerConnection().getSessionStr(); It will have the same format as you would pass in to the above constructor. Hi, Steve, thanks foк this tip. Also I have another one question to you – is there any way to receive current CPU and memory usage of ESX host? I’ve thought that this info should be in properties of HostSystem, but not found it there. These are performance related stats. You may want to check out the PerformanceManager. Steve One issue that we had on our end: On calling si.getServerConnection().getSessionStr(); we got the following: vmware_soap_session=”528857ed-ae51-cb5e-ad97-0691f2fe8056″; Path=/; which as you can see has some extra characters appended to it as opposed to the version shown in the blog post. When I passed in this whole string in ServiceInstnace constructor it did gave me a ServiceInstance object but it returned null on some of the methods of ServiceInstance. To correct this issue we had to extract the session id from the string returned from this method. e.g. we used the regex: (.*”.*?”) to extract this out: vmware_soap_session=”528857ed-ae51-cb5e-ad97-0691f2fe8056″ Now, on passing this string in the constructor gives us a working ServiceInstance. Now, my question is that as we saw, on passing an incorrect session string to the constructor we still get a service instance but a wrong one, how to test if it is the right service instance? Simply checking against null fails. The ServiceInstance is a proxy on the client side. Until you try it, for example call an inexpensive method, you never know its validness. So, just call the currentTime() method. -Steve
http://www.doublecloud.org/2010/10/really-simple-tricks-to-speed-up-your-clis-10-times-using-vsphere-java-api/
CC-MAIN-2018-09
refinedweb
755
73.78
Subject: Re: [boost] [multiprecision] Are these types suitable as numerictypes for unit tests? From: Gennadiy Rozental (rogeeff_at_[hidden]) Date: 2013-06-11 02:29:50 Richard <legalize+jeeves <at> mail.xmission.com> writes: > >The names "enable_if" and "disable_if" are ambiguous > >because they are present in the namespace "boost" > >as well as in "boost::unit_test::decorator". In addition, > >there is symbol-injection via a using directive in > >Boost.Test which, although needed by Boost.Test, > >seems to cause the ambiguity. I believe these were removed. Where do you see these? > I couldn't find any code in Boost.Test that uses the decorators > enable_if and disable_if. > > They are undocumented anywhere, so I find it unlikely that any clients > of Boost.Test are depending on them from the outside. > > They look like dead code to me. They are not dead. They are brand new features I am in progress of documenting. Gennadiy Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2013/06/204551.php
CC-MAIN-2021-43
refinedweb
172
63.46
command API attributes were recently renamed in the spec: so the shadowing of attributes in derived interfaces got removed too however, we should consider to add a new attribute e.g. .commandState instead, this attribute would return an object with all these attributes see HTML5 context menu bug is not blocked by this for now (In reply to comment #1) > however, we should consider to add a new attribute e.g. .commandState > instead, this attribute would return an object with all these attributes > > see Jan, you told me Cameron and Olli agreed. I do agree too given that I did propose that solution. Does someone disagree? However, you could probably mention that solution in a W3 bug (or open a new one) and implement it here. What is the advantage of such a state object from a page author's point of view? (In reply to comment #3) > What is the advantage of such a state object from a page author's point of > view? Checking if an element is used as a command would be more natural: if (element.commandObject !== null) { } Also, checking if the browser support the feature could be done with: if (element.commandObject !== undefined) { } Which seems better than checking a random attribute or all of them. Generally speaking, it would prevent polluting HTMLElement and will remove the "command" prefix for all command API related attributes. Replace commandObject with commandType and that's exactly how the spec currently works, no? .getCommandInfo(out DOMString aType, out DOMString aLabel, ...) would be nice too however I just found out that WebIDL doesn't support "out" parameters :) sorry, I forgot to mention that it would be a good compromise IMO it doesn't pollute the namespace so much and there's no need to create a helper object. would it be possible to add support for out arguments ? Not really, since JS can't pass primitive values by reference. ok, so the original spec contained these new attributes: .commandType, .label, .icon, .disabled, .checked An objection was raised that this pollutes the event namespace (onfoo="") and it was proposed to use an object called e.g. .commandState that would contain these attributes. Now, the attributes are: .commandType, .commandLabel, .commandIcon, .commandHidden, .commandDisabled, .commandChecked They were renamed to fix other problem (shadowing of attributes). I think that authors won't use such "long" variable names in onfoo="", so it should be a bit less problematic. Actually, the editing API looks similar: execCommand() queryCommandEnabled() queryCommandIndeterm() ... Now, I'm not sure if it is good or bad :)
https://bugzilla.mozilla.org/show_bug.cgi?id=670898
CC-MAIN-2016-26
refinedweb
421
63.49
Section 12.5 Network Programming Example: A Networked Game Framework This section presents several programs that use networking and threads. The common problem in each application is to support network communication between several programs running on different computers. A typical example of such an application is a networked game with two or more players, but the same problem can come up in less frivolous applications as well. The first part of this section describes a common framework that can be used for a variety of such applications, and the rest of the section discusses three specific applications that use that framework. This is a fairly complex example, probably the most complex that you have seen so far in this book. Understanding it is not essential for a basic understanding of networking. This section was inspired by a pair of students, Alexander Kittelberger and Kieran Koehnlein, who wanted to write a networked poker game as a final project in a class that I was teaching. I helped them with the network part of the project by writing a basic framework to support communication between the players. Since the application illustrates a variety of important ideas, I decided to include a somewhat more advanced and general version of that framework in the current edition of this book. The final example is a networked poker game. 12.5.1 The Netgame Framework One can imagine playing many different games over the network. As far as the network goes, all of those games have at least one thing in common: There has to be some way for actions taken by one player to be communicated over the network to other players. It makes good programming sense to make that capability available in a reusable common core that can be used in many different games. I have written such a core; it is defined by several classes in the package netgame.common. We have not done much with packages in this book, aside from using built-in classes. Packages were introduced in Subsection 2.6.6, but we have stuck to the "default package" in our programming examples. In practice, however, packages are used in all but the simplest programming projects to divide the code into groups of related classes. It makes particularly good sense to define a reusable framework in a package that can be included as a unit in a variety of projects. Integrated development environments such as Eclipse or Netbeans make it very easy to use packages: To use the netgame package in a project in an IDE, simply copy-and-paste the entire netgame directory into the project. If you work on the command line, you should be in a working directory that includes the netgame directory as a subdirectory. Then, to compile all the java files in the package netgame.common, for example, you can use the following command in Mac OS or Linux: javac netgame/common/*.java For windows, you should use backslashes instead of forward slashes: javac netgame\common\*.java You will need similar commands to compile the source code for the examples in this section, which are defined in other subpackages of netgame. To run a main program that is defined in a package, you should again be in a directory that contains the package as a subdirectory, and you should use the full name of the class that you want to run. For example, the ChatRoomServer class, discussed later in this section, is defined in the package netgame.chat, so you would run it with the command java netgame.chat.ChatRoomServer I will have more to say about packages in the final example of the book, in Section 13.5. The applications discussed in this section are examples of distributed computing, since they involve several computers communicating over a network. Like the example in Subsection 12.4.5, they use a central "server," or "master," to which a number of "clients" will connect. All communication goes through the server; a client cannot send messages directly to another client. In this section, I will refer to the server as a hub, in the sense of "communications hub": The main things that you need to understand are that: The hub must be running before any clients are started. Clients connect the hub and can send messages to the hub. The hub processes all messages from clients sequentially, in the order in which they are received. The processing can result in the hub sending messages out to one or more clients. Each client is identified by a unique ID number. This is a framework that can be used in a variety of applications, and the messages and processing will be defined by the particular application. Here are some of the details... In Subsection 12.4.5, messages were sent back and forth between the server and the client in a definite, predetermined sequence. Communication between the server and a client was actually communication between one thread running on the server and another thread running on the client. For the netgame framework, however, I want to allow for asynchronous communication, in which it is not possible to wait for messages to arrive in a predictable sequence. To make this possible a netgame client will use two threads for communication, one for sending messages to the hub and one for receiving messages from the hub. Similarly, the netgame hub will use two threads for communicating with each client. The hub is generally connected to many clients and can receive messages from any of those clients at any time. The hub will have to process each message in some way. To organize this processing, the hub uses a single thread to process all incoming messages. When a communication thread receives a message from a client, it simply drops that message into a queue of incoming messages. There is only one such queue, which is used for messages from all clients. The message processing thread runs in a loop in which it removes a message from the queue, processes it, removes another message from the queue, processes it, and so on. The queue itself is implemented as an object of type LinkedBlockingQueue (see Subsection 12.3.3). There is one more thread in the hub, not shown in the illustration. This final thread creates a ServerSocket and uses it to listen for connection requests from clients. Each time it accepts a connection request, it hands off the client socket to another object, defined by the nested class ConnectionToClient, which will handle communication with that client. Each connected client is identified by an ID number. ID numbers 1, 2, 3, ... are assigned to clients as they connect. Since clients can also disconnect, the clients connected at any give time might not have consecutive IDs. A variable of type TreeMap<Integer,ConnectionToClient> associates the ID numbers of connected clients with the objects that handle their connections. The messages that are sent and received are objects. The I/O streams that are used for reading and writing objects are of type ObjectInputStream and ObjectOutputStream. (See Subsection 11.1.6.) The output stream of a socket is wrapped in an ObjectOutputStream to make it possible to transmit objects through that socket. The socket's input stream is wrapped in an ObjectInputStream to make it possible to receive objects. Remember that the objects that are used with such streams must implement the interface java.io.Serializable. The netgame Hub class is defined in the file Hub.java, in the package netgame.common. The port on which the server socket will listen must be specified as a parameter to the Hub constructor. The Hub class defines a method protected void messageReceived(int playerID, Object message) which is called to process the messages that are received from clients. The first parameter, playerID, is the ID number of the client from whom the message was received, and the second parameter is the message itself. In the Hub class, this method will simply forward the message to all connected clients. This defines the default processing for incoming messages to the hub. To forward the message, it wraps both the playerID and the message in an object of type ForwardedMessage (defined in the file ForwardedMessage.java, in the package netgame.common). In a simple application such as the chat room discussed in the next subsection, this default processing might be exactly what is needed by the application. For most applications, however, it will be necessary to define a subclass of Hub and redefine the messageReceived() method to do more complicated message processing. There are several other methods in the Hub class that you might want to redefine in a subclass, including - protected void playerConnected(int playerID) -- This method is called each time a player connects to the hub. The parameter playerID is the ID number of the newly connected player. In the Hub class, this method does nothing. Note that the complete list of ID numbers for currently connected players can be obtained by calling getPlayerList(). - protected void playerDisconnected(int playerID) -- This is called each time a player disconnects from the hub. The parameter tells which player has just disconnected. In the Hub class, this method does nothing. The Hub class also defines a number of useful public methods, notably - sendToAll(message) -- sends the specified message to every client that is currently connected to the hub. The message must be a non-null object that implements the Serializable interface. - sendToOne(recipientID,message) -- sends a specified message to just one user. The first parameter, recipientID is the ID number of the client who will receive the message. This method returns a boolean value, which is false if there is no connected client with the specified recipientID. - shutDownServerSocket() -- shuts down the hub's server socket, so that no additional clients will be able to connect. This could be used, for example, in a two-person game, after the second client has connected. - setAutoreset(autoreset) -- sets the boolean value of the autoreset property. If this property is true, then the ObjectOutputStreams that are used to transmit messages to clients will automatically be reset before each message is transmitted. The default value is false. (Resetting an ObjectOutputStream is something that has to be done if an object is written to the stream, modified, and then written to the stream again. If the stream is not reset before writing the modified object, then the old, unmodified value is sent to the stream instead of the new value. See Subsection 11.1.6 for a discussion of this technicality.) For more information -- and to see how all this is implemented -- you should read the source code file Hub.java. With some effort and study, you should be able to understand everything in that file. (However, you only need to understand the public and protected interface of Hub and other classes in the the netgame framework to write applications based on it.) Turning to the client side, the basic netgame client class is defined in the file Client.java, in the package netgame.common. The Client class has a constructor that specifies the host name (or IP address) and port number of the hub to which the client will connect. This constructor blocks until the connection has been established. Client is an abstract class. Every netgame application must define a subclass of Client and provide a definition for the abstract method: abstract protected void messageReceived(Object message); This method is called each time a message is received from the netgame hub to which the client is connected. A subclass of client might also override the protected methods playerConnected, playerDisconnected, serverShutdown, and connectionClosedByError. See the source code for more information. I should also note that Client contains the protected instance variable connectedPlayerIDs, of type int[], an array containing the ID numbers of all the clients that are currently connected to the hub. The most important public methods that are provided by the Client class are - send(message) -- transmits a message to the hub. The message can be any non-null object that implements the Serializable interface. - getID() -- gets the ID number that was assigned to this client by the hub. - disconnect() -- closes the client's connection to the hub. It is not possible to send messages after disconnecting. The send() method will throw an IllegalStateException if an attempt is made to do so. The Hub and Client classes are meant to define a general framework that can be used as the basis for a variety of networked games -- and, indeed, of other distributed programs. The low level details of network communication and multithreading are hidden in the private sections of these classes. Applications that build on these classes can work in terms of higher-level concepts such as players and messages. The design of these classes was developed though several iterations, based on experience with several actual applications. I urge you to look at the source code to see how Hub and Client use threads, sockets, and streams. In the remainder of this section, I will discuss three applications built on the netgame framework. I will not discuss these applications in great detail. You can find the complete source code for all three in the netgame package. 12.5.2 A Simple Chat Room Our first example is a "chat room," a network application where users can connect to a server and can then post messages that will be seen by all current users of the room. It is similar to the GUIChat program from Subsection 12.4.2, except that any number of users can participate in a chat. While this application is not a game, it does show the basic functionality of the netgame framework. The chat room application consists of two programs. The first, ChatRoomServer.java, is a completely trivial program that simply creates a netgame Hub to listen for connection requests from netgame clients: public static void main(String[] args) { try { new Hub(PORT); } catch (IOException e) { System.out.println("Can't create listening socket. Shutting down."); } } The port number, PORT, is defined as a constant in the program and is arbitrary, as long as both the server and the clients use the same port. Note that ChatRoom uses the Hub class itself, not a subclass. The second part of the chat room application is the program ChatRoomWindow.java, which is meant to be run by users who want to participate in the chat room. A potential user must know the name (or IP address) of the computer where the hub is running. (For testing, it is possible to run the client program on the same computer as the hub, using localhost as the name of the computer where the hub is running.) When ChatRoomWindow is run, it uses a dialog box to ask the user for this information. It then opens a window that will serve as the user's interface to the chat room. The window has a large transcript area that displays messages that users post to the chat room. It also has a text input box where the user can enter messages. When the user enters a message, that message will be posted to the transcript of every user who is connected to the hub, so all users see every message sent by every user. Let's look at some of the programming. Any netgame application must define a subclass of the abstract Client class. For the chat room application, clients are defined by a nested class ChatClient inside ChatRoomWindow. The program has an instance variable, connection, of type ChatClient, which represents the program's connection to the hub. When the user enters a message, that message is sent to the hub by calling connection.send(message); When the hub receives the message, it packages it into an object of type ForwardedMessage, along with the ID number of the client who sent the message. The hub sends a copy of that ForwardedMessage to every connected client, including the client who sent the message. On the client side in each client, when the message is received from the hub, the messageReceived() method of the ChatClient object in that client is called. ChatClient overrides this method to make it add the message to the transcript of the ChatClientWindow. To summarize: Every message entered by any user is sent to the hub, which just sends out copies of each message that it receives to every client. Each client will see exactly the same stream of messages from the hub. A client is also notified when a player connects to or disconnects from the hub and when the connection with the hub is lost. ChatClient overrides the methods that are called when these events happen so that they post appropriate messages to the transcript. Here's the complete definition of the client class for the chat room application: /** * A ChatClient connects to a Hub and is used to send messages to * and receive messages from the Hub. Messages received from the * Hub will be of type ForwardedMessage and will contain the * ID number of the sender and the string that was sent by that user. */ private class ChatClient extends Client { /** * Opens a connection to the chat room server on a specified computer. */ ChatClient(String host) throws IOException { super(host, PORT); } /** * Responds when a message is received from the server. It should be * a ForwardedMessage representing something that one of the participants * in the chat room is saying. The message is simply added to the * transcript, along with the ID number of the sender. */ protected void messageReceived(Object message) { if (message instanceof ForwardedMessage) { // (no other message types are expected) ForwardedMessage fm = (ForwardedMessage)message; addToTranscript("#" + fm.senderID + " SAYS: " + fm.message); } } /** * Called when the connection to the client is shut down because of some * error message. (This will happen if the server program is terminated.) */ protected void connectionClosedByError(String message) { addToTranscript("Sorry, communication has shut down due to an error:\n " + message); sendButton.setEnabled(false); messageInput.setEnabled(false); messageInput.setEditable(false); messageInput.setText(""); connected = false; connection = null; } /** * Posts a message to the transcript when someone leaves the chat room. */ protected void playerConnected(int newPlayerID) { addToTranscript("Someone new has joined the chat room, with ID number " + newPlayerID); } /** * Posts a message to the transcript when someone leaves the chat room. */ protected void playerDisconnected(int departingPlayerID) { addToTranscript("The person with ID number " + departingPlayerID + " has left the chat room"); } } // end nested class ChatClient For the full source code of the chat room application, see the source code files, which can be found in the package netgame.chat. Note: A user of my chat room application is identified only by an ID number that is assigned by the hub when the client connects. Essentially, users are anonymous, which is not very satisfying. See Exercise 12.6 at the end of this chapter for a way of addressing this issue. 12.5.3 A Networked TicTacToe Game My second example is a very simple game: the familiar children's game TicTacToe. In TicTacToe, two players alternate placing marks on a three-by-three board. One player plays X's; the other plays O's. The object is to get three X's or three O's in a row. At a given time, the state of a TicTacToe game consists of various pieces of information such as the current contents of the board, whose turn it is, and -- when the game is over -- who won or lost. In a typical non-networked version of the game, this state would be represented by instance variables. The program would consult those instance variables to determine how to draw the board and how to respond to user actions such as mouse clicks. In the networked netgame version, however, there are three objects involved: Two objects belonging to a client class, which provide the interface to the two players of the game, and the hub object that manages the connections to the clients. These objects are not even on the same computer, so they certainly can't use the same state variables! Nevertheless, the game has to have a single, well-defined state at any time, and both players have to be aware of that state. My solution is to store the "official" game state in the hub, and to send a copy of that state to each player every time the state changes. The players can't change the state directly. When a player takes some action, such as placing a piece on the board, that action is sent as a message to the hub. The hub changes the state to reflect the result of the action, and it sends the new state to both players. The window used by each player will then be updated to reflect the new state. In this way, we can be sure that the game always looks the same to both players. (Instead of sending a complete copy of the state each time the state changes, I might have sent just the change. But that would require some way to encode the changes into messages that can be sent over the network. Since the state is so simple, it seemed easier just to send the entire state as the message in this case.) Networked TicTacToe is defined in several classes in the package netgame.tictactoe. TicTacToeGameState represents the state of a game. It includes a method public void applyMessage(int senderID, Object message) that modifies the state to reflect the effect of a message received from one of the players of the game. The message will represent some action taken by the player, such as clicking on the board. The basic Hub class knows nothing about TicTacToe. Since the hub for the TicTacToe game has to keep track of the state of the game, it has to be defined by a subclass of Hub. The TicTacToeGameHub class is quite simple. It overrides the messageReceived() method so that it responds to a message from a player by applying that message to the game state and sending a copy of the new state to both players. It also overrides the playerConnected() and playerDisconnected() methods to take appropriate actions, since the game can only be played when there are exactly two connected players. Here is the complete source code: package netgame.tictactoe; import java.io.IOException; import netgame.common.Hub; /** * A "Hub" for the network TicTacToe game. There is only one Hub * for a game, and both network players connect to the same Hub. * Official information about the state of the game is maintained * on the Hub. When the state changes, the Hub sends the new * state to both players, ensuring that both players see the * same state. */ public class TicTacToeGameHub extends Hub { private TicTacToeGameState state; // Records the state of the game. /** * Create a hub, listening on the specified port. Note that this * method calls setAutoreset(true), which will cause the output stream * to each client to be reset before sending each message. This is * essential since the same state object will be transmitted over and * over, with changes between each transmission. * @param port the port number on which the hub will listen. * @throws IOException if a listener cannot be opened on the specified port. */ public TicTacToeGameHub(int port) throws IOException { super(port); state = new TicTacToeGameState(); setAutoreset(true); } /** * Responds when a message is received from a client. In this case, * the message is applied to the game state, by calling state.applyMessage(). * Then the possibly changed state is transmitted to all connected players. */ protected void messageReceived(int playerID, Object message) { state.applyMessage(playerID, message); sendToAll(state); } /** * This method is called when a player connects. If that player * is the second player, then the server's listening socket is * shut down (because only two players are allowed), the * first game is started, and the new state -- with the game * now in progress -- is transmitted to both players. */ protected void playerConnected(int playerID) { if (getPlayerList().length == 2) { shutdownServerSocket(); state.startFirstGame(); sendToAll(state); } } /** * This method is called when a player disconnects. This will * end the game and cause the other player to shut down as * well. This is accomplished by setting state.playerDisconnected * to true and sending the new state to the remaining player, if * there is one, to notify that player that the game is over. */ protected void playerDisconnected(int playerID) { state.playerDisconnected = true; sendToAll(state); } } A player's interface to the game is represented by the class TicTacToeWindow. As in the chat room application, this class defines a nested subclass of Client to represent the client's connection to the hub. One interesting point is how the client responds to a message from the hub. Such a message represents a new game state. When the message is received, the window must be updated to show the new state. The message is received and processed by one thread; the updating is done in another thread. This has the potential of introducing race conditions that require synchronization. (In particular, as I was developing the program, I found that it was possible for a message to be received before the window's constructor had finished executing. This led to a very hard-to-diagnose bug because my response to the message was trying to use objects that had not yet been created.) When working with the Swing API, it is recommended that all modifications to the GUI be made in the GUI event thread. An alternative would be to make paintComponent() and other methods synchronized, but that would negatively impact the performance of the GUI. Swing includes a method SwingUtilitites.invokeLater(runnable) to make it possible to run arbitrary code in the GUI event thread. See Subsection 12.2.5. In the TicTacToe client class, this technique is used in the method that processes events received from the hub: protected void messageReceived(final Object message) { if (message instanceof TicTacToeGameState) { SwingUtilities.invokeLater(new Runnable(){ public void run() { // The newState() method updates the GUI for the new state. newState( (TicTacToeGameState)message ); } }); } } To run the TicTacToe netgame, the two players should each run the program Main.java in the package netgame.tictactoe. This program presents the user with a dialog box where the user can choose to start a new game or to join an existing game. If the user starts a new game, then a TicTacToeHub is created to manage the game, and a TicTacToeWindow is created that immediately connects to the hub. The game will start as soon as a second player connects to the hub. On the other hand, if the user running TicTacToeWindow chooses to connect to an existing game, then no hub is created. A window is created, and that window connects to the hub that was created by the first player. The second player has to know the name of the computer where the first player's program is running. As usual, for testing, you can run everything on one computer and use "localhost" as the computer name. 12.5.4 A Networked Poker Game And finally, we turn very briefly to the application that inspired the netgame framework: Poker. In particular, I have implemented a two-player version of the traditional "five card draw" version of that game. This is a rather complex application, and I do not intend to say much about it here other than to describe the general design. The full source code can be found in the package netgame.fivecarddraw. To fully understand it, you will need to be familiar with the game of five card draw poker. And it uses some techniques from Section 13.1 for drawing the cards. In general outline, the Poker game is similar to the TicTacToe game. There is a Main class that is one by both players. The first player starts a new game; the second must join that existing game. There is a class PokerGameState to represent the state of a game. And there is a subclass, PokerHub, of Hub to manage the game. But Poker is a much more complicated game than TicTacToe, and the game state is correspondingly more complicated. It's not clear that we want to broadcast a new copy of the complete game state to the players every time some minor change is made in the state. Furthermore, it doesn't really make sense for both players to know the full game state -- that would include the opponent's hand and full knowledge of the deck from which the cards are dealt. (Of course, our client programs wouldn't have to show the full state to the players, but it would be easy enough for a player to substitute their own client program to enable cheating.) So in the Poker application, the full game state is known only to the PokerHub. A PokerGameState object represents a view of the game from the point of view of one player only. When the state of the game changes, the PokerHub creates two different PokerGameState objects, representing the state of the game from each player's point of view, and it sends the appropriate game state objects to each player. You can see the source code for details. (One of the hard parts in poker is to implement some way to compare two hands, to see which is higher. In my game, this is handled by the class PokerRank. You might find this class useful in other poker games.)
http://math.hws.edu/javanotes/c12/s5.html
CC-MAIN-2016-07
refinedweb
4,897
62.58
Part of a larger open source project called D.I.N.A. the at-a-glance IoT notification device. Check it out here:-... Link to code mentioned in this instructable: This build will show you how to successfully use the Arduino Yun to run a python program to integrate in with the google maps matrix API and create a visual display of your commute time. The neopixel will go from green -> yellow -> red based on the range you set for good traffic to bad traffic. The function will run every 5 minutes and continue to keep you updated and let you know if you need to find a detour! I will try to be detailed with the build involving the electrical components and getting the program running correctly, I won't be explaining too much about the enclosure. I encourage you to get creative with your own enclosure design, but just in case I will provide the STL files for my design. You will learn: - How to use the bridge library and the built in process functionality. - How to do basic NEOPIXEL color changes and for loops to create a dial - How to create a basic python script to make http get requests. - How to parse JSON api responses - Finally how to retrieve those responses via serial communication and display the values in a neat way! Step 1: Hardware and Components Electronics - Arduino Yun - Neopixel (ring or strip would work) in this example I use a 24 LED ring - Minimum 1A 5V power supply - Decent size capacitor - SD Card (optional) Hardware - 3d Printed Parts - Mainbase - Toplid - Clearacrylic_1 and _2 - Blackacrylic_1 - Protoboard or small breadboard for connections Additional - The main version of DINA has a button because it supports multiple modes. If you would like to learn more about how to switch between modes and add a button to this build please comment. Step 2: Wiring If you are using the Neopixel ring you will need to solder wires onto the connections for pwr, gnd, and in. In this example I am using pin 7 for the neopixel. Also make sure you get the polarity correct if using a polarized capacitor. Why use a capacitor? If you are using a trusted and well made power supply you can probably get away with not using it but if you are using a cheaper supply or a large bench top supply you will want to use a capacitor to help with voltage spikes. Step 3: Setting Up the Yun Although probably not required for this project it is usually best to follow these instructions to expand the Yun's disk space... you will definitly want to do this if you plan on going further on the linux side trying to implement things like Nodejs. Setting up the Arduino Yun: First things first you need to get the Yun connected to the internet. Right out of the box if you power up the Yun it will start in what is called AP mode. In this mode the Yun is acting like it's own server allowing you to connect directly to the device via wifi. - Turn the yun on (powered either by usb or pwr supply) find the Yun's wifi on your computer it with be "Yun-....." - Connect to that network. - In your browser go to or if that doesn't work try 192.168.240.1 - This should pull up the yun's setup page, the default password is "arduino" - Click configure, set a new password. - Under the wireless parameters find your home network and enter in the network details. Finally click "Configure and Restart" - At this point if all goes well the Arduino will automatically switch to station mode and connect to your network. To make sure it is connected wait a couple minutes then go back to your browser and enter and it should bring up the same login screen. If it doesn't then it most likely didn't connect correctly. If this happens press and hold the wifi rst button on the yun for over 5 sec and it will kick back into AP mode. - Now you are connected to the internet and ready to start coding! Step 4: Creating the Google Maps API Integration First you will need to get a key from Google in order to access their google maps API. In order to do this you will need to create a project, enable the API, and get a key. It is pretty straight forward once you are there and click around a bit:... We will specifically be using the Distance Matrix API to determine the current travel times. We are specifically going to be looking to capture the duration_in_traffic value. If you are unfamiliar with assembling the URL for the request I highly suggest downloading a software called Postman with will allow you to copy over one the examples from this page:... run it with your key, and change parameters until you get the correct response. This software also gives you a chance to quickly see what google returns. Here is an example of the url I am using for my request (add your key to this): <p><a href="" rel="nofollow"></a>aps/api/distancematrix/json?units=imperial&origins=10+1st+St+Austin+Texas+7874&destinations=20+University+Pkwy+Round+Rock+Texas+78681&traffic_model=best_guess&key="ADD YOUR KEY HERE, DELETE THE QUOTES"&departure_time=now</p> So now we need to put this into a python function that we will run on the Linux portion of the Yun. This part is actually very simple because this type of API call requires no authorization. import urllib2<br>import json import sys response = urllib2.urlopen('ADD THE URL FROM ABOVE HERE WITH YOUR PARAMETERS AND KEY') data = json.load(response) ttime = data['rows'][0]['elements'][0]['duration_in_traffic']['value'] print (ttime) sys.exit() Now you need to get this python file uploaded into the Yun. The best way to do this on windows is using WinSCP. Once you have WinSCP installed, connect to the Yun with SCP protocol, host-name: arduino.local, and port 22. You should be prompted to log in using root and the password you setup prior. Once logged in navigate to /mnt/sda1/arduino/www/python and then upload your python file to this folder. This assumes that you have an SD card mounted. If not, then you can put the file in a different folder (ex. root) and change the code in the next step to reflect that different path. Step 5: Programming the Atmel Code Using Arduino IDE The comments in this program do a pretty good job at explaining how this program works. To upload this sketch open the Arduino IDE and either connect to your Yun using a virtual port or USB. These options will show when you go to tools->port. If you don't see anything here check the usb connection or ensure that your yun is connected to the same wifi network. You may need to add some of these libraries (neopixel for sure) before you can successfully execute the code. To do this go to sketch -> include library -> manage libraries. Then add the libraries list at the top of the sketch file attached. This program will do the following: - Initiate a bridge process with the linux processor, send a request to run the python code at startup and every 5 minutes. - It will then monitor the serial communication and save any value that comes across into an array. This array is set to a variable and is then run through values specified for time ranges. - It will run a fun loading screen while that python code is running, it will clear all the LEDs, and then run the full color with dial mode. - This mode will create a color that corresponds the to the ranges specified. Usually green for low time, red for longest, and several colors in between. - This program will also turn the neopixel into a dial and only change pixels up to a certain level based on the time returned from the check. Enjoy not getting stuck in traffic! Runner Up in the Microcontroller Contest 2017 10 Discussions 2 years ago Cool! Is this just for home, or is it for in the car use? Reply 2 years ago Thanks! It was intended for home because it requires wifi, but if you hotspotted your phone and got decent size 12V to 5V converter I don't see why it wouldn't work. Reply 2 years ago Re: 12v to 5v - Any usb convertor for the car can do that. What's the amperage? Reply 2 years ago With the 24 pixel ring it pulls on average 500-700mA. I power mine with a 1A pwr supply but I would maybe consider 1.5A just in case. 2 years ago Your video shows green light for a "good" commute. Does it change to yellow, then red as the commute gets longer? If not, consider this a suggestion. Not that I would have ever seen green when I commuted through Downtown Los Angeles (though that was way back in the 80s). Also, you could add an extra "lower" commute level for urbanites that would release a small amount of a foul odor with the verbal admonition "go back to bed!" when the commute was going to be impossible :) Reply 2 years ago Hey Cliffystones, how it is programmed now it will go from red -> orange -> yellow -> green. And yeah definitly need to add a feature in v2 to cure that LA traffic! 2 years ago Amazing!!! 2 years ago Useful idea; I'll have to give it a try sometime! 2 years ago Cool idea. You've got my vote. Reply 2 years ago Thanks!
https://mobile.instructables.com/id/Commute-Travel-Time-LED-Indicator/
CC-MAIN-2019-18
refinedweb
1,631
71.24
Results 1 to 1 of 1 Thread: Trying a simple OpenGL program Trying a simple OpenGL program - Member Since - Feb 13, 2009 - 1 Hi, I am trying to achieve something very simple, but it seems I'm still doing something wrong... I try to get the version etc what OpenGL reports. How can I properly do this? I have this at the moment: Code: #include <AGL/agl.h> #include <stdio.h> int main ( ) { GLint attribs[] = { AGL_RGBA, // 1 AGL_DOUBLEBUFFER, AGL_SAMPLE_BUFFERS_ARB, 1, AGL_SAMPLES_ARB, 2, AGL_SUPERSAMPLE, AGL_NO_RECOVERY, AGL_NONE }; AGLPixelFormat pixelFormat = NULL; AGLContext context = NULL; pixelFormat = aglChoosePixelFormat (NULL, 0, attribs); // 2 if (pixelFormat) { context = aglCreateContext (pixelFormat, NULL); // 3 printf( "%s\n", glGetString(GL_VENDOR) ); aglDestroyPixelFormat (pixelFormat); } return 1; } Code: g++ -framework OpenGL -framework AGL test.cpp && ./a.out Code: (null) What did I do wrong? Thanks a lot! Thread Information Users Browsing this Thread There are currently 1 users browsing this thread. (0 members and 1 guests) Similar Threads Simple CAD programBy sra4ever in forum Images, Graphic Design, and Digital PhotographyReplies: 3Last Post: 02-06-2013, 12:03 PM Simple Drawing ProgramBy jehan in forum Switcher HangoutReplies: 2Last Post: 11-16-2011, 06:43 AM Help with simple program for terminalBy NOYB111 in forum OS X - Operating SystemReplies: 13Last Post: 01-10-2011, 12:19 PM Simple xCode ProgramBy dTwizy in forum OS X - Development and DarwinReplies: 3Last Post: 08-13-2008, 04:55 AM Need simple DJ program-help!By Festus in forum Music, Audio, and PodcastingReplies: 5Last Post: 12-07-2007, 01:43 PM
http://www.mac-forums.com/forums/os-x-development-darwin/141317-trying-simple-opengl-program.html
CC-MAIN-2016-18
refinedweb
251
50.67
Background According to wikipedia, the Sexual Compulsivity Scale (SCS) is a psychometric measure of high libido, hypersexuality, and sexual addiction. While it does not say anything about the score itself, it is based on people rating 10 questions from 1 to 4. The questions are the following. Q1. My sexual appetite has gotten in the way of my relationships. Q2. My sexual thoughts and behaviors are causing problems in my life. Q3. My desires to have sex have disrupted my daily life. Q4. I sometimes fail to meet my commitments and responsibilities because of my sexual behaviors. Q5. I sometimes get so horny I could lose control. Q6. I find myself thinking about sex while at work. Q7. I feel that sexual thoughts and feelings are stronger than I am. Q8. I have to struggle to control my sexual thoughts and behavior. Q9. I think about sex more than I would like to. Q10. It has been difficult for me to find sex partners who desire having sex as much as I want to. The questions are rated as follows (1=Not at all like me, 2=Slightly like me, 3=Mainly like me, 4=Very much like me). A dataset of more than 3300+ responses can be found here, which includes the individual rating of each questions, the total score (the sum of ratings), age and gender. Step 1: First inspection of the data. The first question that pops into my mind is how men and women rate themselves differently. How can we efficiently figure that out? Welcome to NumPy. It has a built-in csv reader that does all the hard work in the genfromtxt function. import numpy as np data = np.genfromtxt('scs.csv', delimiter=',', dtype='int') # Skip first row as it has description data = data[1:] men = data[data[:,11] == 1] women = data[data[:,11] == 2] print("Men average", men.mean(axis=0)) print("Women average", women.mean(axis=0)) Dividing into men and women is easy with NumPy, as you can make a vectorized conditional inside the dataset. Men are coded with 1 and women with 2 in column 11 (the 12th column). Finally, a call to mean will do the rest. Men average [ 2.30544662 2.2453159 2.23485839 1.92636166 2.17124183 3.06448802 2.19346405 2.28496732 2.43660131 2.54204793 23.40479303 1. 32.54074074] Women average [ 2.30959164 2.18993352 2.19088319 1.95916429 2.38746439 3.13010446 2.18518519 2.2991453 2.4985755 2.43969611 23.58974359 2. 27.52611586] Interestingly, according to this dataset (which should be accounted for accuracy, where 21% of answers were not used) women are scoring slighter higher SCS than men. Men rate highest on the following question: Q6. I find myself thinking about sex while at work. While women rate highest on this question. Q6. I find myself thinking about sex while at work. The same. Also the lowest is the same for both genders. Q4. I sometimes fail to meet my commitments and responsibilities because of my sexual behaviors. Step 2: Visualize age vs score I would guess that the SCS score decreases with age. Let’s see if that is the case. Again, NumPy can do the magic easily. That is prepare the data. To visualize it we use matplotlib, which is a comprehensive library for creating static, animated, and interactive visualizations in Python. import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('scs.csv', delimiter=',', dtype='int') # Skip first row as it has description data = data[1:] score = data[:,10] age = data[:,12] age[age > 100] = 0 plt.scatter(age, score, alpha=0.05) plt.show() Resulting in this plot. It actually does not look like any correlation. Remember, there are more young people responding to the survey. Let’s ask NumPy what it thinks about correlation here? Luckily we can do that by calling the corrcoef function, which calculates the Pearson product-moment correlation coefficients. print("Correlation of age and SCS score:", np.corrcoef(age, score)) Resulting in this output. Correlation of age and SCS score: [[1. 0.01046882] [0.01046882 1. ]] Saying no correlation, as 0.0 – 0.3 is a small correlation, hence, 0.01046882 is close to none. Does that mean the the SCS score does not correlate with age? That our SCS score is static through life? I do not think we can conclude that based on this small dataset. Step 3: Bar plot the distribution of scores It also looked like in the graph we plotted that there was a close to even distribution of scores. Let’s try to see that. Here we need to sum participants by group. NumPy falls a bit short here. But let’s keep the good mood and use plain old Python lists. import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('scs.csv', delimiter=',', dtype='int') # Skip first row as it has description data = data[1:] scores = [] numbers = [] for i in range(10, 41): numbers.append(i) scores.append(data[data[:, 10] == i].shape[0]) plt.bar(numbers, scores) plt.show() Resulting in this bar plot. We knew that the average score was around 23, which could give a potential evenly distribution. But it seems to be a little lower in the far high end of SCS score. For another great tutorial on NumPy check this one out, or learn some differences between NumPy and Pandas.
https://www.learnpythonwithrune.org/numpy-how-does-sexual-compulsivity-scale-correlate-with-men-women-or-age/
CC-MAIN-2021-25
refinedweb
905
68.47
How to do I change the USB camera resolution? Hi, you should ask your question on NVIDIA's devtalk forum, since this page only really gets viewed by me and Bill. Anyway since you're obviously trying many things about your camera resolution problem, there are several things that can effect camera resolution, but since you didn't mention it I'll mention that you should try setting the resolution at runtime in OpenCV, in case that works: #include <stdio.h> // Include OpenCV's C++ Interface #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { VideoCapture camera; printf("Accessing camera 0 ...\n"); camera.open(0); if ( !camera.isOpened() ) { cerr << "ERROR: Could not access camera " << 0 << " !" << endl; exit(1); } // Try to set the camera resolution. Note that this only works for some cameras on // some computers and only for some drivers, so don't rely on it to work! camera.set(CV_CAP_PROP_FRAME_WIDTH, 1920); camera.set(CV_CAP_PROP_FRAME_HEIGHT, 1080); processImages(camera); return 0; } If that doesn't work, it might be because USB2.0 doesn't normally support 1920x1080 video unless if the video is compressed by the webcam hardware, and so the driver and/or your code needs to grab compressed video frames and decompress them. Ideally V4L2 does that for you seemlessly, but sometimes it needs some configuration for it to work. Some sample commands for setting resolution on command-line before running your OpenCV program: v4l2-ctl --set-fmt-video=width=1920,height=1080,pixelformat=YUYV v4l2-ctl --set-fmt-video=width=1920,height=1088,pixelformat=4 # For Raspberry Pi Cam v4l2-ctl -v width=1280,height=720,pixelformat=BGR3 Or you can try building Gstreamer into your OpenCV library then use Gstreamer to grab the camera frame and pass it to OpenCV. It actually just needs changing 1 line of your code if you do it that way, but takes some time playing with Gstreamer for it to work. If you have any issues, post them on the devtalk Jetson TK1 forum. Good luck! - Shervin.
https://elinux.org/Thread:Talk:Jetson/Cameras/How_to_do_I_change_the_USB_camera_resolution%3F/reply
CC-MAIN-2019-30
refinedweb
339
60.24
NAME vm_page_grab - returns a page from an object SYNOPSIS #include <sys/param.h> #include <vm/vm.h> #include <vm/vm_page.h> vm_page_t vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags); DESCRIPTION The vm_page_grab() function returns the page at pindex from the given object. If the page exists and is busy, vm_page_grab() will sleep while waiting for it. If the page does not exist, it is allocated. If VM_ALLOC_RETRY is not set in allocflags and the function sleeps, either getting the page from the object or while allocating it, NULL is returned. RETURN VALUES If successful, vm_page_grab() returns the page; otherwise, NULL is returned. SEE ALSO vm_page_alloc(9) AUTHORS This manual page was written by Chad David 〈davidc@acns.ab.ca〉.
http://manpages.ubuntu.com/manpages/karmic/man9/vm_page_grab.9freebsd.html
CC-MAIN-2015-27
refinedweb
119
59.3
Opened 13 years ago Closed 12 years ago #1421 closed enhancement (wontfix) Enable AttributeError reporting in template rendering Description This bugs me a while. When exception is thrown inside model function not traceback or any indication is given (with DEBUG=True), for example (m-r): class Foo(models.Model) def bar(self): raise SomeException() will return nothing (None) with *no indication* that error is occurred! Which leads to mysterious errors or missing data without any indication what is happened. So I got accustomed to write something like this: class Foo(models.Model) def bar(self): try: raise SomeException() except Exception, err: return str(err) to, at least, get some indication (as a text returned from function) when error is occurred. Any solutions or plans for this? Change History (6) comment:1 Changed 13 years ago by comment:2 Changed 13 years ago by I hit this with get_admin_url in the LogEntry #1417. Instead of raising attribute error it's silently fails. example (m-r): def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ try: return "%s/%s/%s/" % (self.content_type.app_label1, self.content_type.model, self.object_id) except Exception, err: return str(err) (note self.content_type.app_label1) If I don't use try..except block I only get empty href's in admin instead od AttributeError. Perhaps you're dealing with the template system here? The template system automatically catches exceptions when rendering content... If I understood corrrectly, any exception which is raised inside template rendering like <a href="{{ entry.get_admin_url }}"> will be silently ignored? This type of behavior can produce some hard to find errors which will be trivial to fix if exception is reported. comment:3 Changed 13 years ago by Update: It's seems to be a problem only with AttributeError, other exceptions are reported. IIRC template system ignores AttributeError and treat them as a blank (which is a Good Thing), but in cases like this it can be very confusing. Maybe we can add some flag which will stop ignoring AttributeError in template code for debugging purporses? comment:4 Changed 12 years ago by comment:5 Changed 12 years ago by comment:6 Changed 12 years ago by There are lots of places in Django that rely on AttributeError being handled as it is. If you want to try and debug particular cases, set TEMPLATE_STRING_IF_INVALID to something non-empty. There's not much else we can do here. I cannot reproduce this. In my test, the SomeExceptionexception was raised just fine. I tested that on magic-removal. Perhaps you're dealing with the template system here? The template system automatically catches exceptions when rendering content...
https://code.djangoproject.com/ticket/1421
CC-MAIN-2019-18
refinedweb
454
57.87
You can use the best practices listed here as a quick reference of what to keep in mind when building an application that uses Cloud Datastore. If you are just starting out with Cloud Datastore, this page might not be the best place to start, because it does not teach you the basics of how to use Cloud Datastore. If you are a new user, we suggest that you start with Getting Started with Cloud Datastore. General - Always use UTF-8 characters for namespace names, kind names, property names, and custom key names. Non-UTF-8 characters used in these names can interfere with Cloud Datastore - Group highly related data in entity groups. Entity groups enable ancestor queries, which return strongly consistent results. Ancestor queries also rapidly scan an entity group with minimal I/O because the entities in an entity group are stored at physically close places on Cloud Datastore servers. - Avoid writing to an entity group more than once per second. Writing at a sustained rate above that limit makes eventually consistent reads more eventual, leads to time outs for strongly consistent reads, and results in slower overall performance of your application. A batch or transactional write to an entity group counts as only a single write against this limit. - Do not include the same entity (by key) multiple times in the same commit. Including the same entity multiple times in the same commit could impact Cloud Datastore Cloud Datastore backup into Google Cloud Datastore Cloud Datastore latency. To avoid the issue of sequential numeric IDs, obtain numeric IDs from the allocateIds()method. The allocateIds()method generates well-distributed sequences of numeric IDs. By specifying a key or storing the generated name, you can later perform a consistent lookup()on that entity without needing issue a query to find the entity. Indexes - If a property will never be needed for a query, exclude the property from indexes. Unnecessarily indexing a property could result in increased latency to achieve consistency, and increased storage costs of index entries. - Avoid having too many composite indexes. Excessive use of composite indexes could result in increased latency to achieve consistency, and increased storage costs of index entries. If you need to execute ad hoc queries on large datasets without previously defined indexes, use Google BigQuery. - Do not index properties with monotonically increasing values (such as a NOW()timestamp). Maintaining such an index could lead to hotspots that impact Cloud Datastore. - If you need strong consistency for your queries, use an ancestor query. (To use ancestor queries, you first need to structure your data for strong consistency.) An ancestor query returns strongly consistent results. Note that a non-ancestor keys-only query followed by a lookup()does not return strong results, because the non-ancestor keys-only query could get results from an index that is not consistent at the time of the query. Designing for scale Updates to a single entity group A single entity group in Cloud Datastore should not be updated too rapidly. If you are using Cloud Datastore, Google recommends that you design your application so that it will not need to update an entity group more than once per second. Remember that an entity with no parent and no children is its own entity group. If you update an entity group too rapidly then your Cloud Datastore writes will have higher latency, timeouts, and other types of error. This is known as contention. Cloud Datastore write rates to a single entity group can sometimes exceed the one per second limit so load tests might not show this problem. Some suggestions for designing your application to reduce write rates on entity groups are in the Cloud Datastore contention article. High read/write rates to a narrow key range Avoid high read or write rates to Cloud Datastore keys that are lexicographically close. Cloud Datastore is built on top of Google's NoSQL database, Bigtable, and is subject to Bigtable's performance characteristics. Bigtable scales by sharding rows onto separate tablets, and these rows are lexicographically ordered by key. If you are using Cloud Datastore, you can get slow writes due to a hot tablet if you have a sudden increase in the write rate to a small range of keys that exceeds the capacity of a single tablet server. Bigtable will eventually split the key space to support high load. The limit for reads is typically much higher than for writes, unless you are reading from a single key at a high rate. Bigtable cannot split a single key onto more than one tablet. Hot tablets can apply to key ranges used by both entity keys and indexes. In some cases, a Cloud Datastore hotspot can have wider impact to an application than preventing reads or writes to a small range of keys. For example, the hot keys might be read or written during instance startup, causing loading requests to fail. By default, Cloud Datastore allocates keys using a scattered algorithm. Thus you will not normally encounter hotspotting on Cloud Datastore writes. Cloud Datastore prepends the namespace and the kind of the root entity group to the Bigtable row key. You can hit a hotspot if you start to write to a new namespace or kind without gradually ramping up traffic.. For a more detailed explanation of this issue, see Ikai Lan's blog posting on saving monotonically increasing values in Cloud Datastore. Ramping up traffic Gradually ramp up traffic to new Cloud Datastore kinds or portions of the keyspace. You should ramp up traffic to new Cloud Datastore kinds gradually in order to give Bigtable sufficient time to split tablets as the traffic grows. We recommend a maximum of 500 operations per second to a new Cloud Datastore. Bigtable might be unable to efficiently split tablets if the keyspace is sparse. Bigtable Cloud Datastore costs incurred. Deletions Avoid deleting large numbers of Cloud Datastore entities across a small range of keys. Bigtable periodically rewrites its tables to remove deleted entries, and to reorganize your data so that reads and writes are more efficient. This process is known as a compaction. If you delete a large number of Cloud Datastore for hot Cloud Datastore keys. You can use replication if you need to read a portion of the key range at a higher rate than Bigtable permits. Using this strategy, you would store N copies of the same entity allowing N times higher rate of reads than supported by a single entity. You can use sharding if you need to write to a portion of the key range at a higher rate than Bigtable permits. Sharding breaks up an entity into smaller pieces. The principles are explained in the sharding counters article. - Learn about Google Cloud Platform Best Practices for Enterprise Organizations.
https://cloud.google.com/datastore/docs/cloud-datastore-best-practices?hl=ja
CC-MAIN-2019-39
refinedweb
1,132
61.97
15.5. A bit of number theory many number-theory-related routines: obtaining prime numbers, integer decompositions, and much more. We will show a few examples here. Getting ready To display legends using LaTeX in matplotlib, you will need an installation of LaTeX on your computer (see this chapter's introduction). How to do it... 1. Let's import SymPy and the number theory package: from sympy import * import sympy.ntheory as nt init_printing() 2. We can test whether a number is prime: nt.isprime(2017) True 3. We can find the next prime after a given number: nt.nextprime(2017) 4. What is the 1000th prime number? nt.prime(1000) 5. How many primes less than 2017 are there? nt.primepi(2017) 6. We can plot \(\pi(x)\), the prime-counting function (the number of prime numbers less than or equal to some number \(x\)). The prime number theorem states that this function is asymptotically equivalent to \(x/\log(x)\). This expression approximately quantifies the distribution of prime numbers among all integers: import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.arange(2, 10000) fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.plot(x, list(map(nt.primepi, x)), '-k', label='$\pi(x)$') ax.plot(x, x / np.log(x), '--k', label='$x/\log(x)$') ax.legend(loc=2) 7. Let's compute the integer factorization of a number: nt.factorint(1998) 2 * 3**3 * 37 8. Finally, a small problem. A lazy mathematician is counting his marbles. When they are arranged in three rows, the last column contains one marble. When they form four rows, there are two marbles in the last column, and there are three with five rows. How many marbles are there? (Hint: The lazy mathematician has fewer than 100 marbles.) The Chinese Remainder Theorem gives us the answer: from sympy.ntheory.modular import solve_congruence solve_congruence((1, 3), (2, 4), (3, 5)) There are infinitely many solutions: 58 plus any multiple of 60. Since there are less than 100 marbles, 58 is the right answer. How it works... SymPy contains many number-theory-related functions. Here, we used the Chinese Remainder Theorem to find the solutions of the following system of arithmetic equations: The triple bar is the symbol for modular congruence. Here, it means that \(m_i\) divides \(a_i - n\). In other words, \(n\) and \(a_i\) are equal up to a multiple of \(m_i\). Reasoning with congruences is very convenient when periodic scales are involved. For example, operations involving 12-hour clocks are done modulo 12. The numbers 11 and 23 are equivalent modulo 12 (they represent the same hour on the clock) because their difference is a multiple of 12. In this recipe's example, three congruences have to be satisfied: the remainder of the number of marbles in the division with 3 is 1 (there's one extra marble in that arrangement), it is 2 in the division with 4, and 3 in the division with 5. With SymPy, we simply specify these values in the solve_congruence() function to get the solutions. The theorem states that solutions exist as soon as the \(m_i\) are pairwise co-prime (any two distinct numbers among them are co-prime). All solutions are congruent modulo the product of the \(m_i\). This fundamental theorem in number theory has several applications, notably in cryptography. There's more... Here are a few textbooks about number theory: - Undergraduate level: Elementary Number Theory, Gareth A. Jones, Josephine M. Jones, Springer, (1998) - Graduate level: A Classical Introduction to Modern Number Theory, Kenneth Ireland, Michael Rosen, Springer, (1982) Here are a few references: - Documentation on SymPy's number-theory module, available at - The Chinese Remainder Theorem on Wikipedia, at - Applications of the Chinese Remainder Theorem, given at - Number theory lectures on Awesome Math, at
https://ipython-books.github.io/155-a-bit-of-number-theory-with-sympy/
CC-MAIN-2019-09
refinedweb
636
58.99
Simple Reverse Geocoding with CouchDB December 2, 2010 5 Comments Real world reverse geocoding searches require minimum of three parameters, two for location (lat, lon) and a filter. Filter can be keyword, type of location, name or something else. Common use case is to find nearest restaurants or closest address. This kind of query is simple for relational database (though not necessarily easy to shard) and the problem has been solved cleanly in many of them. (PostGIS, MySQL Spatial extensions, ..) Geocoding is trickier to implement in typical NoSQL database that supports only one dimensional key range queries. Geohashes are classical solution, but in my experience they are too inaccurate for dense data. Simple method that works quite well are geoboxes, where earth is divided to grid that is used as index lookup table. Every location maps to a box that can be addressed with unique id. This is experiment to implement simple geobox based geocoding on CouchDB from scratch. I assume you’re already familiar with CouchDB basics. The examples here are written with Python with couchdb-python client library. 1. Preparations First we need geobox function that quantizes location coordinates to a list of boxes. Boxes cover the earth as grid. Latitude and location are quantized to coordinates that present geobox center on desired resolution. from decimal import Decimal as D D1 = D('1') def geobox(lat, lng, res): def _q(c): return (c / res).quantize(D1) * res return (_q(lat), _q(lng)) Based on this function, we define a function that computes the geobox and its neighbors and retuns list of strings. import math def geonbr(lat, lon, res): blat,blon = geobox(lat, lon, res) boxes = [(dlat, dlon) for dlon in [blon - res, blon, blon + res] for dlat in [blat - res, blat, blat + res]] def _bf(box): (dlat, dlon) = box return math.fabs(dlon - lon) < float(res)*0.8 \ and math.fabs(dlat - lat) < float(res)*0.8 return filter(_bf, boxes) def geoboxes(lat, lon, res): return list(set(['#'.join([dlat, dlon]) for (dlat, dlon) in geonbr(lat, lon, res)])) The constant 0.8 defines how close the location can be at the geobox border before we include neighbor box in the list. For example, calling geoboxes with lat lon (32.1234, -74.23233) will yield following geoboxes. Numbers are handled as Decimal instances to avoid float rounding problems. >>> from decimal import Decimal as D >>> geoboxes(D('32.1234'), D('-74.23233'), D('0.05')) ['32.15#-74.20', '32.10#-74.20', '32.15#-74.25', '32.10#-74.25' 2. Data Import Data can be anything with location and some keyword, so let’s use real world places. Place name will be our searchable term in this example. Geonames.org geocoding service makes its data available for everyone. Find here country you want and download & unpack selected data file. I did use ‘FI.zip’. Data is tab-delimited and line-separated. We need to define few helper functions for reading and importing it. from decimal import Decimal as D def place_dict(entry): return {'_id': entry[0], 'name': entry[1].encode('utf-8'), 'areas': entry[17].encode('utf-8').split('/'), 'loc': { 'lat': entry[4], 'lon': entry[5], }, 'gboxes': geobox(D(entry[4]), D(entry[5]), D('0.05')) } def readnlines(f, n): while True: l = f.readline() if not l: break yield [l] + [f.readline() for _ in range(1, n)] The place_dict converts line from Geonames dump file to JSON document for CouchDB. The readnlines is just helper to make updates in batches. Geobox resolution is 0.05 that makes roughly 5 x 5 km geoboxes. Then just load the data to database. First we create database in server, open the utf-8 encoded file and write it as batches to the CouchDB. >>>import codecs >>>import couchdb >>>s = couchdb.Server() >>>places = couchdb.create('places') >>>f = codecs.open('/home/user/Downloads/FI.txt', encoding='utf-8') >>>for batch in readnlines(f, 100): ... batch = [l.split('\t') for l in batch] ... places.update([place_dict(entry) for entry in batch]) [(True, '631542', '1-239590f242b46d45b33516687c0b1df3'), ... This takes a few moments. You can follow the progress on CouchDB Futon: The place_dict does not validate the content, so the import might stop at broken line in the dump file, in that case you need to filter out the offending lines and rerun. Query few places by id and verify that the data really is there and has right format >>> places['638155'] <Document '638155'@'1-174cbb83a2794c33c40645ddf681fc76' {'gboxes': ['66.85#25.75', '66.90#25.75'], 'loc': {'lat': '66.88333', 'lon': '25.7534'}, 'name': 'Saittajoki', 'areas': ['Europe', 'Helsinki']}> 3. Define View CouchDB views (i.e. queries) are defined by storing a design document in the database. The couchdb Python API provides simple way to update design documents. The query we need is defined in CouchDB by following script function(d) { if(d.name) { var i; for (i = 0; i < d.gboxes.length; i += 1) { emit([d.gboxes[i], d.name], null); } } } This view builds a composite key index by the geobox string and the place name. Load the view to CouchDB. Note that Javascript function is not validated until next query, and you will get strange error messages if it does not parse or execute correctly. Be careful! >>>from couchdb.design impor ViewDefinition >>>>>view = ViewDefinition('places', 'around', viewfunc) >>>view.sync(places) 4. Materialize View CouchDB indexes views on first query and the first query will take a long time in this case. This is because CouchDB does not update index on insert, so after bulk import index building will take some time. Monitor the progress on Futon status page. (). Init indexing by simple query. >>> list(places.view('places/around', limit=1)) [<Row id='123456', key=['65.00#25.05', u'Some Place'], value=None> Note that we call ‘list’ for the query to force execution. The view member function returns just generator. The limit is one to return one entry to verify success. 5. Making Queries Now we can search places by name and location. To do that, lets compute first the geoboxes for a location. >>> geonbr(D('60.198765'), D('25.016443'), D('0.05')) ['60.15#25.05', '60.20#25.00', '60.20#25.05', '60.15#25.00'] To search all locations in single gebox, use query like this: list(places.view('places/around', startkey=['60.20#25.05'], endkey=['60.20#25.05',{}])) To search by place name in a geobox, just include the search term both in start and end keys. The search term in endkey is appended with high Unicode character to define upper bound. list(places.view('places/around', startkey=['60.20#25.05', 'Ha'], endkey=['60.20#25.05', 'Ha'+u'\u777d'])) Define simple helper function def around(box, s): return list(places.view('places/around', startkey=[box, s], endkey=[box, s+u'\u777d'])) Now, to search all places around location that start with search term (e.g. here ‘H’), call the around function for each geobox for that location. >>> l = geonbr(D('60.19'), D('25.01'), D('0.05')) >>> for gb in l: ... around(gb, 'H') ... [<Row id='659403', key=['60.15#25.05', 'Haakoninlahti'], value=None>, <Row id='658086', key=['60.15#25.05', 'Hevossalmi'], value=None>] [<Row id='659403', key=['60.20#25.00', 'Haakoninlahti'], value=None>, <Row id='6545255', key=['60.20#25.00', 'Herttoniemenranta'], value=None>, <Row id='658132', key=['60.20#25.00', 'Herttoniemi'], value=None>, <Row id='651476', key=['60.20#25.00', u'H\xf6gholmen'], value=None>, <Row id='6514261', key=['60.20#25.00', 'Hotel Avion'], value=None>, <Row id='6528458', key=['60.20#25.00', 'Hotel Fenno'], value=None>, <Row id='798734', key=['60.20#25.00', 'Hylkysaari'], value=None>] [<Row id='659403', key=['60.20#25.05', 'Haakoninlahti'], value=None>, <Row id='6545255', key=['60.20#25.05', 'Herttoniemenranta'], value=None>, <Row id='658132', key=['60.20#25.05', 'Herttoniemi'], value=None>, <Row id='658086', key=['60.20#25.05', 'Hevossalmi'], value=None>] [<Row id='659403', key=['60.15#25.00', 'Haakoninlahti'], value=None>, <Row id='651476', key=['60.15#25.00', u'H\xf6gholmen'], value=None>, <Row id='6514261', key=['60.15#25.00', 'Hotel Avion'], value=None>, <Row id='6528458', key=['60.15#25.00', 'Hotel Fenno'], value=None>, <Row id='798734', key=['60.15#25.00', 'Hylkysaari'], value=None>] Our geobox resolution (0.05) guarantees minimum search radius 2.5km and maximum 7.5km. We could use several resolutions, more boxes or always search from location box and 8 boxes around the location to improve results. Note the duplicates that you have to filter out in memory. Now it’s simple thing to fetch the interesting places and compute what ever presentation you want to give to the user. >>> q = places.view('_all_docs', keys=['659403', '658086'], include_docs=True) >>> for row in q: ... print row.doc ... <Document '659403'@'1-5f7fe8f63ae034ea9562c20a8c9b6ae7' {'gboxes': ['60.15#25.05', '60.20#25.00', '60.20#25.05', '60.15#25.00'], 'loc': {'lat': '60.16694', 'lon': '60.16694'}, 'name': 'Haakoninlahti', 'areas': ['Europe', 'Helsinki']}> <Document '658086'@'1-ecaf156721b392411f025a3b00e27d62' {'gboxes': ['60.20#25.05', '60.15#25.05'], 'loc': {'lat': '60.16167', 'lon': '60.16167'}, 'name': 'Hevossalmi', 'areas': ['Europe', 'Helsinki']}> Hi Ikonen, Quite a good descriptive blog about the geobox working. Your approach with geobox for spatial indexing seems promising in CouchDB, as existing solution with GeoCouch does not support the reduce and geohash has flaw of edge case. Well I have one query, is this solution is extendable to index polygon or polyline features. What I think, if we increase the neighbors to match the extent (bbox) of polygon and index all these geobox than we can query the polygon features also. I am new to the NoSQL/CouchDB, another doubt I have about the performance in case the query bbox size is large. This will lead to more numbers of geoboxes that need to be checked in view. I am interested in polygon and line features indexing and searching through the approach you have explained, please let me know how much suitable is this. Regards, Gagan Hi, I believe it’s possible to use this solution to search entities inside a polygon. In this case I would index each place coordinate with varying resolutions that make possible to limit the search to desired area size. 0.0001 = 10m 0.0005 = 50m 0.001 = 100m 0.0025 = 200m … 0.1 = 10 km 0.2 = 20 km Then when searching polygons, compute the polygon bounding box and select best granularity for the polygon. In some cases it could 10km box, in some cases 100m box. depends of the polygon size. Then simply compute the search keys in selected resolution from polygon vertex locations with neighbors, union them to avoid unnecessary double queries and query & merge results. This is relatively straightforward to optimize further by selecting optimal number of queried geoboxes based on size and form of the polygon. For example, query could consist of single 1km box and one 20m box where polygon bleeds over edge. Drawback is that with large number of geoboxes the space and first query cost is high. Also, when adding more query parameters (like the name as in example) the number of keys grow exponentially. Thanks Ikonen, I got your point and I’ll experiment with this approach. I was going through the geobox concept in more detail, got one doubt that is the geobox string just a unique id for that box or it has more significance. Regards, Gagan Geobox string is just unique id for the box. In my example it’s concatenated quantized coordinates with ‘#’ in the middle so I it’s easily recognizable and you can tell immediately the size of the box from the string. It also works nicely with even (e.g. 75.0, 54.0) coordinates and you should be able to add other resolutions later without computing all of them again. (of course some care is needed so that you don’t use resolutions that are divisible so that they produce same id for different box sizes) Thanks Again Ikonen for the detail explanation. Gagan
https://bravenewmethod.com/2010/12/02/simple-reverse-geocoding-with-couchdb/?replytocom=79
CC-MAIN-2020-10
refinedweb
2,022
68.36
Skill Level: Intermediate Table Of Contents - Introduction - What Is Needed - Background Information - What Is CircuitPython - What Is Blinka - Building The Circuit - Installing Blinka - Writing Your First CircuitPython Program - Using The REPL - Working With Libraries - Additional Resources - Summary Introduction This tutorial will teach you how to get up and running with CircuitPython on a Raspberry Pi using the Blinka library. We will cover the following topics: -. - How to install and use libraries in your CircuitPython program.. In addition, this tutorial will use. What Is Needed -”. CircuitPython is based on MicroPython which itself is based on Python. CircuitPython adds strong hardware support to the Python language. It also provides a multitude of libraries and drivers to support sensors, breakout boards, and other external hardware components. This makes CircuitPython an incredibly powerful ally in quickly developing your own hardware interfaced projects. What Is Blinka CircuitPython was originally developed to run on small microcontroller boards using a simplified Python interpreter. However, the Raspberry Pi and other SBCs are full-fledged computers running their own operating systems. Blinka is a Python library that provides the CircuitPython hardware API compatibility layer for SBCs, like the Raspberry Pi, so that they can run CircuitPython programs using the standard Python interpreter. Blinka translates the CircuitPython hardware API to whatever libraries the Linux board provides. On the Raspberry Pi, for instance, the RPi.GPIO library is used for GPIO access, the spidev library is used for SPI, and ioctl messaging is used for I2C. This allows us to use the CircuitPython built-in libraries, e.g. board, microcontroller, digitalio, etc. so that our CircuitPython programs can be agnostic to the hardware they are running on and just work as expected. CircuitPython adds hardware support to the Python language along with a large selection of hardware libraries. With Blinka, we can take advantage of those fantastic libraries developed for CircuitPython and use them in our SBC based projects. Building The Circuit Before connecting any circuitry to your Raspberry Pi, shutdown and disconnect it from power. This avoids accidental damage during wiring. Using a breadboard and jumper wires, connect a red LED in series with a 330 Ω resistor to GPIO21 (physical pin 40) of the Raspberry Pi according to the schematic diagram shown below. Once the circuit is built, connect power to your Raspberry Pi and boot it up. Installing Blinka I assume you are already comfortable installing and using Raspberry Pi OS so I won’t go into those details, but it is safe to say, you should be running a very recent and stable OS version. You should also make sure the I2C and SPI interfaces are enabled on your Raspberry Pi. Python 3 is required to support Blinka and CircuitPython, so use python3 and pip3 in your commands. Open a terminal window on your Raspberry Pi and install Blinka, which also installs various supporting libraries, using the following command. $ pip3 install Adafruit-Blinka Now let’s verify Blinka was installed correctly. Open your favorite text editor and create a Python program named blinkatest.py with the code shown below that I retrieved from Adafruit’s learning guide.!") Run the program to test the hardware interfaces used by Blinka. $ python3 blinkatest.py You should see the following printed to your screen if everything passed. Hello blinka! Digital IO ok! I2C ok! SPI ok! done! Writing Your First CircuitPython Program Now let’s write that old-time standard first program, blinking an LED, that covers the basics for what you need to run a very simple CircuitPython program. Create a file named blink.py with the code shown below. import board import digitalio import time import RPi.GPIO print("Hello, CircuitPython!") led = digitalio.DigitalInOut(board.D21) led.direction = digitalio.Direction.OUTPUT print("Press CTRL-C to exit.") try: while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) except KeyboardInterrupt: RPi.GPIO.cleanup() print("\nCleaned up GPIO resources.") All CircuitPython programs should import the board module. This module defines the specifics for the development board you are using and is necessary for CircuitPython programs to access the board’s GPIO pins and hardware. Line 6 of the program welcomes us to CircuitPython. The digitalio library is used to interface to the GPIO pins of the Raspberry Pi. Lines 8 and 9 set the led variable to point to pin GPIO21 and define it as an output in order to drive our LED. The infinite while loop repeatedly turns on and off the LED with half second delays in between. When CTRL-C is pressed, the except KeyboardInterrupt clause of the try/except block runs the RPi.GPIO library’s cleanup() function directly to ensure all GPIO pins are reset to their default state before exiting the program. Run our new blink program $ python3 blink.py and you should see the LED on your breadboard now blinking. Press CTRL-C to exit the program. Using The REPL Since CircuitPython programs are really just running the standard Python interpreter using the Blinka library for hardware support on the Raspberry Pi, we can still use Python’s standard Read-Evaluate-Print-Loop (REPL) functionality. Enter the REPL by simply executing the python3 command without any arguments. $ python3 Let’s try some CircuitPython specific constructs by typing them in at the >>> REPL prompt. Start with importing CircuitPython’s board library and printing the board’s ID. >>> import board >>> board.board_id 'RASPBERRY_PI_3B' As you can see, I am running on a Raspberry Pi 3 Model B. We can also list all of the Raspberry Pi’s pins known by CircuitPython, along with some other items. >>> dir(board) ['CE0', 'CE1', 'D0', 'D1', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', 'D16', 'D17', 'D18', 'D19', 'D2', 'D20', 'D21', 'D22', 'D23', 'D24', 'D25', 'D26', 'D27', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'I2C', 'MISO', 'MISO_1', 'MOSI', 'MOSI_1', 'RX', 'RXD', 'SCK', 'SCK_1', 'SCL', 'SCLK', 'SCLK_1', 'SDA', 'SPI', 'TX', 'TXD', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'ap_board', 'board_id', 'detector', 'pin', 'sys'] Want to update the LED manually from the REPL? Enter the digitalio statements from our program we wrote earlier. >>> import digitalio >>> led = digitalio.DigitalInOut(board.D21) >>> led.direction = digitalio.Direction.OUTPUT >>> led.value = True >>> led.value = False When you are done playing with the REPL, press CTRL-D to exit. Working With Libraries The ability to access and utilize a vast collection of hardware-specific libraries is one of the core tenets of the CircuitPython ecosystem. All of the currently available libraries can be viewed from the Adafruit_CircuitPython_Bundle GitHub repository. Let’s utilize one of the libraries to demonstrate how this all works. So you don’t need an extra piece of hardware, I selected a library that just converts between binary (ASCII) and hexadecimal representations. On microcontroller boards solely running the simplified CircuitPython interpreter, libraries are installed by simply copying the necessary libraries from the bundle. However, on the Raspberry Pi running the standard Python interpreter, we install CircuitPython libraries in the usual Python fashion with pip3. Install the adafruit_binascii library by running the following command. $ pip3 install adafruit-circuitpython-binascii Create a file named binascii.py with the code shown below. from adafruit_binascii import hexlify, unhexlify # Binary data. data = b"CircuitPython is Awesome!" print("Original Data: ", data) # Get the hexadecimal representation of the binary data hex_data = hexlify(data) print("Hex Data: ", hex_data) # Get the binary data represented by hex_data bin_data = unhexlify(hex_data) print("Binary Data: ", bin_data) This is a modified program that I retrieved from the example listed in the adafruit_binascii library’s GitHub repository. It converts binary based ASCII characters to their hexadecimal representation and then back again. Run the program $ python3 binascii.py and you should see the following printed to the screen. Original Data: b'CircuitPython is Awesome!' Hex Data: b'43697263756974507974686f6e20697320417765736f6d6521' Binary Data: b'CircuitPython is Awesome!' That’s all there is to it. Additional Resources The following is a list of additional resources you may find helpful. - CircuitPython Website () - CircuitPython On Linux And Raspberry Pi Learning Guide () - CircuitPython Essentials Learning Guide () - CircuitPython API Reference () - Awesome CircuitPython () - CircuitPython Cheatsheet () - Blinka On GitHub () - Blinka Documentation () - Adafruit Discord #help-with-circuitpython channel. - Adafruit Forums > Supported Products & Projects > Adafruit CircuitPython and MicroPython () - List Of Available CircuitPython Libraries () - Library API documentation () I recommend reviewing the above resources. They provide a wealth of information for learning more about CircuitPython. If you run into any problems, the CircuitPython on Linux and Raspberry Pi Blinka to run CircuitPython programs on a Raspberry Pi. Specifically, we learned -, and - how to install and use libraries in your CircuitPython program. Hopefully, you have discovered that CircuitPython, by way of the Blinka library, can be an invaluable part of your next Raspberry Pi. 1 Comment […] how to get started using Blinka to support your CircuitPython Programs on the Raspberry Pi – Woolsey Workshop and […]
https://www.woolseyworkshop.com/2020/09/29/getting-started-with-circuitpython-on-raspberry-pi-with-blinka/
CC-MAIN-2022-40
refinedweb
1,466
56.55
I am not able to run a node. [closed] I am running ros kinetic on ubuntu 16. While running a file hello_world.cpp, I get the following error /media/ammar/New Volume/December/ros_directory/src/agitr_book/src/hello_world.cpp: line 2: syntax error near unexpected token `(' /media/ammar/New Volume/December/ros_directory/src/agitr_book/src/hello_world.cpp: line 2: `int main (int argc, char **argv)' This is the code in hello_world.cpp #include "ros/ros.h" int main (int argc, char **argv) { //intializes ros client library //last parameter is a string containing //deafult name of the node //can be overwridden by a launch file //call this once at the beginning of the program ros::init(argc, argv, "hello_ros"); //establishes this program as a ros node //nh is the main mechanism that the program //will use to interact with the ROS system //creating this object registers the program //as a node at ros master ros::NodeHandle nh; //generates an informational message //send to console screen ROS_INFO_STREAM("HELLO_ROS"); } I don't think, there is anything wrong the code as I am following it along with a book. I believe the problem is with the #include line but i don't know what?? If anyone could help me, it will be appreciated. Since your node is C++, you need to compile it before you run it.
https://answers.ros.org/question/338917/i-am-not-able-to-run-a-node/
CC-MAIN-2019-51
refinedweb
223
53.51
Different, but the same, and different again EVERYONE knows that Americans are believers and Europeans are heathens. A new poll by the Financial Times and Harris confirms that only 4% of Americans call themselves atheists. 32% of French do. But as ever, France and America can be compared as well as contrasted. Both countries have a powerful tradition of separation of church and state: 72% of the French and 59% of Americans don't want religion taught in state schools. Britain, Spain and Italy have far less hostility to the church in the public classroom. Then along comes another contrast. Excerpts from the print edition & blogs » Editor's Highlights, The World This Week, and more »
http://www.economist.com/node/21003976/2006/12?page=3
CC-MAIN-2015-11
refinedweb
115
65.62
This article describes how to begin building applications specifically geared to the Prosper.com website. Prosper.com is a popular auction-style site that helps fulfill loans to individuals through a bidding process. Figure 1 - Sample Loan Query Application Courtesy of Prosper Development Introduction In the past, the way to secure a loan was to go to a bank or broker, go through hours of tedious financial discovery and wait a month for approval. The internet has changed all that. Sites such as LendingTree and E-Loan make it much easier to obtain a loan. Not only can you obtain a loan quicker, but these sites force banks to compete for your business (Nothing like putting the power back into the hands of the consumer!). The founder of E-Loan, Chris Larsen, decided one day (probably after seeing how e-bay works), that there was another way to provide loans. Why not let individuals lend or borrow money from other individuals through an auction system. So what exactly gets auctioned? Interest rates! And that is how Prosper was born... How Does Prosper Work? Prosper allows a borrower request a certain amount of money that they would like to borrow (up to $25,000). The borrower places their request on the auction block. In exchange, the lender gets to know quite a lot of financial detail about the borrower (their credit rating, salary, length of employment, number of delinquencies). The lender uses this information along with the borrower's requested interest rate to decide whether or not they will lend money to the borrower. Keep in mind that this auction is completely blind like e-bay. The lender never knows the identity of the borrower and visa versa. The credit information is real, though. Lenders are allowed to ask questions to the borrower, such as, "Please break down your monthly income and expenses." Or, "Please explain the delinquencies." Once the lender decides to lend money, they can bid as little as $50 on the borrower towards the loan. A loan is not issued unless the full amount requested by the borrower is funded by the multiple lenders. (Many requested loans are not fulfilled for this reason.) Once the loan has been completely filled to the total amount requested by the borrower, a new lender can still bid on the loan until the time runs out. The new lender "ups" the bid by bidding a lower interest rate than the previous lenders who have bid on the borrower so far. Often you'll see a successful loan's interest rate drop as much as 50%! It seems borrowers flock to prosper to pay off high interest credit cards, higher interest loans, or to borrow money to start a business. The Risk The risk is always that the borrower defaults on the loan (stops making monthly payments). The lower the credit grade, the larger the risk to the lender. Grades range from AA, A, B, C, D, E, and HR (High Risk). Higher risk credit grades tend to pay much larger interest rates, but are more likely to default. AA grade is the safest, and rarely defaults, but doesn't usually command a high rate. Prosper makes the lender aware of the risks before placing the bid. They even statistically calculate risk of default and return based on historical site statistics. Still there is no guarantee, so it's always best to diversify if you are a lender. Groups Prosper allows you to form Groups. As a member of a group, you have the guidance of the Group Leader to help you obtain the loan. The Group Leader can endorse you as a good loan prospect, if he or she feels you are low risk. The group leader can also request proof of salary and let lenders know that you can be trusted. Figure 1, shows a list of groups just started this April. Prosper API Prosper has opened up its API to the developer world which is pretty exciting for financial software engineers. The API makes it easy to write .NET Applications to automate tasks and metrics produced by the Prosper website. Prosper provides good documentation on the API so you can get started using it right away. The API works through a WebService. The WebService allows you to Login, Logout, and Query or Retrieve certain data. It does not seem like you can automate bidding yet, but I suspect this will be added in a future release. In this article we will talk about using the Query web method, since this is what was provided in the sample application. Objects to Query Prosper has provided a host of objects that you can query on, each providing multiple properties containing loan data. Table 1 are a list of objects and some of their properties. Table 1 - Queryable Prosper Objects Setting up the API To use the API, we just need to generate a Web Service object using .NET. Here are the steps: 1) Create a new Windows Forms Project or ASP.NET Project 2) Right Click on Solution Explorer and choose Add Web Reference. 3) Fill in the url as shown in figure 2 and press Go. Click Add Reference: Figure 2 - Adding a Web Reference Object The reference to the prosper api will appear in your solution as a com.prosper.services as shown in Figure 3. You are now ready to talk directly to the prosper web site to gather information: Figure 3 - Web Reference to Prosper Appearing in the Solution Explorer Using the API in C# Once you've generated the web service reference, you have all the Prosper objects available to you in the .NET framework. You can call any of them just like you would any other class. In this example, we will show you how to query on an object to get a group. You'll first want to add a using statement, so you don't have to preference namespaces every time you access a prosper object: Listing 1 - Adding a using clause to your class You will also want to declare and construct a prosperapi object in order to use it's query method later: Listing 2 - Constructing a prosper API object You are now free to query on any of the available prosper objects provided. Listing 3 shows a simple query to obtain the group information shown in figure 1: Listing 3 - Querying on the Group Object using the prosper API result = prosperAPI.Query(null, "Group", "Name,CreationDate,IsExceptingNewMembers,ShortDescription", "CreationDate > '04/01/08'"); The first parameter in the Query method is an authentication key, which for the initial release can be set to null. The second parameter specifies the name of the prosper object we are querying on (the Group object). The third parameter is a list of all the properties separated by comma of the Group object from which we are requesting information. All properties that we do not specify in the property list will be returned as null. The last parameter is the conditional expression to filter are query. The query expression is similar to a where clause in a database query. All of the groups fulfilling the condition creation date > april 1, 2008 will be returned to the prosper result object. The prosper result object contains a collection of prosper objects that you can loop through to retrieve individual object information. Listing 4 - Looping through the results of the Prosper Query Since we asked for Group objects, the objects returned are of type Group, so if we need to get a property from the group, we just unbox it: Listing 5 - unboxing a Prosper Group object string descriptionOfGroup = myProsperGroup.ShortDescription; You can use the ArrayList above to bind to a DataGridView in order to display your query results. Just drop a DataGridView onto your form and add the code in Listing 6 after the query is performed: Listing 6 - Binding to a DataGridView Conclusion Now that Prosper has opened up it's API to the public, it should be quick and easy to create some cool applications to analyze and track loan information. Prosper has a large enough pool of borrowers that you contains some interesting statistics from querying their loan info. You can also use the prosper API to help you create some cool tools to give you an advantage in the prosper marketplace. I have created a tool myself in .NET called the Prosper Lender's Companion and use it to track and fine tune the bidding process. It's easy to get into the development game at Prosper and perhaps if your developed application is good enough, they will market it on their website! If you are looking to experiment with prosper or borrow money for a .NET project, you can join Prosper and tell them I sent you. In the meantime, don't be afraid to lend a helping hand to the frontier of auction loan markets using C# and .NET.
http://www.c-sharpcorner.com/UploadFile/mgold/ProsperAPICSharp04222008181011PM/ProsperAPICSharp.aspx
crawl-002
refinedweb
1,496
69.82
US6026461A - Bus arbitration system for multiprocessor architecture - Google PatentsBus arbitration system for multiprocessor architecture Download PDF Info - Publication number - US6026461AUS6026461A US09208139 US20813998A US6026461A US 6026461 A US6026461 A US 6026461A US 09208139 US09208139 US 09208139 US 20813998 A US20813998 A US 20813998A US 6026461 A US6026461 A US 6026461A - Authority - US - Grant status - Grant - Patent type - - Prior art keywords - mc - memory - bus - system -/267—Reconfiguring circuits for testing, e.g. LSSD, partition2212/00—Indexing scheme relating to accessing, addressing or allocation within memory systems or architectures - G06F2212/25—Using a specific main memory architecture - G06F2212/254—Distributed memory - G06F2212/2542—Non-uniform memory access [NUMA] architecture Abstract Description This application is a divisional application of U.S. application Ser. No. 08/695,556, filed on Aug. 12, 1996, now U.S. Pat. No. 5,887,146. The present application claims the benefit of U.S. Provisional Application No. 60/002,320, filed Aug. 14, 1995, which is hereby incorporated herein by reference. The present invention relates to multiprocessing computer systems, and more particularly to a flexible, highly scalable multiprocessing computer system incorporating a non-uniform memory access architecture. Symmetric multiprocessing (SMP) computer architectures are known in the art as overcoming the limitations of single or uni-processors in terms of processing speed and transaction throughput, among other things. Typical, commercially available SMP systems are generally "shared memory" systems, characterized in that multiple processors on a bus, or a plurality of busses, share a single global memory. In shared memory multiprocessors, all memory is uniformly accessible to each processor, which simplifies the task of dynamic load distribution. Processing of complex tasks can be distributed among various processors in the multiprocessor system while data used in the processing is substantially equally available to each of the processors undertaking any portion of the complex task. Similarly, programmers writing code for typical shared memory SMP systems do not need to be concerned with issues of data partitioning, as each of the processors has access to and shares the same, consistent global memory. However, SMP the complexity of software running on SMP's increases, resulting in a need for more processors in a system to perform complex tasks or portions thereof, the demand for memory access increases accordingly. Thus more processors does not necessarily translate into faster processing, i.e. typical SMP systems are not scalable. That is, processing performance actually decreases at some point as more processors are added to the system to process more complex tasks. The decrease in performance is due to the bottleneck created by the increased number of processors needing access to the memory and the transport mechanism, e.g. bus, to and from memory. Alternative architectures are known which seek to relieve the bandwidth bottleneck. Computer architectures based on Cache Coherent Non-Uniform Memory Access (CCNUMA) are known in the art as an extension of SMP that supplants SMP's "shared memory architecture." CCNUMA architectures are typically characterized as having distributed global memory. Generally, CCNUMA machines consist of a number of processing nodes connected through a high bandwidth, low latency interconnection network. The processing nodes are each comprised of one or more high-performance processors, associated cache, and a portion of a global shared memory. Each node or group of processors has near and far memory, near memory being resident on the same physical circuit board, directly accessible to the node's processors through a local bus, and far memory being resident on other nodes and being accessible over a main system interconnect or backbone. in a scalable, shared memory multiprocessor system. A weakly ordered memory consistency model is implemented in DASH, which puts a significant burden relating to memory consistency on software developed for the DASH bus-based snoopy scheme, as known in the art, is used to keep caches coherent within a node on the DASH system, while inter-node cache consistency is maintained using directory memories to effect a distributed directory-based coherence protocol. In DASH, each processing node has a directory memory corresponding to its portion of the shared physical memory. For each memory block, the directory memory stores the identities of all remote nodes caching that block. Using the directory memory, a node writing a location can send point-to-point invalidation or update messages to those processors that are actually caching that block. This is in contrast to the invalidating broadcast required by the snoopy protocol. The scalability of DASH depends on this ability to avoid broadcasts on an inter-node basis. The DASH architecture relies on the point-to-point invalidation or update mechanism to send messages to processors that are caching data that needs to be updated. All coherence operations, e.g. invalidates and updates, are issued point-to-point, sequentially, and must be positively acknowledged in a sequential manner by each of the remote processors before the issuing processor can proceed with an operation. This DASH implementation significantly negatively affects performance and commercial applicability. As acknowledged in the above-referenced publication describing DASH, serialization in the invalidate mechanism negatively affects performance by increasing queuing delays and thus the latency of memory requests. DASH provides "fences" which can be placed by software to stall processors until pending memory operations have been completed, or which can be implemented to delay write operations until the completion of a pending write. The DASH CCNUMA architecture generally presents an environment wherein a significant burden is placed on software developers to ensure the protection and consistency of data available to the multiple processors in the system. The DASH architecture, and more specifically the memory consistency and cache coherency mechanisms also disadvantageously introduce opportunities for livelock and deadlock situations which may, respectively, significantly delay or terminally lock processor computational progress. The multiple processors in DASH are interconnected at the hardware level by two mesh networks, one to handle incoming messages, and the other to handle outgoing communications. However, the consumption of an incoming message may require the generation of an outgoing message, which can result in circular dependencies between limited buffers in two or more nodes, which can cause deadlock. DASH further dedicates the meshes for particular service: the first mesh to handle communications classified as request messages, e.g. read and read-exclusive requests and invalidation requests, and the second mesh to handle reply messages, e.g. read and read-exclusive replies and invalidation acknowledges, in an effort to eliminate request-reply circular dependencies. However, request-request circular dependencies still present a potential problem, which is provided for in the DASH implementation by increasing the size of input and output FIFOs, which does not necessarily solve the problem but may make it occur less frequently. The DASH architecture also includes a time-out mechanism that does not work to avoid deadlocks, but merely accommodates deadlocks by breaking them after a selected time period. Although the DASH implementation includes some hardware and protocol features aimed at eliminating processor deadlocks, heavy reliance on software for memory consistency, and hardware implementations that require express acknowledgements and incorporate various retry mechanisms, presents an environment wherein circular dependencies can easily develop. Accordingly, forward progress is not optimized for in the DASH CCNUMA architecture. The CCNUMA architecture is implemented in a commercial multiprocessor in a Sequent Computer Systems, Inc. machine referred to as "Sting" which is described in STING: A CCNUMA Computer System for the Commercial Marketplace, L. Lovett and R. Clapp, ISCA 96, May 1996 incorporated herein by reference. The Sting architecture is based on a collection of nodes consisting of complete Standardized High Volume (SHV), four processor SMP machines, each containing processors, caches, memories and I/O busses. Intra-processor cache coherency is maintained by a standard snoopy cache protocol, as known in the art. The SHVs are configured with a "bridge board" that interconnects the local busses of plural nodes and provides a remote cache which maintains copies of blocks fetched from remote memories. The bridge board interfaces the caches and memories on the local node with caches and memories on remote nodes. Inter-node cache coherency is managed via a directory based cache protocol, based on the Scalable Coherent Interface (SCI) specification, IEEE 1396. The SCI protocol, as known in the art, is implemented via a commercially available device that provides a linked list and packet level protocol for an SCI network. The chip includes FIFO buffers and Send and Receive queues. Incoming packets are routed onto appropriate Receive queues, while the Send queues hold request and response packets waiting to be inserted on an output link. Packets remain on the Send queues awaiting a positive acknowledgement or "positive" echo from the destination as an indication that the destination has room to accept the packet. If the destination does not have queue space to accept a packet, a negative echo is returned and subsequent attempts are made to send the packet using an SCI retry protocol. The linked list implementation of the SCI based coherency mechanism presents a disadvantage in that the links must be traversed in a sequential or serial manner, which negatively impacts the speed at which packets are sent and received. The retry mechanism has the potential to create circular redundancies that can result in livelock or deadlock situations. The linked list implementation also disadvantageously requires significant amounts of memory, in this remote cache memory, to store forward and backpointers necessary to effect the list. Machines based on CCNUMA architecture presently known in the art do not take into consideration to any great extent respective workloads of each of the multiple processors as the machines are scaled up, i.e. as more processors or nodes are added. Disadvantageously, as more processors are added in known CCNUMA multiprocessors, limited, if any, efforts are made to ensure that processing is balanced among the job processors sharing processing tasks. Moreover, in such systems, when related tasks are distributed across multiple nodes for processing, related data needed for processing tends to be spread across the system as well, resulting in an undesirably high level of data swapping in and out of system caches. Methods and operating systems are known for improving efficiency of operation in multiprocessor systems by improving affinity of related tasks and data with a group of processors for processing with reduced overhead, such as described in commonly assigned U.S. patent application Ser. No. 08/187,665, filed Jan. 26, 1994, which is hereby incorporated herein by reference. Further, as described in commonly assigned U.S. patent application Ser. No. 08/494,357, filed Jun. 23, 1995, which is incorporated herein by reference, mechanisms are known for supporting memory migration and seamless integration of various memory resources of a NUMA multiprocessing system. However, known CCNUMA machines generally do not incorporate mechanisms in their architectures for such improvements in load balancing and scheduling. The present invention provides a highly expandable, highly efficient CCNUMA processing system based on a hardware architecture that minimizes system bus contention, maximizes processing forward progress by maintaining strong ordering and avoiding retries, and implements a full-map directory structure cache coherency protocol. According to the invention, a Cache Coherent Non-Uniform Memory Access (CCNUMA) architecture is implemented in a system comprising a plurality of integrated modules each consisting of a motherboard and two daughterboards. The daughterboards, which plug into the motherboard, each contain two Job Processors (JPs), cache memory, and input/output (I/O) capabilities. Located directly on the motherboard are additional integrated I/O capabilities in the form of two Small Computer System Interfaces (SCSI) and one Local Area Network (LAN) interface. The motherboard (sometimes referred to as the "Madre" or "Sierra Madre") includes thereon main memory, a memory controller (MC) and directory Dynamic Random Access Memories (DRAMs) for cache coherency. The motherboard also includes GTL backpanel interface logic, system clock generation and distribution logic, and local resources including a micro-controller for system initialization. A crossbar switch (BAXBAR) is implemented on the motherboard to connect the various logic blocks together. A fully loaded motherboard contains 2 JP daughterboards, two Peripheral Component Interface (PCI) expansion boards, and eight 64 MB SIMMs, for a total of 512 MB of main memory. Each daughterboard contains two 50 MHz Motorola 88110 JP complexes. Each 88110 complex includes an associated 88410 cache controller and 1 MB Level 2 Cache. A single 16 MB third level write-through cache is also provided and is controlled by a third level cache controller (TLCC) in the form of a TLCC application specific integrated circuit (ASIC). The third level cache is shared by both JPs, and is built using DRAMs. The DRAMs are protected by error correction code (ECC) which is generated and checked by two error detection "EDiiAC" ASICs under the control of the TLCC. Static Random Access Memories (SRAMs) are used to store cache tags for the third level cache. A Cache Interface (CI) ASIC is used as an interface to translate between a packet-switched local (PIX) bus protocol on the motherboard and the 88410 cache controller bus protocol on the JP Daughter Board. The architecture according to the invention minimizes system bus contention by implementing four backplane or system busses referred to as "PIBus". Each of the four PIBus interconnects is a 64 bit wide, multiplexed control/address/data wire. Multiple system busses may be implemented to provide one, two or four backplane or system busses, depending upon the particular implementation and the related coherency protocol(s). The PIBus, in an illustrative embodiment described hereinafter is used in implementing a directed-broadcast system bus transfer protocol that limits system wide resource overhead to modules or nodes targeted to service a request. Throughput on the PIBus is maximized, and transfer latencies minimized, by a memory based, full-map directory structure cache coherency protocol, that minimizes snooping. The full-map directory structure is maintained in the memory modules that are accessible over the PIBus. Each directory contains one entry per cache line in the corresponding memory. The directory entries contain coherency information for their respective cache lines. The directory entry fields include: valid bits; modified bit; lock bit; unordered bit and an ordered bit. All memory addresses on the PIBus are routed to the appropriate memory module. Each address is put in a queue for service by the memory. Each address is looked up in the directory and the memory will generate a response based on the directory contents and the type of access requested. The memory will send a response which will be picked up only by those nodes that have a valid copy of the accessed cache line, i.e. a directed broadcast. The responses from memory issued in the directed broadcast transfer protocol include invalidates, copyback and read data. The directed broadcast transfer protocol implementation according to the invention avoids unnecessary processor stalls in processors whose caches do not have a copy of the line being addressed, by forwarding "snoop" traffic in a manner that it will only affect those nodes that have a valid copy of the line being addressed. The memory uses the valid bit field in the directory as an indicator as to which nodes have a copy of an accessed cache line. Ordering of events occurring with respect to the backbone or backplane PIBus is effected so as to maximize processing forward progress by maintaining strong ordering and avoiding retries. All of the operations initiated by one requester must appear to complete in the same order to all other requesters, i.e. cache, processor(s), I/O, in the system. Events are ordered by adhering to a three level priority scheme wherein events are ordered low, medium or high. Strict rules are implemented to ensure event ordering and to effect coherent ordering on the PIBus between packets of different priorities. The three level priority scheme according to the invention, works in conjunction with arbitration services, provided by an "ORB" ASIC, to effectively guarantee forward progress and substantially avoid livelock/deadlock scenarios. The arbitration mechanism is a function of the type of bus involved, and accordingly there is arbitration associated with the local PIX bus, i.e. local to the motherboard, and arbitration associated with access to the system wide or PIBus. The motherboard level PIX busses each use a centralized arbitration scheme wherein each bus requester sends the ORB ASIC information about the requested packet type and about the state of its input queues. The ORB ASIC implements a fairness algorithm and grants bus requests based on such information received from requesters, and based on other information sampled from requesters. The ORB samples a mix of windowed and unwindowed requesters every bus clock cycle. Windowed requests have associated therewith particular time periods during which the request signal must be sampled and a grant issued and prioritized in accordance with predetermined parameters. At the same time that PIX bus requesters are being sampled, the ORB samples the busy signals of the potential bus targets. During the cycle after sampling, the ORB chooses one low priority requester, one medium priority requester and one high priority requester as potential bus grant candidates, based on: ordering information from a low and a medium request tracking FIFO; the state of the Busy signals sampled; and a "shuffle code" which ensures fairness of bus grants. Further selection for a single candidate for the PIXbus grant involves a prioritization algorithm in which high priority requests have priority over medium requests which have priority over low, and in which medium level requests are subjected to a "deli-counter-ticket" style prioritization scheme that maintains time ordering of transactions. High and low priority requests are not strictly granted based on time ordering. The system wide backpanel, or PIBus arbitration mechanism is handled separately for each of the four PIBusses. The arbitration/grant logic is distributed across respective "PI" ASICs, which facilitates traffic between the PIX bus and the PIBus in both directions. PIBus arbitration is based on a "windowed-priority" distributed arbitration with fairness, in which there are specific times, i.e. windows, during which request signals are sampled and then grants associated with each request are prioritized. The requests are prioritized based on a shuffle code that ensures fairness. Since the arbitration logic is distributed each PIBus requester knows the request status of all the other requesters on the bus, and all the local requester only needs to know if a particular grant is for itself or another requester. The "BAXBAR" crossbar switch is implemented on the motherboard to connect the various logic blocks of the CCNUMA architecture according to the invention together, and to propagate transfers between the busses on the motherboard and the daughterboard. The crossbar switch supports six 19 bit bidirectional ports and two 18 bit bidirectional ports, and is controlled by a three bit port select and an eight bit enable control. The port select bits control selection of eight potential sources for outputs, and also enable selected output ports. Features of the invention include a highly efficient, high performance multiprocessor distributed memory system implemented with a high speed, high bandwidth, extensible system interconnect that has up to four busses available for multiprocessor communication. The architecture provides a highly scalable open-ended architecture. In contrast to the typical bus-snooping protocols known in the art, in which each cache must look up all addresses on the bus, the directed broadcast protocol according to the invention increases system performance by not interfering with nodes that do not have a copy of an accessed cache line. Accordingly, unnecessary processor stalls are avoided. The CCNUMA system implementation according to the invention maximizes forward progress by avoiding retries and maintaining strong ordering and coherency, avoiding deadly embraces. Strong ordering, i.e. completion of any two consecutive operations initiated by a single requester being observable by any other entity, i.e. cache, processor, I/O, only in their original order, takes much of the burden and complexity relating to memory consistency out of the hands of software implementations and rest it with hardware in a manner that makes for greater consistency and predictability. The system wide or backplane bus distributed arbitration mechanism ensures fairness in bus accesses while maintaining ordering to a high degree. Node-local centralized local bus arbitration effects highly efficient and fair access to local resources. These and other features and advantages of the present invention will become more apparent from the following detailed description taken in conjunction with the accompanying drawing in which: FIG. 1 is a high level block diagram of a multiprocessor system implementing a CCNUMA architecture according to the invention; FIG. 2 is a block diagram of a motherboard of the multiprocessor system of FIG. 1; FIG. 3 is a block diagram of one daughter board for connection to the motherboard of FIG. 2; FIG. 4 is a memory map of distributed system memory distributed among the motherboards of the multiprocessor system of FIG. 1; FIG. 5 is a block diagrammatic overview of a PI asic controlling access to and from a system backplane or PIBus; FIG. 6 is a Table representing PIXBUS Operation Decode and Queue Priority Assignment; FIG. 7 is a block diagram of a PI Header Buffer and Data Queue; FIG. 8 is a block diagram of PI arbitration; FIG. 9 is a high level block diagram of the memory complex of the multiprocessor system of FIG. 1; FIG. 10 is a block diagram of a memory controller ASIC; FIGS. 11-24 are state machine diagrams for state machines implementing functionality in the memory controller of FIG. 10; FIG. 25 is a block diagram of an Error Detection and Control device ("EDiiAC" or "EDAC") ASIC; FIGS 26A and 26B are Tables of Cache Request Transitions; FIG. 27 is a Table of Cache Inhibited Request Transitions; FIG. 28 is a block diagram of an ORB ASIC; FIG. 29 is a state machine diagram for a TR-- TRACKER state machine implemented in the ORB ASIC of FIG. 28; FIG. 30 is a block diagram of a BaxBar crossbar switch; FIGS. 31A, 31B and 31C illustrate crossbar source selection, PORT-- OE assignments, and port to bus mapping of the BaxBar crossbar switch, respectively; FIG. 32 is a block diagram of a GG ASIC; FIG. 33 is a block diagram of an RI ASIC; FIGS. 34-36 are state machines for resources operation request, resource bus request and resources looping, respectively, implemented in the RI ASIC of FIG. 33; FIG. 37 is a block diagram of a CI ASIC; and FIG. 38 is a block diagram of a TLCC ASIC. As illustrated in FIG. 1, a CCNUMA processing system according to the present invention includes a plurality of motherboards (52) interconnected by a backplane (54). The backplane includes 4 PI buses (56), which provide communication between the motherboards (52). The PI busses (56) are all identical, allowing up to four sets of motherboards (52) to transfer data simultaneously. Each motherboard (52) is a standard module, allowing the processing system (50) to contain virtually any number of motherboards required for the processing load. Motherboards (52) are easily added to increase the processing power. A single motherboard (52), as illustrated in FIG. 2, is an integrated module containing processors, memory, and I/O. The processors, memory, and I/O expansion facilities are all contained on separate daughter boards or SIMMs (Single Inline Memory Modules) which plug into the motherboard. Located directly on the motherboard there are additional integrated I/O facilities, including 2 SCSI (Small Computer System Interface) and 1 LAN (Local Area Network). The motherboard also includes a memory controller and directory DRAMs (for cache coherency), Local Resources including a micro-controller for system initialization, GTL backpanel interface logic, System Clock generation and distribution logic, and a Crossbar switch to connect the various logic blocks together. A fully loaded motherboard (52) contains 2 processor Daughter Boards (58a), (58b), two PCI expansion boards (60a), (60b), and 512 MB of main memory (62) comprised of eight 64 MB SIMMs. Many of the functional modules are implemented using ASICs (Application Specific Integrated Circuits). Functional Overview PIBus The primary communication between processors across the backpanel is accomplished using the PIBus Interface. A single PIBus (56) consists of a multiplexed 72-bit Address CTRL/Data bus and associated arbitration and control signals. Each motherboard (52) implements 4 identical PIBus Interfaces using respective PI ASICs (64a-c), as will be described hereinafter. System traffic is partitioned across the 4 PI Busses (56) by address, so that each bus (56) is approximately equally utilized. The PIBus (56) is implemented using GTL logic. This is a logic level/switching standard that allows for very high speed communication across a heavily loaded backpanel. The logic signals switch between 0.4 and 1.2V. PIXBus The PIXbus (66) is the name given to the bus protocol that is used to connect the functional elements of the motherboard (52) together. This is a packetized 72 bit wide multiplexed address/data bus using a similar protocol to that which the PIBus (56) uses across the backpanel (54). This bus (66) is actually implemented as a series of busses that connect into/out of a central crossbar switch (68), referred to in some places herein as the "BaxBar". The PIXbus is implemented, using LVTTL technology, via 4 BaxBar ASICs (70). A major portion of the PIX Bus (66) is an interconnection between the BaxBar ASICs (70) and the four PI (PIBus Interface) ASICs (64a-d). This bus (66) uses AC Termination for signal integrity and timing. Arbitration for the PIXBus is provided by an ORB ASIC (98), as described in detail hereinafter. The complete PIXBus is actually comprised of a plurality of individual busses interconnecting the functional components on the motherboard of the system according to the invention, including: an RI bus (72) portion of the PIXBus which connects the BaxBar ASICs (70) to an RI (Resources Interface) ASIC (74) and to debug buffers and a debug connector; a GG bus (76) portion of the PIXBus which connects the BaxBar ASICs (70) to two GG (Golden Gate, I/O Interface) ASICs (78 a-b). This bus uses series resistors near to the GG for Signal Integrity/timing improvement; an MC Bus (80) portion of the PIXBus connects the BaxBar ASICs (70) to a MC (Memory Controller) ASIC (82); a CIO Bus (88a) portion of the PIXBus connects the BaxBar ASICs (70) to a first daughterboard (58a); a CI1 Bus (88b) portion of the PIXBus connects the BaxBar ASICs (70) to a second daughterboard (58b); and MUD-- L (92) and MUD-- H Bus (94) portions of the PIXBus which are two busses used to connect the BaxBar ASICs (70) to two EDiiAC ASICs (96) facilitating data integrity of data from the memory system which is generally comprised of memory (62) and directory tag memory (86). Memory Subsystem The Memory subsystem on the motherboard (52) is capable of providing up to 512 MB of system memory for the processing system (50). Actual DRAM storage is provided by up to eight 16M (36) standard SIMMs (62). One motherboard (52) can be populated with 0, 4 or 8 SIMMs. Data is typically accessed in full 64 Byte Cache blocks, but may also be read and written in double word or 64 bit quantities. The memory data is protected using ECC (Error Correction Code) which is generated for data correction using two of the EDiiAC ASICs (96a-b). Each EDiiAC (96) provides a 64 bit data path and the two are used to interleave within a cache block to maximize performance. In addition to the main memory data store, the memory subsystem also contains storage for a full map directory (86) which is used to maintain cache coherency, as described in detail hereinafter. The directory (86) is implemented using 4 Mx 4 DRAMs attached directly to the motherboard (52). The directory is organized as a 8Mx 17 storage using 11 data bits and 6 ECC bits. The ECC codes for both the directory and the main data store are capable of correcting all single bit errors and detecting all double-bit errors. I/O Subsystem The I/O subsystem of the motherboard (52) is comprised of two independent PCI channels (79a-b) operating at 25 MHz. Each PCI channel (79) is interfaced to the PIX bus (66) using a single GG ASIC (78) which also contains an integrated cache for I/O transfers. The GG ASIC (78) contains all necessary logic to provide the interface between the 50 MHz PIX bus (66) and the 25 MHz PCI bus (78), including PCI arbitration. The GG ASIC (78) also serves as a gatherer of interrupts from system wide areas and combines these interrupts and directs them to the appropriate processor. Each of the two PCI busses (79) is connected to an integrated SCSI interface (98), and to a single expansion slot (60). One of the two PCI busses (79a) also contains an integrated 10 Mb LAN interface (100). The two SCSI interfaces (98a-b) are implemented using the NCR825 Integrated PCI-SCSI controller as a pair of Wide Differential SCSI-2 interfaces. Each controller is connected through a set of differential transceivers to a 68 pin High Density SCSI connector (not shown). The single LAN connection (100) is made using the DECchip 21040 PCI-Ethernet controller. This provides a single chip integrated LAN which is connected to an RJ-45 connector (not shown). The two expansion PCI slots are provided for by attaching a PCI Daughterpanel to the motherboard. This small board provides a connection between high-density AMP connectors and a standard PCI card connector. The board also allows the two PCI cards to be plugged in parallel to the motherboard. The motherboard design has space to allow two half size PCI cards to be plugged into each motherboard. Further PCI expansion is achieved by using a PCI expansion chassis, and plugging a host-side adapter cable into one of the motherboard expansion slots. Resources Each motherboard (52) contains all the local resources that are required of a system (50), with the exception of the System ID PROM (not shown) which is contained on the backpanel (54). The resource logic on the motherboard (52) includes a Microcontroller (102), state-recording EEPROMs (Electrically Erasable Programmable Read Only Memory, not shown), NOVRAM (Non-Volatile RAM), and SCAN interface logic (104) which is described in detail in copending commonly owned PCT Application Serial No. 09/011,721 (Atty Docket No. 158/46,642), HIGH AVAILABILITY COMPUTER SYSTEM AND METHODS RELATED THERETO, which is incorporated herein by reference. The resource logic is duplicated on each motherboard (52), but a working system (50) only ever uses the resources section of the board in either slot0 or slot1 of the backplane system (54) as system wide Global Resources. An RI (Resources Interface) ASIC (74) provides the interface between the PIXbus (72) and the devices within the Resources section on the motherboard (52)., Macro Array CMOS High Density devices (MACHs) which are high density electrically erasable CMOS programmable logic,. Clocks Each motherboard (52) contains the necessary logic to generate and distribute both 50 MHz and 12.5 MHz clocks to the other boards in the system (not shown). It also contains the logic to distribute the received clocks from the backpanel to all appropriate clock loads with a minimum of added skew. The for as for a system (50) will always be sourced by either the motherboard (52) in slot 0 or the motherboard (52) in slot 1. Each slot receives clocks from both slots and selects clocks from the appropriate slot (slot 0 unless the clocks from slot 0 have failed). Each motherboard contains two PECL crystals used for generation of all system clocks. These two crystals are a 100 MHz nominal clock crystal and a 105 MHz margin clock crystal. Both of these crystals are passed through a divide by two circuit to produce 50 and 52.5 MHz system clocks with 50% duty cycle. These two clocks are muxed together to produce the system clock for the system (50). The multiplexing is controlled from the resources section and allows either nominal or margin clocks to be used by the system. The chosen clock is buffered and 8 differential copies (one for each slot in a system) are driven out to the backpanel (PECL-- CLK-- OUT). A ninth copy of the system clock is further divided to produce a nominally 12.5 MHz signal which is used to generate the 12.5 MHz scan/resources clock on each motherboard. Eight differential copies of this signal are also distributed to the backpanel. Each motherboard receives two 50 MHz system clocks from the backpanel. All first level differential pairs are routed to the same length, and all second level differential pairs are routed to the same length to reduce clock skew. 50 MHz TTL clocks are produced using a translator/distribution device, such as a Synergy Copyclock as known in the art. This device receives a differential PECL clock and translates it to TTL. An external feedback loop is used with the translator to add phase delay to the output clocks until the input of the feedback clock is in phase with the input clock. This has the net effect of eliminating skew between the differential PECL clock distributed to the ASICs and the TTL clock distributed to the EDiiACs (96) and synchronizing buffers. The PECL clock lines are therein terminated to VDD (3.3V) using 62 ohm over 620 ohm resistors. The TTL clocks are source series terminated inside the translator chip. Each motherboard (52) generates a 25 MHz clock that is used for the PCI devices. This clock is derived from the 50 MHz system clock divided by two, and is then PECL to TTL translated by the translator. The length of the feedback loop for the translator was calculated to provide the desired skew correction to make the 25 MHz clock have the minimum skew in relation to the 50 MHz clock. All the clock lines are therein terminated the same way as the 50 MHz clocks with the exception of the expansion clocks which are series terminated using 51 ohm resistors. Each motherboard (52) contains logic that allows it to detect and signal that there is a problem with the clock distribution logic. In slots 0 and 1 this logic also forms a means to have the clock distribution automatically failover from clocks in slot 0 to clocks in slot 1, as described in the referenced PCT application. Daughter Boards The system Daughter Boards (58), as illustrated in FIG. 3., each contain two 50 MHz Motorola 88110 processor complexes. Each 88110 processor (110) has an associated 88410 cache controller (112) and 1 MB Level 2 Cache (114) built using eight MCM67D709 SRAMs. A single 16 MB third level write-through cache (116) is also provided and is controlled by a TLCC (Third Level Cache Controller) ASIC (118). The third level cache (116) is shared by both processors (110), and is built using ten 60 ns 1Mx 16 DRAMs. The DRAMs are protected by ECC (Error Correction Code), which is generated and checked by two EDiiAC ASICs (120) under the control of the TLCC ASIC (118). Tag memory (122) built with three 12 ns 256Kx4 SRAMs is used to store the cache tags for the Third Level Cache. A CI ASIC (124) is used to translate between the packet-switched PIX bus protocol on the motherboard (52) and the 88410 cache controller data bus (126) protocol on the Daughter Board (58). System Functional Description PIX Bus Interface The system according to the invention uses a packetized split response bus protocol to communicate between the processors and memory or I/O. The system also uses a Directory based cache coherency mechanism to eliminate snoop cycles on the main system busses. The CI ASIC's (124) main function is to serve as a translation/sequencer between the PIX bus protocol that is used on the motherboard (52) and the 88410 bus protocol on the daughterboard (58). All off board communication with the exception of Clocks and Reset are part of the PIX bus and is connected directly to the CI. The PIX bus (88) consists of a 64 bit address/data bus with 8 bits of parity, 2 additional "bussed" control signals that indicate the length of the current packet and an error indication. There are an additional 11 signals that are used to provide arbitration control. The PIX bus categorizes different bus operations into three different priorities, LOW, MED, and HIGH, and each PIX bus entity implements queues as appropriate to allow it to receive multiple packets of each priority, as described hereinafter. The CI ASIC (124) only receives Low or Med packets and generates only Low and High packets. Cache Bus Interface The two CPU complexes, CI, and TLC, all on the daughterboard, are connected together by the S-- D bus (126), consisting of 64 bits of data and 8 parity bits, and the S-- A bus (128) which consists of 32 bits of address and additional control lines (130). Arbitration for access to the cache bus is performed by the CI ASIC (124). There are three possible bus masters; each of the two processors (110) for read and write operations (data transfers to or from cache) and the CI (124) for snoop operations (no data transfer). The TLC (118) is always a bus slave. Due to pin limitations, the CI ASIC (124) multiplexes the 32 bit S-- A (128) and 32 bits of the S-- D bus (126) into a 32 bit S-- AD bus (134). This multiplexing is done using four LVT162245 devices (134). When an 88110 processor (110) detects a parity error during a read operation it asserts a P-- BPE-- N signal for a single cycle. This signal is monitored by the CI ASIC (124) and will cause a Fatal Error to be asserted when detected. Because the system coherency is maintained by the MC (82, FIG. 2) and the directory, the CPU complexes must be prevented from modifying a line of data that was previously read in. This is done by causing all read requests to be marked as SHARED in the 88410 (112, FIG. 3), and 88110 (110). In hardware, this is accomplished by pulling down S-- SHRD-- N and S-- TSHRD-- N pins on the 88410 (112) and the P-- SHD-- N signal on the 88110 (110). Third Level Cache The Third Level Cache (TLC) on the daughterboard (58) is a 16 MB direct mapped cache implemented using 1Mx16 DRAMs. The cache is implemented using a write-through policy. This means that the cache never contains the only modified copy of a cache line in the system, and as such only ever sources data to either of the two processors (110) on the daughterboard (58) as the result of a read request. The data store for the cache is constructed from 10 1Mx16 60 ns DRAMs (116). These DRAMs are organized as two banks of 5 DRAMs which contain 64 bits of data plus 8 bits of ECC. Each bank of DRAMs is associated with an EDiiAC ASIC (120a-b) which is used to buffer the data and to perform error detection and correction of data read from the cache. The system outputs of the two EDiiACs are multiplexed down to the 64 bit S-- D bus (126) using six ABT16260 2:1 latching multiplexers (138). The tag store for the cache is implemented using three 256Kx4 12 ns SRAMs (122). Control for the whole TLC is provided by the TLCC ASIC (118), as described in detail hereinafter. Due to timing constraints on the S-- D bus (126) the output enable and mux select for the ABT16260 muxes (138) are driven by an FCT374 octal register (not shown). The inputs to the register are driven out one cycle early by the TLCC ASIC (118). The latch enables used to latch data from the S-- D bus (126) also use external logic. They are derived from the 50 Mhz clock, described in the clock distribution section. The data bits into the low EDiiAC (120b), accessed when a signal S-- A[3] is a 0, are logically connected in reverse order, i.e. SD-- L[0] is connected to pin SD 63, SD-- L[1] to pin SD 62, SD-- L[63] to pin SD0. The parity bits are also reversed to keep the parity bits with their corresponding byte of data. This reversal of bits MUST be taken into account by any software that does diagnostic reads and writes of the EDiiACs (120). The TLCC (118) is designed to operate correctly with several different types of DRAMs. It is capable of supporting both the 1K and 4K refresh versions of 16 MBit DRAMs. The 4K refresh DRAMs use 12 row address bits and 8 column bits to address the DRAM cell. The 1K refresh parts use 10 row and 10 column bits. To allow the use of either DRAM, row address lines A10 and A11 are driven out on A8 and A9 during the column address phase. These bits are ignored by the 4K refresh components in the column address phase, and the A10 and A11 lines are No Connects on the 1K refresh DRAMS. The TLCC (118) also supports DRAMs that use either 1 or 2 Write Enables (WE). This can be done because the minimum access size for the DRAMs is a 64 bit double word. Therefore, the two WE lines for each DRAM can be tied together. On DRAMs that use a single WE, the extra WE is a No Connect. CPU Complex The daughterboard (58) contains two CPU complexes. Each complex consists of an 88110 CPU (110), 88410 Level 2 Cache Controller (112) and 8 67D709 128Kx9 SRAMs (114). The 88110 and 88410 are implemented using 299 and 279 PGA's (Pin Grid Arrays) respectively. The SRAMs are 32 pin PLCC's and are mounted on both sides (top and bottom) of the daughterboard (58). The SRAMs (114) are 67D709 SRAMs that have two bidirectional data ports which simplifies the net topology for data flow from the memory system to the processor. One data port is used to transfer data to/from the 88110 on the P-- D bus (140a-b), the other data port connects the two SRAM complexes together and also connects to the TLC muxes and either the CI or the CI transceivers on the S-- D bus (126). The board (58) is laid out so that the S-- D bus (126) is less than 8.5" in length. This length restriction allows the bus (126) to be operated without any termination and still transfer data in a single 20 ns cycle. The P-- D bus (140) is a point-to-point bus between the SRAMs (114) and a single 88110 (110). This bus is approximately 61" long. The control signals for the SRAMs (114) are driven by the 88410 (112) for all accesses. To provide the best timing and signal integrity for all of these nets, they are routed using a "tree" topology. This topology places each of the 8 loads at an equal distance from the 88410 (112a-b), which helps to prevent undershoot and edge rate problems. The exception to this topology is R-- WE-- N[7:0] lines which are point-to-point from the 88410 (112) to the SRAMs (114). These use 22 ohm Series Resistors to control the edge rate and undershoot (not shown). To prevent Write-through operations from occurring on the System bus a P-- WT-- N pin on the 88110 (110) is left disconnected, and the corresponding pin on the 88410 (112) is pulled up. To help alleviate some hold time issues between the CI ASIC (124) and the Cache RAMs, the Cache RAM clocks are skewed to be nominally 0.2 ns earlier than the other 50 MHz clocks on the board (58). Clocks The daughterboard (58) receives two PECL differential pairs from the motherboard (52) as its source clocks (not shown). One of the pairs is the 50 MHz System Clock and the other is the 12.5 MHz, test/scan clock. Each of the two clocks is buffered and distributed as required to the devices on the daughterboard (58). The clock distribution scheme on the daughterboard (58) matches that used on the motherboard (52) to minimize overall skew between motherboard (52) and daughterboard (58) components. Differential PECL is also used to minimize the skew introduced by the distribution nets and logic. All etch lengths for each stage of clock signal distribution tree are matched to eliminate skew. There are a couple of exceptions to this. The clocks that are driven to the 2nd Level Cache RAMs (114) are purposely skewed to be 500 ps earlier than the other 50 MHz clocks. This is done to alleviate a Hold time problem between the CI ASIC (124) and the SRAMs (114) when the CI ASIC is writing to the SRAMs (line fill). JTAG The daughterboard (58) has a single IEEE 1149.1 (JTAG) scan chain that can be used both for Manufacturing and Power-Up testing, and scan initialization of the CI (124) and TLCC (118) ASICs. The EDiiACs (120), 88110's (110) and 88410's (112) all implement the five wire version of the JTAG specification, but will be operated in the 4-wire mode by pulling the TRSTN pin high. The CI (124), TLCC (118), and board level JTAG logic all implement the four wire version. A TCK signal is generated and received by the clock distribution logic. The devices in the chain are connected in the following order: CI (124)→Lo EDiiAC (120a)→Hi EDiiAC (120b)→TLCC (118)→TLC Address Latch (142)→88110 A (110a)→88410 A (112a)→88110 B (110b)→88410 B (112b)→SEEPROM (144). SEEPROM A Serial EEPROM (144) is used on the daughterboard (58) to provide a non-volatile place to store important board information, such as Board Number, Serial Number and revision history. The SEEPROM chosen does not have a true JTAG interface, therefore it cannot be connected directly into the scan chain. Instead, a JTAG buffer 74BCT8373 (not shown) is used to provide the interface between the two serial protocols. System ASICs Much of the functionality effected in the CCNUMA system according to the invention is implemented in ASICs, as generally described hereinbefore, and more particularly described hereinafter. PI ASIC In monitoring PIBUS-to-PIXBUS traffic, the PI ASIC determines when some node starts a tenure on the PIBUS by observing the request lines of all the nodes, and calculating when the bus is available for the next requester. The PI ASIC(s) (of which there are four, 64a-d, and which may be referred to interchangeably as "PI") have responsibility for examining all traffic on the PIBUS (56), and responding to specific operations that it is involved in. The PI determines when a transfer is started by monitoring the PIBUS request information. There are three different ways that an operation can be decoded as targeted to a particular PI's node. These are: Node-field Bit Compare, ID Originator Node Parsing, and Address Decode. The first beat (i.e. data transfer during one system clock cycle) of a transaction packet (also known as a Header beat) is always either a node type or an address type. If the first beat is a node type then the second beat is always an address type. Information in the operation field determines which combination of decode mechanisms to use. If the first beat is a node type, then this transfer has come from a memory controller's (82) directory control logic. Transfers require snooping local to all nodes which have their respective bit set in the 16-bit node field. If the bit is set, the PI (64) is responsible for requesting the PIXBUS (56) and forwarding the transfer inward. If the first beat is address type, then the operation field is parsed to determine whether to look at the requester ID or the address. If the first beat operation field implies the requester ID match the PI's node ID register, then the PI is responsible for requesting the PIXBUS and forwarding the transfer inward. If the first beat is address type, and the command field does not imply the requester ID compare, then the address is parsed to determine if the PI's node is the target of the transfer. If the physical address range compare results in a match, then the PIXBUS (66) is requested, and the transfer is forwarded inward. If the address range compare results in a match for the control, internal devices, or I/O channel mappings, the PIXBUS is requested and the transfer is forwarded inward. Address decode consists of five range compares. These range compares are based on boundaries which are initialized at powerup. The memory map for the illustrative embodiment of the multiprocessor system according to the invention is shown in FIG. 4. The global resource space (150) resides in the top 4 MB of the 32-bit address range. It is contiguous. Only one node (i.e. motherboard) in the system is allowed to respond to Global Space access. Global Space (150) contains resources such as PROM, DUARTs, boot clock, and a real time clock (RTC, not shown). A Valid bit in an address decoder will be used to determine which node currently owns the Global Space. Directly below the global resource space is 4 MB of Software Reserved area (154) and 3 MB of unused memory space (156). Below the Software Reserved Space is 1 MB of Local Control Space Alias (158). It is used to access node local control space without having to know specifically which node it is accessing. This function is implemented in the Cl ASIC (124), which converts any address issued by a processor (110) in the local control space alias (158) into an address in that node's control space. The Per-JP Local Resources (160) follow the Local Control Space Alias segment. Per-JP Local Resources include 88410 (112) flush registers, a WHOAMI register used to identify a respective node, per-JP programmable interval timer (PIT), per-JP Interrupt registers, and cross interrupt send registers. The next segment is the 16 MB Control space (162). Control Space is evenly partitioned over 16 nodes, so the minimum granularity for decoding of incoming addresses is 1 MB. The next segment used is the 16 MB of Third Level Cache (TLC) Tag Store (166). The TLC maps addresses into this space to allow simple access for prom initialization and diagnostics. JP generated addresses in this range will not appear beyond the bus which the TLC resides (i.e. CI (124) will not pass these addresses to the CI-- BUS (130),(126)). Therefore, the PI ASIC (64) will not have to do any special address decode for this address range. Directly below Control Space (150) is the 64 MB dedicated to the integrated devices (168). The PI ASICs (64) will have a 2 MB granularity while the GG ASICs (78) will have a 1 MB granularity. Integrated Device space must be contiguous on each node. Holes are allowed between node assignments. I/O channel space (172-174) exists between the highest physical memory address and the lower limit of the integrated devices space in the address range E000-- 0000 to F7FF-- FFFF. It must be contiguous on each node. Holes are allowed between node assignments. It has a 32 MB granularity. It is typically used for VME (Versa Module Eurobus) I/O. Physical memory (176-180) must be contiguous on each node. Holes are allowed between node assignments. However, some software may not allow such holes. Physical memory has a granularity of 128 MB. The architecture of the present system is set up to require that one node in the system contain modulo 128 MB of memory starting at address 0 (bottom of memory). Incoming PIBus Transfer (PIBus to PIXbus) The third cycle of a PIBUS transfer is the reply phase. This allows one cycle for decoding of the address/node information presented in the first beat. The interpretation of these pins differs between node and addr type first beats. If the first beat is a node type, then this operation is snoopable. Under that condition, all PIs (64) whose Node ID match their respective node field bit found in the node beat and is able to accept the transfer (P-TRANS queue not full) must assert PI-- RCVR-- ACk-- N. If a PI's Node ID matches it's respective node field bit and the PI's P-TRANS queue is full, the PI must assert PI-- RSND-- N. If no PI-- RCVR-- ACK-- N or PI-- RSND-- N is asserted during the reply cycle, this is a system fatal error, and must be reported as such. To ensure that none of the target PI ASICs (64) forwards the transfer inward (onto the PIXBUS (66)) until all targets receive a complete transfer, the target PI ASICs (64) will wait one cycle after the reply to either request the PIXBUS (66) or to discard the transfer. All target PI ASICS (64) must discard the transfer if there was a PI-- RSND-- N in the reply phase. If the first beat was address type, then this operation is not snoopable. Therefore, there is only one intended target, and only the intended target is to assert either PI-- RCVR-- ACK-- N or PI-- RSND-- N. If no PI-- RCVR-- ACK-- N or PI-- RSND-- N is asserted during the reply cycle, Low priority operation types will be transformed into a NACK type operation while other types will result in a fatal error, since it implies there was no target node responding. In addition, if intended target observes PI-- RSND-- N asserted without it being the source of PI-- RSND-- N this is a fatal system error since only one node can respond to an address type beat. Since the node field of a command-node beat is only used to parse operations incoming from a PIBUS (56), it is not necessary to forward that beat to the node's PIXBUS (66). All incoming node type beats will be dropped when placing the transfer in the P-Transaction Queues. Note that all of the command information of the address type beat is identical to the command of the node type beat, and an address type is sent with every packet. PIBUS-to-PIXBUS Queue & Buffer Selection There are three PIBUS incoming queues in the PI (HI, MED, LOW). Header beat operation fields are parsed to determine which queue they should be sent to. (e.g. copyback-invalidate-reply, copy-back reply and write-back operations, respectively). The MED priority queue is dedicated to operations that have made the furthest progress, and will result in completion or forward progress of the operations that have already referenced memory on some module. Examples are INV-- CMD and RD-- S-- REPLY (e.g. invalidate and read-shared-reply). The lower priority queue is dedicated to those operations that when serviced will cause the injection of more, higher priority traffic into the system. These are operations which have not yet been acted upon by memory such as RD-- S and CI-- WR (e.g. read-- shared and cache inhibited-- write). Since the ORB (98) determines which queue gets granted a transfer on the PIXBUS there may be cases where the ORB allows some lower priority transfers to go ahead of higher priority transfers. Requests are indicated when the PI asserts the signals PI-- X-- HI-- REQ-- N, PI-- X-- MED-- REQ-- N or PI-- X-- LOW-- REQ-- N for a high, medium or low request respectively. A PI (64) will initiate a request only if there is a valid entry in one of the queues. Once a particular high, medium or low request has been made it remains asserted until the ORB (98) grants the PI (68) a bus tenure of that priority. Other ungranted requests will remain asserted. For high and low requests, de-assertion occurs in the cycle after receiving the grant even if there are more entries of that priority in the queue. The medium request will remain asserted if there are more mediums in the queue. A new high or low request can only be made if the previous high or low transfer did not have a MC-- RESEND-- N signal asserted in the fourth cycle of the transfer. This signal represents a limitation that prevents the PI from streaming transfers of HI or LOW priority through the PI. However, full PIXBUS bandwidth can be utilized by the PI if there are two transfers of different priority ready to be transmitted to the PIXBUS. Also, the other PIs on the PIXBUS may request independently of each other so one of the four PIs (64) dropping it's request will have little impact on the PIXBUS bandwidth utilization. A PI (64) will change the amount of time it takes to re-request the PIXBUS (66) on a resend. A backoff algorithm is used to progressively keep it from re-requesting the bus for longer periods of time. This helps prevent a PI (64) from wasting PIXBUS cycles resending operations to ASICS that recently have had full input queues. The progression of backoff time is as follows: 0,1,3,7,15,16,18,22,30,31,1,5,13, . . . . This is done by using a 5-bit decrementor and a starting value for each subsequent backoff is increased from the previous value by 1,2,4,8,1,2,4,8, . . . . The decrementor gets cleared if no resend is seen for the priority being backed-off or if a resend is seen for another priority. There is only one decrementor, and it always keeps track of the backoff needed for the last priority to get a resend. PIXBUS Grant Granting of PIXBUS (66) tenure is determined by the ORB (98) through assertion of the ORB-- GNT-- PI-- HI, ORB-- GNT-- PI-- MED, and ORB-- GNT-- PI-- LOW input signals. The ORB (98) will only grant tenure if the PI asserts PI-- X-- HI-- REQ-- N, PI-- MED-- REQ-- N, or PI-- X-- LOW-- REQ-- N signals for indicating, respectively, a high, medium or low priority request. Once granted the PI will select the HI, MED or LOW queue that corresponds to the grant. The PI will then transfer the oldest operation of that priority which the queue holds. The ORB (98) may grant any PI (64) tenure without regard to any PI, PIXBUS, queue status, except when a PI (64) is making a low priority request while asserting PI-- CS-- REQ. In this case, the ORB (98) must respect the requesting PI's assertion of busy, via a PI-- X-- MED-- BUSY-- N queue status and not grant the requesting PI (64). PI-- CS-- REQ will be asserted anytime the PI (64) holds a low priority PI control space access operation in the queue. Low priority PI requests that are granted when PI-- CS-- REQ is asserted will result in a low priority queue transfer to the medium priority queue for control space access processing. To ensure system coherency, it is necessary that the PI ASICs (64) prevent any IM type of operation who's cache block address matches any INV-- CMD or RD-- INV-- RPLY (i.e. invalidate or read-- invalidate-- reply), to be forwarded to a memory system. This prevention is called squashing. Squashing in the PI ASIC (64) is achieved by transforming such operation types to be a NOP type (i.e. no operation), where it will be treated as a NOP on the PIXBUS. Any operations currently existing in the PI queues that are Intent to Modify (IM) type operations are squashed if the current incoming INV-- CMD or RD-- INV-- RPLY address matches any of the three possible low priority header buffer entries with any such operations. Any such operations which are currently being decoded are squashed if the associated cache block address matches any lNV-- CMD or RD-- INV-- RPLY address within the other header buffer or those which are currently being decoded. Nodes (motherboards) that just received IM operations that resulted in a squash must assert a PI-- RSND-- N signal on the PIBUS to force potential receivers of such operations to squash any possible IM operations just received. There are two different modes of operation for PIBUS transfers involving PI-- RSND-- N (or PI-- RCVR-- ACK-- N), i.e. resend or receiver acknowledge, responses. If the operation is targeted at only one PIBUS resident (i.e. the first beat of transfer is an address transfer), then only the targeted PIbus interface is allowed to issue a PI-- RSND-- N (or PI-- RCVR-- ACk-- N) response. Therefore, when the PIBUS interface receives an address, and that address is resolved to reside on the node, it can be forwarded immediately. This is a non-broadcast type operation. If the operation is potentially a multi-target (i.e. the first beat of transfer is a node bit field), then any targeted PIBUS interface is allowed to issue a PI-- RSND-- N (or PI-- RCVR-- ACK-- N) response. However, since the operation cannot be operated on until all parties involved are able to accept the operation (no one asserts PI-- RSND-- N), it cannot be forwarded immediately. This is a broadcast type operation. PIXBUS Arbitration PIXBUS (66, 68, 72, 76, 80, 88, 92, 94 of FIG. 2) arbitration takes three different forms, one for each of the incoming queue types. HI (high) priority arbitration takes precedence over MED (medium) priority arbitration. MED priority arbitration takes precedence over LOW (low) priority arbitration. MED priority arbitration uses a deli-counter ticket style mechanism to support the time ordering of transactions. HI and LOW priority arbitration are not confined to granting based on time ordering. Requests are indicated when the PI (64) asserts any of the signals PI-- X-- HI-- REQ-- N, PI-- X-- MED-- REQ-- N or PI-- X-- LOW-- REQ-- N for a HI, MED or LOW request respectively. The ORB (98) array is responsible for servicing requests from the PI with a fairness algorithm. The ORB (98) array bestows bus tenure, i.e. issues a grant, to the PI (64) by driving a ORB GNT-- PI-- HI, ORB-- GNT-- PI-- MED and/or ORB-- GNT-- PI-- LOW signal. For the MED priority input queue, the ORB (98) array maintains a Deli Count or "ticket" assigned upon the arrival of a remote MED priority type access targeted to the node. This arrival is indicated to the ORB (98) by the receiving PI (64) asserting a PI-- MED-- CUSTOMER signal. This indicates to the ORB (98) array that the PI (64) is utilized this ticket. The ORB array will then increment the ticket value, wrapping if necessary, for the next cycle. The actual ticket values are maintained in the ORB. The PI's PI-- ORDERED-- OP output is asserted upon the enqueing of a CI-- RD, CI-- WR or CI-- WR-- UNLK (i.e. cache-inhibited-read, write or write unlock) low priority operation type or INV-- CMD, or RD-- INV-- RPLY (i.e. invalidate or read-- invalidate-- reply) medium priority operation type into the PI queue(s). The PI-- ORDERED-- OP signal is used by the ORB (98) to give special priority to these types of operations when one of the PIs (64) has a MED priority operation that needs special ordering. A PI-- NEW-- CUSTOMER-- N output is asserted by the PI on any enqueing of a MED priority or LOW operation into the queue. A ONE-- TO-- GO signal is asserted by the PI (64) when it knows that the next beat is the last beat of the packet for which it was granted. The ORB (98) can use this signal to determine when the tenure is about to end. An X-- XTEND signal is asserted by the PI (64) in all cycles it expects to have bus tenure after the first beat transferred. The PIXBUS receiver can use this signal to determine when the tenure has ended. The PI (64) removes Medium priority operations from its queue in the cycle after its operation transfer was granted since there is no MC-- RESEND-- N possible for medium priority transfers. That is, the memory controller, as described in detail hereinafter, will not resend medium priority data transfers. Any data associated with the Medium operation transfer is removed as it is transferred. High and Low priority operations cannot be removed until after the MC-- RESEND-- N signal is checked in the reply cycle. If there is a resend, the transfer completes as it would without the resend. The only difference is that the operation information and associated data is retained in the PI (64) for re-transmitting when re-granted. PIXBUS-to-PIBUS Traffic The PI (64) determines when a transfer starts on the PIBUS by observing an X-- TS signal which accompanies the first beat of a packet transfer. The PI (64) is responsible for examining all traffic on the PIXBUS, and responding to specific operations that it is involved in. There are three different ways that an operation can be decoded as targeted to a particular PI. These are: RMT-- SNP Bit Compare, Requester ID Node Compare and Address Decode. The first beat of a transaction packet (also known as a Header beat) is always either a node type or an address type. If the first beat is a node type and an RMT-- SNP bit is set, then the second beat is always an address type. Otherwise, it is just an address type. Information in an operation field determines which combination of decode mechanisms to use. These are summarized in the Table of PIXBUS Operation Decode and Queue Assignment, FIG. 6. PIXBUS operations are the same format as those of the PI BUS (56). The only exception is that inbound node type operations have their node headers stripped. Inbound node type operations will not have the RMT-- SNP bit set. If the first beat is a node type, then this transfer has come from a memory controller's directory control logic. Transfers require snooping local to all nodes which have their respective bit set in a 16-bit node field. To distinguish between a snoop which was generated on this node and one which as already been forwarded to the PIBUS, the RMT-- SNP bit is used. If the bit is set, and this beat is a node type, then the PI (64) is responsible for requesting the PIBUS and forwarding the transfer inward. If the RMT-- SNP bit is not set, and this beat is a node type, then the PI (64) will only check the packet's parity. If the first beat is an address type, then the operation field is parsed to determine whether to look at the requester ID or the address fields. This determination is summarized in the Table of FIG. 6. If the first beat is an address type, and the operation field implies the requester ID match the PI's node ID register, then the PI (64) is responsible for requesting the PIBUS and forwarding the transfer outward. If the first beat is a address type, and the command field does not imply the requester ID compare, then the address is parsed to determine if the PI's node is the target of the transfer. If the physical address range compare DOES NOT result in a match, then the PIBUS is requested, and the transfer is forwarded outward. If the address range compare DOES NOT result in a match for the control, internal devices, or I/O channel mappings, the PIBUS is requested and the transfer is forwarded outward. If the address range compare DOES result in a match for the PI control space mappings and an ASIC ID matches, the PIBUS is requested and the transfer is forwarded outward. This match is indicated with a PI-- OUR-- ASIC signal. Address decode for the PIXBUS is the same as the PIBUS address decode. PI BUS Selection If a PIXBUS operation needs to be forwarded to the PIBUS the four PIs must determine which PI (64) will accept the operation. This filtering process is done using information from the address beat of a transaction header. For non-PI control space operations an address bit 19 is XORed with an address bit 7 and address bit 18 is XORed with address bit 6. The resulting two bit code is used to be compared with what codes will be allowed by ADDR-- 76-- EN configuration bits. If that code is allowed by the PI (64) the operation will be accepted by the PI. For PI control space operations only address certain bits, i.e. 7,6, which are used as the two bit code. There are three PIXBUS incoming queues in the PI (HI, MED, LOW). Header beat Operation fields are parsed to determine which queue they should be sent to. The three queues have different priorities. Anything residing in the HI priority queue has priority over everything in the MED & LOW priority queue. Anything residing in the MED priority queue has priority over everything in the LOW priority queue., as discussed hereinbefore. The MED priority queue is dedicated to operations that have made the furthest progress, and will result in completion or forward progress of the operations that have already referenced memory on some module. Examples are INV-- CMD and RD-- S-- REPLY. The lower priority queue is dedicated to those operations that when serviced will cause the injections of more higher priority traffic into the system. These are operations which have not yet been acted upon by memory such as RD-- S & Cl-- WR. All incoming packet transfers are put in their respective priority queues. The only exception is that for Cl-- RDs and Cl-- WRs which are targeted to the PI's control space and received from the PI (64) itself. This is the case of remote PI control space access. In this case the low priority operation is put into the Medium queue instead of the Low queue. This is done to prevent deadlocking situations involving remote PI control space access. PIBUS requests are asserted with the PI-- P-- REQ-- N<7:0> signals. Once granted the PI (64) must drop it's request. New requests are only asserted when PIBUS arbitration logic allows a new window (See PIBUS Arbitration). There must be a valid queue entry in either the high, medium or low queue before the PI (64) will request the PIBUS. A request may be delayed if there is a resend reply on the PIBUS bus. Selection of which of the high, medium or low queue for output depends on the setting of a P-- OUT-- SHUF-- ARB state, and which queues contain valid entries. If P-- OUT-- SHUF-- ARB=0 then all valid high queue entries will get sent before all medium and low entries and all medium entries will get sent before all low entries. Priority will be ordered HI, MED, LOW. If there is a resend reply on the PIBUS for an operation of a given priority then the PI (64) will shift its priority scheme to MED, LOW, HI) and select the next valid priority operation for output next time. If there is also a resend reply for this operation then the PI (64) will shift again to LOW, HI, MED. If there is yet another resend reply the PI (64) will shift again to HI, MED, LOW and so forth until an operation is sent without a resend reply. Once sent the priority goes back to the original HI, MED, LOW priority scheme. If the P-- OUT-- SHUF-- ARB=1, then a shuffling of the queue priority occurs like that of the shuffling done for PIBUS arbitration. For one operation the priority will be HI, MED, LOW, then the next will be MED, LOW, HI, then LOW, HI, MED, and back to HI, MED, LOW. To ensure system coherency, it is necessary that the PI (64) ASICs prevent any intent to modify (IM) type of operation who's address matches any lNV-- CMD or RD-- INV-- RPLY to be forwarded to a memory system. As discussed hereinbefore, this prevention is called squashing. Squashing in the PI ASIC will be achieved by transforming the IM operation to a NOP type operation where it will be treated as a NOP on the PIXBUS. Any IMs currently existing in the PI (64) queues are squashed if the current incoming INV-- CMD or RD-- INV-- RPLY address matches any of the three possible low priority header buffer entries with IMs. Any IMs which are currently being decoded are squashed if the IM address matches any INV-- CMD or RD-- INV RPLY address within the other Header buffer or those which are currently being decoded. Unlike the PIBUS-to-PIXBUS transfer, there is no required latency in requesting the PIBUS. This is because there are no PI (64) targeted PIX transactions which can be signalled to be resent. The ORB (98) will guarantee that there is always enough PIXBUS input queue space to accept a transaction which it grants onto the PIXBUS. The only exception to this rule is the memory controller (MC) input queue which can cause a MC-- RESEND. However, the transaction which is resent by the MC will never be a PI (64) targeted transaction and so it can be assumed that if a PI (64) detects a PIBUS bound transaction it will complete without a resend response. PIBUS arbitration is based on a "Windowed-Priority" distributed arbitration with fairness. What this means is that there are specific times (windows) where the PI-- REQ-- P-- N (request) signals are sampled and then grants associated with each request are prioritized based on a pre-determined code known as the shuffle code. Since this arbitration logic is distributed, each PIBUS requester knows the request status of all the other requesters on the bus. The local requester only needs to know if a particular grant is for itself or another requester. The shuffle code used in the PI (64) is simply a 3-bit counter. It is initialized on reset with the lower three bits of a NODE ID value which is unique for each NODE. The NODE ID counter is also initialized at reset with the NODE ID. Shuffles are allowed if configured to do so, or after the first PIBUS transfer window and then both counters count up by one anytime all requests in a given window have been granted. The PIs (64) will only assert new requests on these window boundaries. As PIs are granted within a window, the PI (64) must deassert the request that was made in that window. A simplified block diagram of the PI Arbitration Logic is shown in FIG. 8. The shuffle code/counter (200) is used as a MUX select for each of the eight 8:1 multiplexers (202). Each 8:1 MUX has a specific permutation of request signals. The output of the multiplexers is connected to a 8-bit priority encoder (204). The 3-bit output of the priority encoder is compared against the NODE ID counter 206 output. If the shuffled prioritized encoded request matches the NODE ID count then the PI (64) is granted the PIBUS tenure. The PI-- ANY-- P-- GNT signal is used by the P-- SLV-- SM to know that a new PI (64) BUS transfer will begin next cycle. The PI (64) ASIC will only enable one PI-- P-- REQ-- N<7:0> corresponding to the node number at which the PI (64) resides. All others will be configured as input only in normal mode operation. The PI (64) expects an acknowledge (P1-- RCVR-- ACK-- N) in the third cycle of the transfer it originates. If there is no acknowledge for a low priority operation, then the PI (64) will create a NACK type packet back to the requester. For all other operation priorities a fatal error will result. The PI (64) also expects a PI-- RSND-- N (if any) in the third cycle of the transfer it originates. Note that the PI (64) always sends the entire transfer to the PIBUS even if there is a P1-- RSND-- N. The PI (64) removes an operation from its queue in the cycle after its operation transfer was acknowledged with no resend (P1-- RCVR-- ACK-- N=0, PI-- RSND-- N=1). If there is a resend, the transfer completes as it would without the resend. The only difference is that the operation info and associated data is retained (or converted to NACK type) in the PI (64) for re-transmitting when re-granted. If a PIBUS is deconfigured then all the PIs on that PIBUS must be deconfigured even if they are fully functional. Memory Controller/MC ASIC The memory system in the CCNUMA architecture according to the invention, illustrated in FIG. 9, is also implemented via an ASIC, referred to as a memory controller (MC) (220). Generally, the MC provides the interface to physical memory (222) for the multiprocessor system, and maintains memory system coherency by implementing a coherency directory (224) for memory. The MC comprises a plurality of functional elements that are described hereinafter. The Memory Controller chip (MC) (82, FIG. 2) controls the execution of physical memory operations. This involves managing both the Directory which maintains system coherency and the memory data store DRAMs. The MC operates at 50 MHz, the standard system clock speed. It is capable of receiving a new packet every 20 ns until its queues are full. The MC is designed to operate on a split transaction, packetized bus based on the architecture defined herein. It is estimated that the MC needs to deliver 115 MB/sec of memory bandwidth for the system according to the invention. This includes a 30% overhead budget. There is one MC ASIC per motherboard board (52), controlling from 0 to 512 MegaBytes, or 1/2 a GigaByte of local memory. The MC, illustrated in FIG. 10, processes memory transaction packets that are driven onto the MCBUS by the BAXBAR. The packets may have originated on any of the local busses or on the PIBUS. To ensure packet ordering needed for coherency, all packets affecting the same block address will always use the same PIBUS. The MC checks packet addresses to decode if they address near or far memory. The MC will accept only near memory packets. The MC accepts high and low priority packets and issues only medium priority packets. Packets issued by the MC can never be retried. The MC has a four packet input queue (230) and four packet output queue (232). Only the packet header beats are enqueued in the MC. The data beats are enqueued in EDiiACs (described in detail hereinafter), which include the data queues (FIFOs) for the memory DRAM data store. The one exception to this are Local Register writes, which are entirely enqueued in the MC. Memory responses (both data and coherency commands) are driven onto the MCBUS as a packet. The MC (with the help of the EDiiACs) performs ECC error detection and correction on DRAM data and checks parity on MCBUS packets. There are two EDiiACs per MC. Each of the EDiiACs has a 64-bit data path and an 8-bit ECC path. When the DRAMs are read or written, the EDiiACs act in parallel to provide a 128-bit data path for the DRAMs. When the EDiiACs drive or receive data from the MUD-- BUS (i.e. MUD-- 1, MUD-- S, used to connect the BaxBar ASICs (70) to two EDiiAC ASICs (96)), they operate in series, each being active every other cycle. This provides a 64 bit data path to the MUD-- BUS and allows a data beat every cycle, even though each EDiiAC by itself can only drive one data beat every other cycle. The MC provides all the control for the EDiiACs and also provides the data store addresses, row address select (RAS), column address select (CAS) and other DRAM control signals. MC Directory Manager The MC includes a Directory Manager functional element that maintains coherency information on each block of physical memory. The information is stored in the directory which is implemented in DRAM. The directory indicates which system nodes (a motherboard is equivalent to a node) hold valid cached copies of memory blocks. It also indicates if a node has a modified version of a memory block and if a memory block is currently locked for the use of a single processor. For each packet that requests memory access, the Directory Manager will examine the corresponding directory information before allowing memory to be altered. When necessary to maintain coherency, the Directory Manager will issue invalidates and copyback commands. The Directory Manager will update the directory information before servicing the next memory request. MC Directory The directory that the directory manager manages maintains system coherency. It stores 11 bits of coherency information for every block of data. Each directory entry describes the state of one memory block (also called a cache line). The coherency information stored in the directory is at a node level. Coherency issues below the node level are the responsibility of the node itself. The directory state is stored in a combination of a Directory Store (DTS) and Copyback Contents Addressable Memory (Copyback CAM or CAM), which are described hereinafter. For each memory access that the MC performs, it must look up the memory address in both the DTS and the CAM to determine the coherency state of the block. The state determines what response the MC will make to the memory request. A memory block can be in any of the five following states: UNUSED. This state means that the block is not resident in any caches in the system. The only valid copy of the block is in memory. All valid bits and the modify bit are zero in this state. SHARED. This state means that there may cache line requesters. MC Directory Store The memory's directory information is stored in DRAMs controlled by the MC ASIC. Each entry in the Directory Store (DTS, 224, FIG. 9) corresponds to a block in the main DRAM data store. Each DTS entry is protected with 6 bits of ECC, used to provide single and double bit error detection and single bit error correction. The DTS is addressed with a 12-bit address bus that is separate from the address bus for the data store. These separate busses are needed to allow multiple accesses to the directory (read and write) while a single multiple-beat block is being accessed in the data store. The DTS will may be implemented with 32 MB DRAM SIMMs, which would be incompletely used, since only 24 MBs are needed. For each DTS entry, bit assignments are as follows: Bit[10]--Unordered Bit[9]--Lock Bit[8]--Mod Bit[7:0]--Vbits (Node 0=Bit 0) Vbits--8 bits--one valid bit for each possible node. Vbit=1 indicates that the corresponding node has a valid copy of this block. Mod--1 bit--the modified bit. Mod=1 indicates that one node has a modified copy of this block and the data in memory is stale. When Mod=1, there must be one and only one Vbit set. Lock--1 bit--the lock bit. Lock=1 indicates that a node has locked the block for its exclusive use. When the lock bit is set, there can not be any Vbits set. Unordered--1 bit--the unordered bit. Unordered=1 indicates that any local read replies from this block must be sent via the backplane to insure ordering with any outstanding invalidates. Busy--A Copyback CAM hit. A directory entry is busy if its block address matches the tag stored in a valid Copyback CAM entry. Such a CAM hit indicates that there is an outstanding copyback request for this block. The memory DRAMs hold stale data for this block so this block is unusable until copyback data is received. Basic Memory Read Access The following is a detailed description of how a read request is processed by the MC. A Read request packet is present on the MCBUS. The MC registers the first word, which is the header, into an Input Register portion of local registers (226). The packet address and command are inspected and since the packet is of interest to the memory it is passed through the Input Queue (230) to the DRAM Controller (232). The address is passed through the RAS/CAS address logic of the DRAM Controller (232), where it is converted into a two part 12-bit DRAM address. The RAS and CAS strobes are also created there, as are the WRITE and CHIP-- SELECT signals. The address is then clocked into the both Address Registers (234) in the address logic (232), one of which addresses the Data Store DRAMS and the other addresses the DTS DRAMS. At this point the two registers hold the same address and the Data Store and the DTS will be read simultaneously. The Directory bits for that address are read from the DTS and registered into the Directory data path (RDP) input register (236). They are then passed through the ECC checking logic (238) and corrected if necessary. The directory bits are then pass to the Header and Directory Decode Module (240) where it is determined what actions must be taken to maintain coherency. New directory bits are generated and passed through ECC generation and into the RDP (236) output register. From there the new directory bits and ECC are written into the DTS. The DTS reads and writes are only one beat each, while the read of the Data Store are 4 beats. Therefore the DTS write can be started while the Data Store read is still in progress. Thus the need for separate address registers for the DTS and Data Store. Once the directory bits are decoded, the Header Encode Module (242) generates a 64-bit header for either a coherency command packet or for a Read Reply packet that will supply the requested read data to the requesting node. The completed header is registered into the Output Queue (246). When the header is at the top of the Output Queue (246), it will be registered into the Output Register. Simultaneously with the Directory being read, the corresponding data is read from the Data Store DRAMS. As the data is read, it is passed through ECC checking and corrected if necessary. 128 bits are read at one time and loaded into a Read FIFO in the EDiiACs (not shown in FIG. 10). Cache line reads are burst reads of 64 bytes. This will require four DRAM reads. Partial reads will read only 128 bits and only one 64 bit beat will be sent with the reply packet. If a Command packet is required for coherency, then the data read from the DRAMs is stale and will not be used. When the command packet gets to the top of the output queue, the stale data will be removed from the EDiiAC read FIFOs. Once the MC has arbitrated for and been granted the MCBUS, an Output Register portion of the local registers (226) drives the new packet header to the BAXBAR. The EDiiACs will drive the data, if any, onto the MUD-- BUS the cycle immediately following the header on the MCBUS. If there is an uncorrectable error in the data read from the DRAMs, the MC and EDiiACs will finish putting the packet onto the MCBUS and the MC will also raise MCBUS-- SCR-- ERR (Source Error). Basic Memory Write Access Write requests are processed by the MC. Each of the memory operations that the MC will support are handled in a very similar manner, as described hereinafter. A write request packet is present on the MCBUS. The MC registers the first word, which is the header, into the Input Register portion of the local registers 226. The packet address and command are inspected and since the packet is of interest to the memory it is passed through the Input Queue (230) to the DRAM Controller (232). Address bit 3 and the HI-- WR-- RAM signal are passed to Data Path Control logic which must begin to write data from the MUD-- BUS into the EDiiAC FIFOs in the following cycle. Any data words following the header are driven onto the MUD-- BUS by the BAXBAR and registered into a Write FIFO in the EDiiACs. The address is passed through the RAS/CAS address logic of the DRAM Controller (232) in the MC, where it is converted into a two part 12-bit DRAM address. The RAS and CAS strobes are also created there, as are the WRITE-- ENABLE signals. The address is then clocked into both Address Registers, one of which addresses the Data Store DRAMS and the other addresses the DTS DRAMS. At this point the two registers hold the same address but only the DTS will be read. If the write is a block write (WB, CB-- INV-- RPLY or CB-- RPLY), the DRAMs begin writing the data. This means that any coherency errors discovered by the directory can not stop the data from being written into the memory. These errors will be fatal. If the write is a partial write (CI-- WR, CI-- WR-- LK or WR-- THRU), the write of the data store DRAMs can not begin until the directory has been read and decoded. The Directory bits for the referenced address are read from the DTS and registered into the Directory Data Path (RDP, 236) input register. They are then passed through the ECC checking logic (238) and corrected if necessary. The directory bits are then passed to the Header and Directory Decode Module (240) where it is determined what actions must be taken to maintain coherency. New directory bits are generated and passed through ECC generation (244) and into the RDP output register. From there the new directory bits and ECC are written into the DTS. Once the directory bits are decoded, the Header Encode logic (242) generates a 64-bit header for an ACK packet, if necessary. The complete header is registered into the Output Queue (246). When the header is at the top of the Output Queue, it will be registered into the Output Register portion of the Local Registers (226). The write data is written into the Data Store DRAMS as soon as the directory bits are decoded. The burst write will take four 128-bit writes to complete. Partial writes will require reading the block out of the DRAMS, merging in the new data and then writing the modified block into the DRAMS. This occurs in the EDiiACs. If a Command packet is required for coherency, then the data in the EDiiAC write FIFO can not be written to the DRAMs and is removed from the FIFO before the MC begins decoding the next request packet. The directory location that corresponds to the main memory location being accessed must be initialized either explicitly or by a "stuff" operation before that main memory location can be accessed. The state of a directory entry is determined by the highest priority directory bit set in that entry. There are five potential directory states. The priority of the bits is listed below. There is no busy bit stored in the directory. A hit in an MC Copyback CAM (250), when checking for a directory entry, indicates that the directory block is busy. Busy (CAM hit)--highest priority Lock--second highest priority Mod--third highest priority VBits--lowest priority The five states are as follows: ______________________________________Directory State Busy Lock Mod VBits______________________________________Busy (Copyback 1 X X YCAM HIT)Locked 0 1 X XModified 0 0 1 XShared 0 0 0 non-zeroUnused 0 0 0 0______________________________________ The system according to the invention implements a mechanism referred to as Queue squashing. Queue squashing is a mechanism to remove from the packet stream as many stale Intent to Modify (IM) packets as possible. A squashed packet is either removed from the stream or is turned into a NOP. Squashing mechanisms are implemented in the MC, PI and CI ASICs. If all stale IMs were allowed to reach the Directory, some might look like valid operations by the time they arrived. Squashing as many stale IMs as possible limits how much the directory state has change since the invalidate that made the IM stale. This increases the chances of detecting that the IM is stale. A stale IM needs no reply packet and should not change any directory state. If the MC receives a stale IM that it can not tell is stale, it will allow the directory to mark that block as modified by that requester. However that requestor does not have a copy of the block. When that requester receives the INV-- CMD that was intended to give it ownership of the block, the requester will respond with an UNDO-- MOD packet which restores the directory's state to shared for that block. Queue squashing is implemented by checking any IM in an ASIC queue against any invalidates (RDJNV-- RPLY or INV-- CMD) that are in queues passing in the other direction. The MC checks for IMs in its Input Queue and for invalidates in its Output Queue. If an IM and an invalidate have the same address, the IM is squashed. If the IM is already in the Input Queue when the invalidate enters the Output Queue, the IM is turned into a NOP. When it reaches the top of the Input Queue, it is immediately dequeued. If the invalidate is already in the Output Queue when the IM arrives at the MC, the IM is enqueued in the Input Queue as a NOP. The enqueue can not be aborted, so only the opcode is altered. When the NOP reaches the top of the Input Queue, it is immediately dequeued. If a stale IM reaches the directory, it will be recognized as stale if the directory state read is illegal for an IM. In that case a NOP reply packet is generated. The reply packet is necessary because the MC may already be requesting the bus before it realizes that the IM is stale. A stale IM can reach the directory when the invalidate command is sent to a PI in order to go to the backplane for snooping, and the IM arrives at the MC from a requestor on the same board as the MC. In that case the IM and the invalidate will never pass each other in any pair of queues. In addition to the functionality described hereinbefore, the MC communicates with the control and status registers inside the EDiiAC ASICs. A more detailed description of the registers and how they are used is set forth in a discussion of the EDiiAC ASIC hereinafter. The main memory DRAMs are accessed through a pair of EDiiAC ASICs (also referred to as the EDACs). The EDACs contain the read and write FIFOs for the memory data. When a read reply packet is sourced by the memory, the header beat is driven by the MC ASIC, the first data beat is driven by one EDAC, the second databeat is driven by the other EDAC, and the two EDACs continue to alternate for the rest of the data beats. The EDACs are selected between by bit 3 of the address. The EDACs just alternate driving data beats because they operate at half the speed of the PIX Bus. The EDACs contain one control register and two status registers. These EDAC registers are not PIX Bus compatible, so software access must access the registers by sending control space requests to the MC ASIC. The MC reformats the requests and forwards them to the EDACs. These forwarded operations are referred to as EDAC Diagnostic Mode operations. When the MC receives a request to read or write an EDAC diagnostic mode register, the request is enqueued in the MC input queue (230) and a flag indicating that this is an EDAC diagnostic mode operation is set in the queue entry. This flag, IQ-- EDAC-- MODE, remains set until it is dequeued from the Input Queue. This flag is used by the decode tables in the MC Header and Directory Decode module (240) to give high priority packets special treatment, as explained below. An additional state bit, HI-- EDAC-- MODE, is also set when the operation is enqueued. HI-- EDAC-- MODE stays set until the MC is granted the bus to issue a NOP packet to the specified EDAC. As long as HI-- EDAC-- MODE is set, the MC will assert MC-- BUSY-- LO-- N. This keeps the MC from receiving any more low priority packets. The MC does not assert MC-- BUSY-- HI-- N. If the MC receives a high priority write, the write is performed, but a RETRY packet is generated if the high priority packet hits a read request in the Copyback CAM. This avoids enqueueing a read reply with data beats. This use of MC-- BUSY-- LO-- N and RETRY responses guarantees two things: that the MC will not receive any more EDAC diagnostic mode operations until this one is complete; and that the MC will not enqueue any more read data into the EDAC FIFOs until this diagnostic mode operation is complete. This guarantees that the EDAC Read FIFOs will be empty when the NOP diagnostic mode packet gets to the top of the MC output queue. When the EDAC diagnostic mode packet gets to the top of the input queue, the MC enqueues two packets in the output queue. This is the only time that the MC generates two reply packets for one input packet. The first packet enqueued is a NOP with eight data beats. The first data beat contains an instruction to the EDAC control register that specifies the desired diagnostic operation. The second data beat returns the EDAC control register to its normal value. The other data beats are ignored. The second packet enqueued is the reply to the requester who initiated the diagnostic operation. If the operation was a read, the reply will be a single beat RD-- S. If the operation was a write or clear, the reply will be an ACK. MC/System Bus Arbitration The arbitration of the MCBUS and MUD-- BUS is included in the local bus arbitration. When one local bus on a motherboard is granted, all the busses are granted. The MC receives high and low priority packets, and sources only medium priority packets. The MC has high and low priority busy signals to tell the arbiter which priority packets it can currently receive. This differentiation between high and low busy signals ensures that the MC will never allow a low priority packet to keep a high priority packet from executing. A signal MC-- BUSY-- HI-- N tells the system arbiter that the MC can not accept any more packets of any priority. It is asserted when the Input Queue (230) is full. MC-- BUSY-- LO-- N tells the system arbiter that the MC can not accept any more low priority packets. However high priority packets can be accepted. It is asserted when the MC contains its maximum of two low priority packets. The Output Queue (246) also has entries that are reserved for responses generated by Copyback CAM (250) hits. The MC does not send the arbiter a busy signal when these reserved entries are full. The only effect is that the MC can not load any new entries in the Copyback CAM (250) until a reserved space opens in the Output Queue (246). Until then, the MC will retry any packet that needs to use the CAM. This is also what the MC does when the CAM itself is full. Packets issued by the MC can never be retried. This would cause coherency violations. Likewise, the MC can not retry any writebacks or copybacks. The MC attempts to drive either MC-- NEAR-- N or MC-- FAR-- N with each medium bus request that is asserts. These signals tell the bus arbiter whether the MC's packet is destined for a local CI or GG, or for the PIBus via a PI. Once MC-- MED-- REQ-- N is asserted, MC-- NEAR-- N (near) and MC-- FAR-- N (far) stay deasserted until the MC can be sure that it has calculated the correct value for them. If neither of the signals is asserted when the arbiter evaluates the MC's bus request, then the arbiter must consider all medium busy signals. If one of the signals is asserted then the arbiter can consider only a select group of the medium busy signals, increasing the MC's chance of getting a grant. Once the MC asserts NEAR or FAR signals, the signal stays asserted until the MC receives a bus grant. The NEAR and FAR signals must deassert the cycle after the grant as the MC may immediately start requesting a new bus tenure. Packet Enqueueing Each time a signal ORB-- TS-- MC is asserted, the MC decodes the address of the packet on the MC-- BUS to determine if the packet is for it. The decode occurs in the MC Header Inspection module. If address [31:24]=FE, address [23:20]=MC-- LR-- NODE-- ID (three bits that indicate the Node ID for this MC) and address [9:6]=MC-- LR-- ASIC-- ID (ASIC ID for this MC), the packet is for this MC's control space. The address is also decoded against the MC-- LR-- MEM-- BIT-- MAP, 32 bits that indicate the physical memory bit map for this MC, each bit of which represents 128 MB of physical memory space. The MC-- LR-- MEM-- BIT-- MAP will have a bit set for each 128 MB of DRAM installed for this MC. Each MC may have up to 512 MB. If the packet is addressed to either the MC's physical or control space, the packet header is enqueued in the Input Queue (230). If the packet is a control space write, the data beat will also be enqueued in the Input Queue (230) the cycle after the header. The Input Queue contains two parallel 4-entry queues, the Header Queue and the Data Queue. The Data Queue entries are only used for control space writes. When a signal HI-- ENQUEUE-- IN is asserted it is an indication to enqueue an MCBUS header beat into the MC Input Queue (Header queue). If the packet is a physical address write, the data beats are enqueued in the EDAC Write FIFOs. Header Decode When IQC-- VALID is asserted there is a valid packet at the top of the Input Queue (230). The assertion of IQC-- VALID starts the SQ-- CURRENT-- STATE state machine (FIG. 11) in the MC sequencer module (254, FIG. 10). This is the main sequencer for the directory manager and queues. IQC-- VALID also starts state machines in the DRAM controller (232). State machine diagrams which are self explanatory to those skilled in the art, are provided herewith as FIGS. 11-24. Some basic information about the header is pre-decoded at the time the packet is enqueued in the Input Queue (230). That information is kept in the queue with the header. This allows the DRAM controller (232) to immediately start the appropriate read or write of Directory and Memory DRAMs. The Header is further decoded in the MC Header and Directory decode module (240). The results of the decode for a physical memory request are not valid until SQ-- MEM-- DECODE-- VALID is asserted. There is also a S-- CS-- DECODE-- VALID for control space operations. The main gate to header decode for physical memory requests is accessing the directory entry for the address. The directory entry is valid the cycle after RDS-- DTS-- VALID is asserted. The RDS-- DTS-- VALID signal indicates that in the next cycle the directory entry for the current address will be valid. The directory entry will be available on RDP-- VBITS RDP-- BUSY, RDP-- LOCK and RDP-- MOD lines. The header decode takes two cycles after the directory entry is read. Reply Packet Encoding By examining the directory entry, the MC Header and Directory decode module (240) decides what type of reply to send. It also decides how to update the directory. The actual encoding of the reply packet header is done in the MC Header encode module (242). The packet header is enqueued in the Output Queue (246). If the reply packet needs to go external to the PIBus to be snooped, a two beat header will be enqueued in the Output Queue (242). The first beat will be a node beat, as described hereinafter. Like the Input Queue (230), the Output Queue has two parallel queues. The Output Queue's queues are five beats instead of four, the extra beat being needed to support EDAC mode operations. In this case one queue is used for the node beat and the other for the header beat. If the packet is a control space read reply, a data beat will be enqueued in the Output Queue (242) the cycle after the header beat is enqueued. This will also use one entry in each of the parallel queues. Both the Input Queue and the Output Queue always enqueue something in both parallel queues. However if both beats are not needed, the second enqueue cycle will load garbage into the queue. Once the reply header is enqueued and the DRAM controller (232) no longer needs the packet at the top of the Input Queue, the Input Queue is advanced to the next request packet. IQC-- VALID is deasserted for one cycle while the queue is advancing. When there is a valid header in the Output Queue and the DRAM controller is ready to drive any needed data beats, the MCBUS Arbitration and Bus Master module (256) requests the bus. For most control space replies, the entire packet is driven from the MC ASIC. The only exceptions are some EDAC diagnostic mode operations which have data beats driven from the EDACs. For physical address read replies, the node beat (if any) and the header beat are driven from the MC ASIC and the data beats are driven from the EDACs. For all other physical address replies there are no data beats and the entire packet is driven from the MC. When the entire packet, including data beats has been driven, the Output Queue (246) is advanced. Like the Input Queue, the Output Queue valid signal, OQC-- VALID is deasserted for one cycle while the queue is advancing. If the MC has another completed request packet already enqueued, the MC bus request signal will not be deasserted when the first bus grant is received. Copyback CAM Memory requests that require a copyback use the Copyback CAM (250). This CAM stores the header of the request packet so that when a copyback reply or writeback to the same address is received, the MC can generate a reply packet to the original requester who precipitated the copyback. In these cases, the reply packet is built from the header stored in the CAM, not from the top of the Input Queue (230). The DRAM controller (232) will write the copyback or writeback data to memory and also store the data beats in the EDAC read FIFOs if a read reply is needed. Copyback replies return the data in the order needed for a read reply packet, so the Read FIFO is filled at the same time that the data is written to the DRAMs. Writebacks will always return the data block aligned, so the data is first written into memory and then read back out to the Read FIFOs in the order needed. Control Space Registers The MC has control space registers that are all in the MC Local Registers module (226). They are 32-bits wide or less. The control space registers are written from an IQ-- DATA output of the Input Queue (230), which corresponds to bits [31:0] on the MC-- BUS. When a control space register is read, the data is loaded into the "address" field (bits [31:0]) of the reply packet's data beat. The data is stored in the Output Queue (246) along with the reply packet header. The data is muxed into the address input of the output queue by an MC Output Mux (258). Packet Ordering The present embodiment of the MC sends all INV-- CMD (invalidate) packets through the PIs to guarantee that INV-- CMDs never arrive before earlier RD-- S-- RPLYs. Since the unordered condition can send any local read reply external, i.e. out through the PIs to the backplane, all INV-- CMDs must also go external. Sending INV-- CMDs external also keeps some stale IM cases from causing data corruptions. The MC is responsible for maintaining coherent order between high priority writes and medium priority invalidates. The need for ordering between packets of different priorities is explained hereinafter with respect to Cache Coherency. Only the need for high and medium ordering is explained here. The ordering problem with high priority packets is that a high priority write (WB, CB-- RPLY CB-- INV-- RPLY) could bypass an incoming medium priority snoopable invalidate (INV-- CMD, RD-- INV-- RPLY). This could result in the following scenario: Memory in this example is on Node 0. Address DATA is a data location that both JP0 and JP5 wish to modify. Address SEMAPHORE is a semaphore that allows only one requester at a time to alter address DATA. Address DATA and SEMAPHORE are serviced on different P1 buses. ______________________________________Packet Requestor Address______________________________________ 1. RD.sub.-- S JPO DATA 2. RD.sub.-- S.sub.-- RPLY JPO DATA 3. RD.sub.-- IM SEMAPHORE 4. (RD.sub.-- INV.sub.-- RPLY JP5 SEMAPHORE) outgoing to node 1 5. CI.sub.-- RD DATA JP5 6. RD.sub.-- S.sub.-- RPLY JP5 DATA 7. CI.sub.-- WR DATA JP5 8. (INV.sub.-- CMD DATA) outgoing to nodes 0,1 9. RD.sub.-- IM SEMAPHORE10. (CB.sub.-- INV.sub.-- CMD JP0 SEMAPHORE) outgoing to node 111. CB.sub.-- INV.sub.-- RPLY JP5 SEMAPHORE12. RD.sub.-- INV.sub.-- RPLY JP0 SEMAPHORE13. CI.sub.-- WR DATA JPO______________________________________ In line 12, JP0 has been granted the semaphore without having received the invalidate for the data (line 8). As a result JP0 reads stale data from its cache and writes it back to memory before ever seeing the invalidate which was issued in line 8. The CB-- INV-- RPLY in line 11 can not be reordered to make it arrive on the PIXbus after the INV-- CMD from line 8, because high priority packets must have unimpeded access to memory. Interfering with this can cause system livelock because the memory queues could always be full of read requests for a block that is currently modified. If the high priority copyback reply can not get to the directory, the read requests can never be satisfied. Therefore it is dangerous to apply any ordering rules to high priority packets. The alternative is to apply the ordering to the reads that try to access memory data altered by a high priority write. Since the CB-- INV-- RPLY can not be reordered, instead the RD-- INV-- RPLY is ordered in line 12. The goal is to keep data written to memory by high priority writes from being sent to other requesters until after any older invalidates have been completed. This is accomplished by sending the RD-- INV-- RPLY in line 12 out through the PIs to the backplane. The medium queue ticketing at the PIs will ensure that the RD-- INV-- RPLY does not arrive at JP0 until after the INV-- CMD from line 8. JP0 will not have a stale cached copy of the data and will have to read the correct data from memory. The ordering could be accomplished by sending all local read replies thorough the PIs. However, this has performance penalties. Instead the ORB sends the MC a signal (ORB-- ORDER-- NEEDED) that is asserted whenever a PI queue holds a medium priority invalidate (INV-- CMD or RD-- INV-- RPLY) which has been in the PI queue for more than a given number of cycles (the number is programmable from 31 to 0). While ORB-- ORDER-- NEEDED is asserted, the MC marks any memory block that receives a high priority write as potentially unordered. The MC will send any local read replies to that block external through the PI's to guarantee that they will be ordered behind the outstanding invalidate. To reduce the number of local read replies sent external, the MC's packet ordering mechanism incorporates the following rules. a) High priority writes from remote requesters mark blocks UNORDERED in the directory when ORB-- ORDER-- NEEDED is asserted at the time that the write was received by the MC. If ORB-- ORDER-- NEEDED deasserts before the MC begins to process the write, the UNORDERED bit will not be set. b) A local read of an UNORDERED block will clear the UNORDERED state in the directory. The UNORDERED state of the block is now tracked in the MC's six entry Snoop CAM (252). The address and requester ID of the local read are loaded into the Snoop CAM. The local read reply has a node beat attached to it and is sent to the PIs. c) If the MC receives a high priority write from a remote requester that hits a local read request in the Copyback CAM (250), the UNORDERED bit is not set, but the read reply is sent external with a node beat and its address and requestor ID are loaded into the Snoop CAM. d) Once loaded, the Snoop CAM (252) entry remains valid until the MC sees the same read reply reissued onto the PIXbus by the PIs. The MC snoops all PIXbus read replies that are to its memory range and which are coming from the PIs. Whenever a snooped read reply matches the address and requester ID of a Snoop CAM entry, that CAM entry is cleared. e) Any additional local read requests to that cache block while the Snoop CAM still holds that address will also be loaded into the Snoop CAM and sent to the PIs with a node beat. f) The UNORDERED condition of a block exists until the directory UNORDERED bit and all Snoop CAM entries for that memory block address have been cleared. If the Snoop CAM contains multiple entries for the same address then each of those read replies must reappear on the PIXbus before the UNORDERED condition is cleared. g) If ORB-- ORDER-- NEEDED is deasserted when a local read request hits the Snoop CAM, the read reply will not be considered unordered if it is a RD-- S-- RPLY. It will not be loaded into the Snoop CAM and it will not be sent to the PIs. If the read reply is a RD-- INV-- RPLY it will still be loaded into the Snoop CAM and sent to the PIs with a node beat. This is to prevent a RD-- INV-- RPLY from arriving at a local requestor before an older RD-- S-- RPLY which may have been delayed in the PI queues. h) The Snoop CAM recognizes six local requestor IDs, which in the present illustrative embodiment are set to the 4 JPs and 2 GGs. The requester IDs can be set with scan, which is described in detail in the referenced PCT application. Each Snoop CAM entry is dedicated to one of those IDs. It is assumed that there will never be more than one outstanding low priority request from each requester. A fatal error will issue if the MC tries to load a new read reply into the Snoop CAM and finds that that requestor already has an outstanding read reply. i) Whenever the directory (224, FIG. 9) is accessed and ORB-- ORDER-- NEEDED is deasserted, the UNORDERED bit in that directory entry is cleared (if set). j) The ORB has a programmable delay which controls how soon the ORB-- ORDER-- NEEDED signal is asserted after the PIs enqueue an invalidate. Unordered read replies are not possible until a number of cycles after the invalidate is enqueued. By reducing the number of cycles that ORB-- ORDER-- NEEDED is asserted, the performance impact of sending local read replies external is reduced. This cycle count delay is programmable from 31 to 0 cycles, and defaults to 31 cycles. It should be further noted that the MC must be run in external invalidate mode if more than one node exists. Otherwise INV CMDs could get out of order with read replies that have been sent external due to unordering. Memory Power-up Initialization During cold reset the MC ASIC resets most internal registers, including configuration registers. Exceptions to this are the Input Queue (230), Output Queue (258), Performance Monitor Counters (not shown), and Input Register and Output Registers (226). Those registers will be initialized through use. The MC leaves cold reset with its fatal and non-fatal error reporting enabled, except for DRAM related errors. Masked errors include refresh errors, ECC errors, coherency errors and MUD-- BUS parity errors. These errors can not be enabled until after the main memory and directory DRAMs have been initialized. To enable this error reporting, an MC-- ERR-- MASK register must be written. On cold reset the MC will tri-state its bus outputs. All outputs will be reset to a benign state. Initialization The MC-- MEM-- BIT-- MAP must be scanned or written to a non-zero value for the MC to accept any memory operations. The MC-- MEM-- BIT-- MAP should match the amount of memory DRAMs present, and should also match the PI ASIC's MEM-- BIT-- MAP. Warm Reset The MC resets internal state machines on warm reset. Configuration registers are not reset, with one exception: MC-- ERR-- MASK[15]. This bit masks MC fatal coherency errors. This class of error must be masked out while PROM is flushing system caches, which occurs during warm resets after fatal errors. Once PROM has reinitialized the directory after a fatal error, it should re-enable MC fatal coherency errors by writing MC-- ERR-- MASK [15]=0. The MC Fatal error line, MC-- FATAL-- OUT-- N, is reset and internal error detection is reset, however control space accessible error reporting registers are not reset. This allows the error information to be read after the MC has been reset. The error registers must be cleared with a control space write to an MC-- FATAL-- ERRORS register before more error information will be saved. Subsequent errors taken after the warm reset but before the error reporting registers have been cleared, will cause the MC to assert the appropriate error pin, but detailed information about the error will not be saved. On warm reset the MC will tri-state its bus outputs. All outputs will be reset to a benign state, except for those needed to keep the DRAMs alive. EDACs and DRAM Cold reset is configured to guarantee that it is asserted for 200 milliseconds. Thus the DRAMs are guaranteed to have their initial powerup period of 500 microseconds before the DRAM controller takes any action. An MC-- LR-- DRAM-- CONFIG register has a cold reset value, 32'hlOB6-- 3780, which causes the DRAM controller to perform RAS- only refreshes on a 512 MByte memory configuration at the fastest possible frequency. This will insure that, once cold reset is de-asserted, the DRAMs receive their required 8 RAS pulses within 256 clock cycles. Alternately, the value of 32'hlOB6-- 3784 will make sure only half the banks are refreshed at any one time, but will take twice as long to make sure that all the DRAMs receive their required 8 RAS pulses. Once the 8 RAS pulses are complete, the main memory and directory DRAMs can be initialized by setting a register MC-- LR-- DRAM-- CONFIG[1:0]=2'b11. This will cause the DRAM controller to load zeros into all of main memory and all of the directory. The MC-- LR-- DRAM-- CONFIG register needs to be polled by software to determine when stuff mode is complete. The DRAM controller (232) will set MC-- LR-- DRAM-- CONFIG[1:0] back to zero when initialization is complete. Once DRAM initialization is complete, MC-- LR-- DRAM-- CONFIG needs to be set to a normal operating value. For 512 MByte memory in a 50 MHz system, the suggested value is 32'hlOB6-- 3720. This sets the refresh to a normal speed, which is slower than that used for initialization. After warm reset is de-asserted, the EDACs can be initialized via writes to the appropriate MC control space register. The EDACs must be initialized after a cold powerup before attempting to write to main memory since the EDAC mode register powers up in an unknown state. The recommended procedure for initializing the EDACs is to write a value (0013 hex) to a "MC-- EDAC-- NORMAL-- MODE" register for both EDACs. Bit 3 of the address of the "MC-- EDAC-- NORMAL-- MODE" register specifies which EDAC mode register to modify. It is recommended that the EDACs have their diagnostic registers cleared after cold powerup by writing to an "MC-- EDAC-- CLEAR-- MODE" register for both EDACs (after initializing the "MC-- EDAC-- NORMAL-- MODE" register). Bit 3 of the address of the "MC-- EDAC-- CLEAR-- MODE" register specifies which EDAC mode register to modify. Sizing Memory The resources section, described hereinafter with respect to the RI ASIC, will read the presence-detect bits of one SIMM from each bank (all SIMMs in a bank must be identical) to determine the population of main memory. The present illustrative embodiment of he CCNUMA architecture according to the invention supports 16Mx36 SIMMs. Only the bits PD1 & PD2 are read, which are defined as GND,GND. It may be advisable to verify that memory is properly configured by sizing with software. It is recommended that the MC be configured for the largest possible configuration while sizing so as to keep all DRAMs active so that they don't require re-initialization (8 RAS pulses). MC Error Detection and Handling The MC generates both fatal and non-fatal errors. Each type of error has a dedicated ASIC interrupt pin: MC-- FATAL-- OUT-- N and MC-- NON-- FATAL-- N, respectively. The MC has an error mask, MC-- ERR-- MASK, that is read/writable from control space. The mask allows individual groups of errors to be disabled independently. When an error is disabled, no interrupt is generated, and the MC does not save error information. Mask bits for both fatal and non-fatal errors are contained in MC-- ERR-- MASK. Non-fatal errors are asserted for failures that will not corrupt system operation but which need to be logged or corrected by the operating system. All information necessary for handling non-fatal errors is saved in control space accessible registers. Non-Fatal errors are clear by writing to a MC-- NON-- FATAL-- ERRORS control space register. Clearing the error also allows error information to be captured for the next error that occurs. As long as an error is outstanding, i.e., not yet cleared, additional errors of that same type can not be recorded by the MC. Fatal errors are asserted for failures that will result in system corruption. This may be either data corruption or loss of ASIC sanity. The MC ASIC will not switch to a scan clock on fatal error and can not be scanned. Scanning, described in the referenced PCT application, would destroy the memory image stored in the DRAMs by interfering with memory DRAM refresh. The memory image must be maintained if a core dump is required for operating system debug. The MC supports a mode (LR-- FATAL-- CLK-- MODE=0 register) wherein it will stop clocks on a fatal error. This mode is intended for debug only, since it will prohibit memory core dumps after a fatal error. The rest of this section is written assuming LR-- FATAL-- CLK-- MODE=1. On fatal error, the MC will abort the current operation and will remain idle except for refreshing the DRAMs. The MC input and output queues are cleared and some internal state machines are reset to idle. The MC will not respond to any bus activity until it receives a warm reset. After the warm reset, the MC's control space registers can be read to get error information that was saved when the fatal error was detected. The PROM then re-initializes the MC by writing to each of the MC's error reporting registers to clear them. Since the MC can not be scanned to collect information about a fatal error, it freezes copies of some of its current state into shadow registers when a fatal error occurs. Shadow registers are copies only and freezing them does not affect normal ASIC behavior. Many of these shadow registers are control space accessible. Others can be accessed only by scanning the MC. The information in the shadow registers remains valid through a warm reset and will not change until after the MC's error registers have been cleared by specific control space writes. If the MC takes a fatal error after it has been given warm reset, but before PROM has read and cleared the error registers, it may be necessary to cold reset the MC and scan test it. When a fatal error originates at the MC, the MC immediately freezes shadow copies of internal state relating to the operation currently being executed. This allows state to be captured before it advances without using several levels of shadow registers. Shadow registers containing less volatile state are not frozen until the MC generated fatal error is sent back to the MC as a system fatal error. If a fatal error is detected by another ASIC, the MC freezes all its shadow registers at the same time, i.e. when the MC receives the system fatal error. Upon receiving FATAL-- IN-- N indicating a fatal error, the MC will: Tri-state the following outputs: MCBUS[71:0]; MC-- EXTEND-- N; and MC-- SRC-- ERR-- N. Deassert the following outputs: MC-- BUSY-- HI-- N; MC-- BUSY-- LO-- N; MC-- MED-- RE-- N; MC-- ONE-- TO-- GO; MC-- DIAG[1]--MC Near Pin; MC-- DIAG[0]--MC Far Pin. Invalidate the Input and Output Queues. Upon receiving FATAL-- IN-- N indicating a fatal error, the MC will: Ignore the following ASIC inputs: ORB-- GNT-- MC; and ORB-- TS-- MC. Upon receiving FATAL-- IN-- N indicating a fatal error, the MC will: Idle the following state machines: MC-- SQ; MC-- ARB-- SM; and MA-- NF-- STATE. When the system takes a fatal error, PROM based software (referred to hereinafter as "PROM") will initiate certain actions. PROM software will first scan as many ASICs as possible to determine the type of error. The ORB ASIC will shadow the MC-- FATAL-- OUT-- N signal so that when multiple fatal error signals are asserted software can determine from scan information which was asserted first. Then warm reset is applied to the ASICs. Then any control space registers in the MC may be read. Warm reset will not affect the contents of the registers which hold pertinent error information. PROM must write to the MC-- FATAL-- ERRORS register to clear the MC's error registers. This write must occur after the warm reset. MC-- FATAL-- ERRORS can not be cleared until MC-- FATAL-- OUT-- N is deasserted, which requires a warm reset. Software may need to also do control space operations to the EDACs to re-initialize them if normal operation will be continued without re-initializing the whole system. Once the MC and EDACs have been re-initialized, the software may choose to flush the contents of the system caches back to main memory. Prior to taking a memory dump, PROM will flush the system caches to get any updated data they hold into the memory. This can cause coherency errors since the MC may receive Writebacks to blocks with illegal directory states. To prevent this, PROM must mask out the MC Fatal Coherency error by setting MC-- ERR-- MASK[15]=1 before beginning the flush. The mask should be set back to 0 when the flush is complete. When the error is masked out, the Writeback data will be written to the memory DRAMS, but the directory state will be updated only if the Writeback was received to a valid directory state. The MC may also drive MC-- SRC-- ERR-- N on the header beats of reply packets generated while the directory is corrupt. To prevent this, it is advisable to set MC-- ASIC-- CONFIG[24]=0. PROM should re-initialize the directory to unused before the flush. This will guarantee that no more coherency errors will be taken once the flushes are complete. Both the main memory DRAM controller and the directory DRAM controller are configured to continue refreshing after a fatal error. This should make it possible to retrieve the DRAM contents after a warm reset. After fatal error has been asserted the DRAM controllers will not process any new operations from the input queue until warm reset has been asserted. Operations in progress will terminate as soon as possible without violating the DRAM parameters. If a fatal error occurs while the DRAM controller is writing a cache block to main memory, it is possible that only part of the block will be written. The DRAM controller does not continue to write data beats after the assertion of FATAL-- IN˜N, but it can not undo data beats that are already written. MC Elements Description Having described the interrelationships of the various elements of the MC as they relate to the overall operation of the MC, the functions, elements or modules are described hereinafter with respect to their individual characteristics, configurations and/or functionality. Not all of the MC elements described hereinafter appear in the block diagram of FIG. 10, as some of the functional elements are sub-portions of the elements depicted in FIG. 10. Input Register (IR) The input registers are free running input register. Every system bus cycle it clocks in the current value of the MC Bus. The IR is 72 bits wide. The main memory data path control (RMP) element will take some bits of the address directly from the IR to control the EDACS. The third beat of the IR, IR-BEAT[3], is used to select the first EDAC to load when write data is present on the MCBUS. The IR also checks for even parity on the MCBUS. Parity is checked every valid bus cycle. Bus parity is not guaranteed when no one is driving the bus. When a parity error is detected the IR will notify an Error module (260) of the MC by asserting a signal IR-PARITY-ERROR. As a result, the Error Module (260) will issue a fatal system error. Header Inspection (HI) The HI function entails the examination of the packet header in the MC's Input Register to decide if the packet should be enqueued. It also determines whether a read or a write is required of one or more of the following: the DTS directory, the Data Store DRAMs and the Local Registers. The HI also asserts a signal MC-BUSY-HI-N when enqueueing the new packet will cause the Input Queue to go full. It is possible that one more packet will arrive after the busy signal is asserted. If this happens, HI will assert MC-RESEND and drop the packet. The requester will reissue the packet at its next opportunity. MC-RESEND will be asserted only for packets intended for this MC. The MC will only resend low and high priority packets, since it never enqueues medium priority packets. A configuration option for the MC is to never raise either MC-BUSY-HI-N or MC-BUSY-- LO-- N, but to always issue MC-- RESEND for packets that the MC can not enqueue. This may have a performance advantage over using both busy and resend if the system does not have good memory affinity. Input Queue (IQ) The Input Queue (230) contains two parallel queues, one for request packet headers, and one for data for control space writes. The header queue is 61 bits wide. The data queue is 33 bits wide. Both queues are 4 beats long. For memory write operations the data beats are stored in the EDACs in the DRAM data path. The IQ also stores control signals decoded from the header by the Header Inspection function. The decoded information allows the DRAM controller (232) to begin operation as soon as a new header appears at the top of the Input Queue. The Input Queue can hold a maximum of four headers. Of those headers, only two may be low priority requests. However up to four high priority requests are allowed. This is part of a forward progress scheme which will always be able to service incoming high priority packets. When the Input Queue is full, the MC asserts its high priority busy signal. The MC will not accept any more packets until the Input Queue has an open entry. If the Input Queue is not full, but it does contain two low priority request packets, then the MC will assert its low priority busy signal. The low busy signal will not be dropped until one of the low priority packets not only leaves the input queue, but is fully processed and its reply packet has been granted the MCBus. This guarantees a maximum of two low priority packets in progress anywhere in the MC. If the Input Queue is holding any IM request packets (Intent to Modify), it will check the IM address against any RD-- INV-RPLY or INV-CMD packets in the Output Queue. If the addresses match, then the Input Queue will "squash" the IM request. This means that it turns the IM into a NOP, as described hereinbefore. This is done to prevent stale IMs from reaching the memory. An IM is stale when it is superseded by an invalidate command to the same cache line. If an IM is determined to be stale before it is enqueued, the MC-HI module will not assert HI-- ENQUEUE-- N and the IM packet will be ignored by the MC. The MC's Input Queue is composed of seven modules: the Input Queue FIFO (MC-IQ), the Input Queue Control (MC-IQC), the MC's generic queue control module (MC-QSM), MC-lQ-M2REG and MC-IQ-M3REG (FIFO registers for the header queue), and MC-IQD-M2REG and MC-IQD-M3REG (FIFO registers for the data queue). The Input Queue includes FIFOs that are controlled via their respective pointers. Each register is preceded by a multiplexer. This allows a new entry to be enqueued at the top of the queue if the queue is empty. Local Registers (LR) The MC has local registers (226) that can be read via a non-memory control-space address. Local Registers may contain configuration information, diagnostic information or performance monitors. Reading and writing local registers is performed with cache inhibited memory operations to control space. The headers of local register accesses are registered into the Input Queue and will be handled in order. The data for local register writes are stored in the corresponding data queue entry in the MCs Input queue. Read reply packets for local register reads will be generated in much the same way as a normal memory read reply, except that the data will come from the LR module and be stored in the MC's Output Queue instead of in an EDAC. The read data is muxed into bits [31:0] of the reply packets data beat by the MC-Output Mux which is on the inputs of the Output Queue. Sequencer (SQ) The Sequencer (254) is the controlling state machine for the Directory Manager. It also helps control the input and output queues and coordinates between the directory manager and the DRAM controller. Header and Directory Decode Module (MC-HD) The MC-HD (240) decodes the packet header at the top of the MC's Input Queue. The MC-HD examines the packet's operation field and the directory entry read for this packet and determines the type of reply packet needed. Only one reply packet type should be specified at a time, one per input packet. This information is sent to the Header Encode Module (242), which encodes the reply packet's header. There are two cycles of decode for each packet in the Input Queue. This is so that the Output Queue has valid inputs for two cycles while it loads its two internal queues. So the MC-HD will decode for two cycles, producing the same output each cycle. The MC-HD also asserts control signals for the Copyback CAM and for the MC-HE module. The MC-HD outputs are only meaningful when the Sequencer (254) is asserting one of the following signals: SQ-- MEM-- DECODE, SQ-- LR-- DECODE, SQ-- DTS-- DECODE. These signals enable the HD's three decode tables. The HD module has three packet header decoding tables, one for each of three types of operations: Memory Operations; Diagnostic Directory Operations; and Local Register Operations. Only one table can be enabled by any one packet. The correct table is enabled by a control signal from the Sequencer. Once a table is enabled, it expects to decode a valid operation. If it does not, it will signal an error. The Memory Operations Table raises HD-- COHERENCY-- ERROR when an error is detected. This will cause a fatal error interrupt to be asserted by the MC. The DTS and LR Operations tables return a NACK when an illegal low priority control space packet is received. A fatal error will be asserted if a high or medium priority packet is received to a control space address. If the directory entry does not need to be changed, the directory will be written with the original data. Soft errors in the DTS directory store will be corrected when data is written back into the DTS. Error Handling (ERR) The Error handling module (260) generates fatal and non-fatal error signals, as described in detail hereinbefore, to notify the system of errors detected by the MC and EDACS. The errors are posted on pins of the MC ASIC. The MC does not support any packet based interrupts. Fatal errors are cleared by cold reset or scanning the interrupt registers. Non-fatal errors can also be cleared by a control space write to the MC-- NON-FATAL-ERRORS register. Only one interrupt of each type can be outstanding at once. The MC will lose information about subsequent interrupts as long as a previous interrupt of that type is outstanding. Diagnostic information on these errors will be saved in the Local Registers Module. DRAM Address Decode The DRAM Address Decode function converts the address portion of the PIX bus header into a row and column address for the DRAM. It also decodes a bank for main memory based on the configuration register. A DRAM Address Path element selects and registers the decoded address for the DRAM address decode function. This element also implements an increment function for the main memory column address. The output of this element is the address that goes to the DRAMs. Control is based on the state of a main memory DRAM sequencer and a directory DRAM sequencer. A Directory DRAM Control module controls all the MC's outputs to the directory DRAM based on the state of the Directory DRAM sequencer and the decoded address. In order to drive the row address as quickly as possible, the RDC receives it from the decode logic directly, and drives it to the DRAM if there is no current operation. Directory ECC Generation The Directory ECC Generation module (244) generates 7 ECC checkbits for 19 bits of data. It is instantiated twice in the Directory data path module; once for read data and once for write data. Directory Data Path The Directory Data Path (RDP) provides a path between the data bus to the directory DRAMs and the directory decode/encode logic. It uses two instantiations of the flow-through Directory ECC module to generate ECC. The RDP corrects single-bit errors in the read data, if enabled to do so. All data, is registered in and registered out of this module. Directory Refresh Control The Directory Refresh Controller contains the refresh timer/counter and an address counter for hardware sniffing. In order to refresh 4096 rows every 64 mS, it must generate a refresh cycle every 15 uS. At operating speeds of 20 ns, a refresh must occur every 781 clock cycles. The Refresh controller includes a programmable register to set the refresh frequency over a range of values between 15 and 781 cycles. It supplies a row address to determine which row is refreshed, and a column and bank address to determine which memory location is sniffed. On Power-up reset it automatically enters a mode where it continually refreshes until all banks have been refreshed. Directory DRAM Sequencer The Directory DRAM Sequencer controls all access to the directory DRAM bank. It receives a start signal for a particular type of operation, and then sequences through all the states of that operation. When it is finished with a particular operation it asserts the IDLE signal. Main Memory Data Path Control The Main Memory Data Path Control (RMP) controls the portion of the data path from the EDAC FIFOs to the BAXBAR. On read operations it must clock data out of the EDAC's read FIFOs into the BAXBAR. The data from EDAC-1 (high order) travels on MUD-- 1-- BUS; the data from EDAC-0 (low order) travels on MUD-0-BUS. It also controls the multiplexing of data in the BAXBAR to deliver a data beat to the PIX bus every cycle. The read operation starts when RMP receives a bus grant and a read data ready signal. On write operations, BAXBAR delivers each data beat on both MUD-- 0-- BUS and MUD-- 1-- BUS. The RMP clocks the data into alternating EDAC write FIFOS. The first word must be held in the write latches of both EDACs in case the transfer is a partial-word write. At the end of the write operation, the RMP asserts the RMP-WDRDY signal. At the end of the read operation, RMP asserts the RMP-RDONE signal. The IR -BEAT[3] signal is used to determine which EDAC write FIFO is clocked first. Main Memory Refresh Control The Main Memory Refresh Controller is very much like the Directory refresh controller described hereinbefore. It contains the refresh timer/counter and an address counter for hardware sniffing. In order to refresh 4096 rows every 64 mS, it must generate a refresh cycle every 15 uS. At operating speeds of 20 ns, a refresh must occur every 781 clock cycles. The main memory refresh controller includes a programmable register to set the refresh frequency over a range of values between 15 and 781 cycles. When it does a refresh operation, all banks have the appropriate row refreshed. This way the refresh frequency does not have to change if more memory is added. The refresh controller supplies a row address to determine which row is refreshed, and a column and bank address to determine which memory location is sniffed. Main Memory DRAM Sequencer (RMS) The Main Memory DRAM Sequencer controls all access to the main memory DRAM banks. It receives a start signal for a particular type of operation, and then sequences through all the states of that operation. When it is finished with a particular operation it asserts the IDLE signal. Copyback CAM Module The Copyback CAM (250) keeps copies of transactions that cause copyback requests. It stores the header from the original read or write request that caused the MC to issue a copyback command (CB-- CMD or CB-- INV-- CMD). When a copyback reply (CB-- RPLY or CB-- INV-- RPLY) or WriteBack (WB) arrives at the top of the MC's input queue, the CAM compares it to all the commands stored in the CAM. If there is a match, then the packet satisfies a prior copyback command. The directory is updated as indicated by the stored command and a read reply packet (RD-- S-- RPLY or RD-- INV-- RPLY) is generated with the copyback or writeback data. Finally the hitting CAM entry is invalidated. The Copyback CAM is necessary because the memory must forward copyback data to the node that is trying to read that block. The requesting node will not know that a copyback was needed to generate the read reply. Writebacks are also looked up in the CAM because a writeback and a copyback command for the same cache line can occur simultaneously. When the copyback command arrives at the cache, it will be ignored because the cache no longer has data for that block. Therefore the memory must recognize the writeback as satisfying the copyback command. The Copyback CAM has two entries. Therefore the MC is limited to two outstanding copyback requests. When a request packet is received which needs to generate a copyback request, the request is given a RETRY reply packet if the CAM is full. No new copyback requests can be generated until a CB-- RPLY,CB-- INV-- RPLY or WB arrives that matches the address of one of the CAM entries. Even then, the CAM is considered busy until the reply packet which is created from the newly arrived copyback or writeback data is granted onto the MCBUS. This ensures that the MC will not require more than two output queue entries to service all the outstanding copybacks. The Copyback CAM is allocated two output queue entries and must not use more or forward progress may be endangered. The CAM checks for hits every cycle, however the Header Decoder Module (MC-- HD) will look at the CAM's hit signal only when a copyback reply, copyback invalidate reply or a writeback is at the top of the input queue. CAM entries may never be equal, i.e. multiple hits are not allowed. The CAM CONTROL is responsible for preventing equal entries. Reset clears all CAM entries simultaneously. If the MC receives a memory operation that requires a copyback, but the Copyback CAM is full, the MC will issue a Retry packet to the requester. The MC will read the directory before considering if the CAM is full to avoid retrying a request unless it absolutely has to copyback. None of the MC's busy signals are affected by the Copyback CAM being full. The Copyback CAM is implemented with two modules: the CAM MUX and the CAM CONTROL. The CAM MUX contains the two CAM entries and outputs only the entry selected by the CAM's hit signal. CAM CONTROL manages the CAM's load pointers and manages reset and signals when the CAM is full. Each CAM entry has registers which are loaded from the top of the Input Queue. Each also has a registered Valid bit. All these registers are loaded when the packet at the top of the Input Queue causes a copyback command to be issued. Only one CAM SLICE is loaded for each copyback. The Valid bit is set or cleared by loading it with the value of CC-VALID when CC-LOAD is active. The CAM mux module compares the contents of its ADDR register against the packet at the top of the input queue every cycle. Each CAM entry puts out a CS-- HIT to indicate that the addresses match and that the Valid bit is set. This hit signal is used to produce the Copyback CAM's output. The CAM MUX takes the outputs of all the CAM entries and asserts CM-- HIT if one of the CAM entries is hitting. It outputs the address, opcode, and requester id from the hitting entry. If there are no hits, the address, opcode and requester id outputs of the CAM MUX are undefined. The CAM Control provides the reset and load control for the CAM SLICES. Multiple CAM hits are not allowed, i.e., CAM entries may never be equal. The Load pointer increments after a CAM entry is loaded, so it is always pointing to the next entry to load. Reset simultaneously clears all CAM entries by synchronously clearing all the Valid bits. A signal SQ-- CLR-- CAM clears one entry by loading a zero into CC-- VALID for the selected entry. Snoop CAM The Snoop CAM is used to detect when read replies for UNORDERED blocks have made it through the PI queues and are visible on the local Pix bus. A block is UNORDERED if its directory UNORDERED bit is set. This is explained hereinbefore. Due to the UNORDERED state of a memory block, the MC may have to send local read replies for that block external (via the backplane) to maintain system coherency. Sending the read reply external guarantees that it will arrive on the local PixBus after any older invalidate type packets that may already be in the PI queues. Once the MC has sent such a read reply external, it snoops the local Pix bus looking for the read reply to reappear. Once the MC sees the read reply it knows that the invalidate that caused the read reply to go external must have also left the PI queues. That memory block is no longer unordered. This is tracked by entering into the Snoop CAM the address (bits 29:6) and the requester ID (bits 5:0) of any read reply that is sent external due to UNORDERED memory state. Issuing the read reply clears the UNORDERED directory bit and the UNORDERED state of that memory block is now tracked in the Snoop CAM instead of in the directory. The Snoop CAM entry is cleared when the MC sees the read reply issued on the local Pix bus. Both the packet's address and requester ID must match the Snoop CAM entry before the entry is cleared. The address of any local read reply generated by the MC is checked against the Snoop CAM as well as against the UNORDERED bit in the directory. The read reply must be sent external if either the UNORDERED bit is set or if the CAM shows that there is already an outstanding external read reply for that memory block. Every local read reply sent external due to an UNORDERED condition is entered the Snoop CAM, even if its address matches one already in the CAM. Since each requester can have only one outstanding read request, the requester IDs of all the Snoop CAM entries will be different, so there will never be multiple hits where both the address and the requester ID match. However there may be multiple hits for just the address compare. When the directory manager does a Snoop CAM lookup to determine if a block is UNORDERED, only the addresses will be compared. But when the read reply snooping logic does a Snoop CAM lookup, both the address and the requester ID will be compared. The Snoop CAM is a performance optimization. The unordered state could be kept exclusively in the directory. However snooping read replies would be impractical since each read reply seen on the local PIX bus would require a directory access to see if that block is marked UNORDERED. Omitting the read reply snooping would increase the number of local read replies sent external since memory blocks would retain their UNORDERED state for much longer. The Snoop CAM is a 6-entry 25-bit wide hybrid between a CAM (contents addressable memory) and a register file. Each CAM entry corresponds to one of six requester IDs. CAM entries hold only a 24-bit address and a valid bit. Loading is done by indexing into the CAM with the requester ID. Clearing requires an address comparison as well as indexing off of the requester ID. The CAM loads and outputs address bits 29:6. A CAM address hit is based on the comparison of the address bits and the valid bit. Each CAM entry has a separate hit signal. It is possible for multiple CAM entries to hit on the same address. The Snoop CAM can be loaded from either the entry at the top of the Input Queue or from the Copyback CAM entry that matches the top Input Queue entry. The Snoop CAM is loaded during the second cycle that HI-- SNP-- SEL=0 after the SQ-- LD-- SNP-- CAM signal is asserted. The Requestor ID of the packet in the Input Queue/Copyback CAM is used to index into the Snoop CAM to choose the entry to be loaded. A fatal error is flagged if the CAM tries to load an already valid entry. When the directory manager (MC-HD module) requires a Snoop CAM comparison, a hit is found if the address stored in any valid Snoop CAM entry matches the address at the top of the Input Queue. An address from the Copyback CAM is used instead of the Input Queue address if the Input Queue packet is a high-priority write that is hitting a read request in the Copyback CAM. When the read reply snooping logic is looking for a hit in the Snoop CAM, both the address and the requester ID must match. The requester ID of the snooped read reply is used to index into the Snoop CAM. Then the address of the read reply is compared with the address stored in that CAM entry. If the addresses match and the entry's valid bit is set, a match has been found and the CAM entry's valid bit is automatically cleared. The CAM has six entries so that it will be able to service one outstanding read request from each of six local requesters. Each entry is dedicated to a specific requester ID. Those IDs can be set by scanning the REQ-- ID-- <5-0> registers, which are set by cold reset to selected IDs. It is assumed that there will never be more than one outstanding low priority request from each requester. If the MC tries to load a new read reply into the Snoop CAM and finds that that requester already has an outstanding read reply, the MC will assert a fatal error. The CAM has no data output. Its only outputs are its hit and valid signals. A warm reset clears all the valid bits. The directory manager and the snooping logic arbitrate for use of the Snoop CAM. Each is granted two cycle windows to use the CAM. The snooping logic has priority if both request simultaneously. The arbitration is performed by the MC-HI module. A HI-- SNP-- SEL signal is asserted when the snooping logic is granted. It is the default to grant the snooping logic. HI-- SNP-- SEL is the select signal for a CAM mux which selects between input from the Input Queue/Copyback CAM and input from the HI snoop register. The HI snoop register holds the last read request snooped from the PIXBus. The snooping logic asserts HI-- SNP-- BUSY when it is starting a CAM access. The directory manager asserts SQ-- SNP-- REQ when it wants to use the CAM. SQ-- SNP-- REQ must always be asserted for exactly two cycles. Header Encode Module (HE) This module (242) encodes the header for any packet issued by the MC. It takes input from the Input Queue, the Header and Directory Decode, the Directory Input Register and the CopyBack CAM. Packet headers can be either one or two beats long. Two beat headers include a node field in the first beat. HE-- TWO-- BEAT will be asserted during the node beat (first beat) of a two beat header. When a Local Register is read, the Header Encode tells a Header Mux to drive one beat of header from this module, followed by one beat of data from the Local Registers. In this case the HE-- TWO-- BEAT signal is asserted during the header beat. The Header Encode Module has one smaller sub-module: the Header EXternal Compare (HEX). This compares the directory VBits to the MC's own node bit to determine if the reply packet will need to go to other nodes. The MC's node bit is decoded from the node number assigned to the MC ASIC on the NODE-- ID[3:0] pins. Output Mux (OM) The OM (258) selects what to drive into the address field of the Output Queue. Selects between headers from the Header Encoder Module and registered data from the Local Register Module. The Output Mux is 32 bits wide. Output Queue Modules The Output Queue (246) holds the MC ASIC's portion of up to 5 outgoing packets. The MC will normally use only 4 of the 5 queue entries. The fifth entry is used only if the MC is processing an EDAC diagnostic mode packet and the output queue fills with three normally generated reply packets. Normally, the MC generates no more than one output packet for each input packet it receives, and the input queue can hold only four packets. However the EDAC diagnostic mode operations require two output packets to be generated. The fifth output queue entry guarantees room for that extra packet. Each of the queue's entries are two beats wide. If only one beat is needed, the second is a copy of the first and is never driven onto the MCBUS. The Output Queue is composed of two smaller queues, Queue A and Queue B. Queue A holds the first beat and 6 bits of packet control information. Queue B holds the second beat. The DRAM control uses some additional bits from the output Queue. It gets the number of data beats to be driven by looking at OQ-- SIZE[2]. This bit is asserted when a full block needs to be driven. OQ-- FORMAT[2] is asserted when the packet has a node beat. When there is a node beat, the DRAM controls wait an extra cycle after bus grant before driving data. A two beat entry may be the two beat header for a remotely snoopable packet (node and address beats) or it may be a Control Space read reply from the MC (address beat and one data beat). The MC ASIC can not source more than a single beat of data. The data beats for memory reads will be supplied by the EDACs via the MUD-- 0-- BUS and MUD-- 1-- BUS. The Output Queue's normal usage is limited to four packets because that is the maximum that the EDAC read FIFOs can hold. Each packet in the Output Queue is guaranteed space for eight beats of data in the EDAC read FIFOS, even if there is no data needed from the EDACs for this packet. The exception to this are the EDAC diagnostic mode operations. Each diagnostic mode operation puts two packets into the Output Queue, but they share the same space in the EDAC read FIFOs because the first packet instructs the EDAC to put diagnostic data into the read FIFO, and the second packet sends that data to the requester. To guarantee forward progress the MC must always have enough output queue space to finish a writeback or copyback reply once it is accepted into the Input Queue. Two entries are reserved in the Output Queue for this purpose because the Copyback CAM has two entries. Only read replies generated by copyback replies(CB-- RPLY or CB-- INV-- RPLY) or writebacks (WB) that hit the Copyback CAM may use these entries. These entries are reserved on a floating basis, i.e., they are not attached to any specific locations within the queue. The Output Queue also reserves two entries for replies generated by the packets in the Input Queue. This is also to guarantee forward progress: the MC should also have enough output queue space to complete the operations accepted into its input queue. The Input Queue is four entries long, but only two of those entries may contain low priority packets. The Output Queue is low-full if the Input Queue has two valid low entries. The MC will assert its low priority busy signal to indicate that it can accept only high priority packets. No busy signal is raised when the two entries corresponding to the CAM are full. Instead the MC will retry any memory request that needs to generate a copyback command. The retry will not occur until the directory has been read. This is identical to what the MC does when the CAM itself is full. The Output Queue enqueues the data on its inputs when the Sequencer (MC-- SQ) asserts SQ-- ENQUEUE-- OUT-- A or SQ-- ENQUEUE-- OUT-- B. Only one of the two queues is enqueued at a time. The Output Queue dequeues the beat at the top of the queue when the Master Bus Arbiter asserts MA-- DEQUEUE-- OUT. An entire entry (two beats) is dequeued at once. There is a cycle delay after MA-- DEQUEUE-- OUT before the dequeue occurs. The Output Queue is built with registers instead of RAM so that it can be part of the MC scan chain. Output Register (OR) The OR registers data from the Output Queue and drives it onto the MCBUS when the bus is granted to the MC. The Output Register is 72 bits wide (64 bits of packet beat and 8 bits of parity). It also generates 8-bit even parity for out going packet beats. The Output Queue does not provide a full 64-bit beat, so missing bits are supplied here as zeros. State Diagrams FIGS. 11-24 present state machine diagrams of the architecture according to the invention, some of which represent the major state machines of the MC ASIC. The following state machine diagrams are included and have a brief description herewith, but should be otherwise well understood by those skilled in the art. SQ-- CURRENT-- STATE: This is the main sequencer for the header and directory decode and reply packet generation. It controls enqueueing of the Input Queue, the Output Queue and the Copyback CAM. It also controls dequeueing of the Input Queue and the Copyback CAM. It helps synchronize the DRAM controller with the header decode and generation logic. SQ-- DONE-- STATE Machine: This state machine determines the earliest time that the MC can request the bus for the reply packet being encoded. When the Output Queue is empty, bus request can be asserted before the header is even ready to be enqueued in the Output Queue. There are two limiting factors. When the header will be ready, and when any data beats will be ready. SQ-- DONE-- STATE is started by the SQ-- CURRENT-- STATE machine when it determines that a reply packet is needed. SQ-- CURRENT-- STATE asserts START-- REQUEST when it knows the header can be produced in time. If the reply packet will contain read data, SQ-- DONE-- STATE waits for the DRAM controller to signal that it is ready. The SQ-- DONE-- STATE asserts DO-- NEW-- OP when we are ready to request the bus. DO-- NEW-- OP asserts for only one cycle. SQ-- DO-- OP-- STATE Machine: This state machine counts the number of packets waiting for a bus grant and tells the MC-- ARB-- SM state machine when to request the bus. It asserts SQ-- DO-- MED-- OP for one cycle when DO-- NEW-- OP is asserted by the SQ-- DONE-- STATE machine. If there is more than one packet waiting for a bus grant, then SQ-- DO-- MED-- OP remains asserted until bus request has been asserted for the last packet. MC-- ARB-- SM: This state machine asserts the MC's bus request whenever SQ-- DO-- MED-- OP is asserted. MC-- ARB-- SM also monitors bus grant and reports an error if grant comes at an illegal time. When a request is granted, the state machine determines whether request should be keep asserted for another packet. It also delays requests if the EDAC Read FIFO is busy dumping unwanted data or is being used for a partial write-merge. When the Read FIFO is busy,it is unavailable to drive data beats for a reply packet. MC-- M-- SM: This state machine drives reply packets on to the bus. It monitors bus grant and uses the packet's format code to drive the correct number of beats onto the bus. The states of this state machine are also used to generate MC-- ONE-- TO-- GO and MC-- EXTEND. SQ-- EDAC-- STATE: This state machine runs only when an EDAC diagnostic mode operation is being performed. It stays in the IDLE state until the NOP packet to the EDACs has been enqueued in the Output Queue. Then it advances to the DECODE state where is waits until OQC-- FULL indicates that the output queue has room to enqueue the reply packet to the requester (either an RD-- S-- RPLY ACK or NACK). It then advances through the ENQ-- A and ENQ-- B states, asserting the SQ-- ENQUEUE-- OUT-- A and SQ-- ENQUEUE-- OUT-- B signals to enqueue the reply packet in the output queue. It returns to the IDLE state only when the NOP packet receives a bus grant. It then asserts the SQ-- EDAC-- DONE signal which deasserts the MC-- BUSY-- HI-- N and MC-- BUSY-- LO-- N signals. HI-- SNP-- STATE: Selects the input for the Snoop CAM input mux. EDiiC ASIC Data integrity for the memory resources on the motherboard (52) as discussed hereinbefore, and the daughterboard (58) third level cache (TLC) to be discussed hereinafter, is effected by a standard Error Detection and Control device known in the art, referred to herein as the "EDiiAC" or "EDAC" ASIC, a block diagram of which is illustrated in FIG. 25. The Error Detection and Correction ASIC is a 240-pin PQFP CMOS gate array using LSI's LCA300K, 0.6 micron process, such as LSI part number L1A9566. This part is a virtual functional equivalent for the IDT 49C466, a generally available memory error correction IC, described in detail in the IDT High Performance Logic data book, the teachings of which are incorporated herein by reference. The EDiiAC, in both applications, checks and generates 8 bits of checkbit information across 64 bits of data. Both reads and writes are supported by 16 word deep FIFOs, as well as a single word latch to bypass the FIFO. On the non-ECC side, parity is checked and generated in either polarity. All single-bit errors are detected and corrected. All two-bit and some multi-bit (greater than two-bit) errors are detected. The EDiiAC also implements a byte merging facility, where individual bytes of data are combined with a word of data read from memory. Operations are controlled by a mode register. The EDiiAC can be set up to generate and check ECC or to generate check and correct. Diagnostic information is captured in the EDiiAC and can be read by manipulating the mode register. The EDiiAC is implemented as a functional part of the memory system as described hereinbefore with respect to the MC ASIC, and as a functional part of the third level cache as will be described hereinafter with respect to the third level cache controller (TLCC) ASIC. Cache Coherency System Event Ordering In any multi-bus, parallelized processor design like the present system (50), ordering of events is a potential problem. As an example, consider two processors sharing a database. Both processors have shared copies of the database data. Processor A acquires the lock for the database. processor A modifies a shared database, then releases the lock to that database. If processor B observes the release of the lock before seeing the notification that his hard copy of the data is stale, he will use the stale data, causing unwanted effects that are difficult to find. Note that the addresses of the data and lock can be completely different; there are no address match dependencies. In the present illustrative embodiment of a CCNUMA architecture according to the invention, several mechanisms are implemented and distributed throughout the functionality of the system which ensure ordering and cache coherency. To begin with, the architecture is designed to maintain the philosophy that any two consecutive events that modify system state which when issued by a single entity (e.g. processor, I/O device) must be observed at every other entity in the system in the same order that they were issued. Candidate events are: low priority events: CI-- RD, CI-- WR-- UNLK, WR-- THRU; medium priority events: INV-- CMD, RD-- INV-- RPLY, CB-- INV-- CMD; and high priority events: CB-- RPLY, CB-- INV-- RPLY, WB. Ordering with respect to the initiation of transfers from the source is effected by requiring that for all operation types except writebacks and copyback replies, transfer requesters be pending until they receive an acknowledge of that transfer. If they issue a CI-- RD, they must receive the data return packet. If they issue a CI-- WR, CI-- WR-- UNLK or WR-- THRU they must receive an ACK packet. If they issue a RD-- IM they must receive the data return block, and if they issue an IM they must receive the INV-- CMD as their acknowledge. This mechanism guarantees that the initial packet has either reached the destination (CI-- operations) or has reached the memory controller (MC) and the invalidate/acknowledge packet has reached the backplane bus and has been accepted by all backplane bus interface arrays. Ordering on a motherboard (52) is guaranteed not only with the pending until acknowledge scheme, but also by the artifact of only having one bus, which serializes the operations. The only other consideration on the source board is that it is necessary to guarantee that operations do not reverse within the input FIFOs of the destination arrays or ASICs. Guaranteeing of ordering at the backplane busses is dealt with for invalidate/ack packets only. Initial transfers do not cause invalidates indirectly, as in a snoop-type architecture. In the present invention, all initial requests are routed to the appropriate memory module, which looks up the state of the cache line held in the memory controller's (MC) (82) cache state directory. The memory controller will generate an invalidate/ack packet and route it to the backplane bus (56). Any affected motherboard (52) which cannot accept the packet (i.e if their medium input queue is full) will indicate by asserting RESEND. No motherboard will accept the packet replied to with a RESEND. This guarantees that the packet is accepted by all motherboards at the same time (this includes the motherboard of the original requester). Motherboard Incoming Packets The mechanisms described guarantee that an invalidate/ack associated with an initial request will have reached the backplane bus interfaces of all motherboards (52). There is a case where the invalidate/ack on the initiator's motherboard will be returned to the initiator, but the invalidate/ack on a remote motherboard may remain for a period of time in the bus interface input queue. This allows a scenario where the initiator can un-pend the processor and issue another request which modifies system state. That request must not be allowed to get into the remote motherboard before the earlier invalidate/ack. A Cache Inhibited Operation (CI-- op) followed by CI-- op will not cause a problem because of the acknowledge requirement. A CI-- op followed by invalidate/ack will not cause a problem because of the acknowledge requirement. A CI-- op followed by writeback/copyback will not cause a problem because of the acknowledge requirement. A writeback/copyback followed by writeback/copyback will not cause a problem because the two operations can only be physical memory references, and there cannot be stale shared data anywhere in the system. A writeback/copyback followed by CI-- op will not cause a problem because the first operation can only be physical memory reference, and there cannot be stale shared data anywhere in the system. A writeback/copyback followed by invalidate/ack will not cause a problem because the first operation can only be physical memory reference, and there cannot be stale shared data anywhere in the system. An invalidate/ack followed by invalidate/ack is handled by arbitration on the destination motherboard(s). Incoming medium priority packets are ticketed (time-stamped) when enqueued by the PI (64), and are granted based on age. Note that all medium priority packets are ordered, not just the invalidate/ack ones. The PI may enqueue non-invalidate packets ahead of older invalidate packets while the invalidate packet is waiting to see if it will receive a PIBus (54) resend. An invalidate/ack followed by CI-- op is handled by arbitration on the destination board(s). The ORB (98) won't grant any CI-- RD, CI-- WR, CI-- WR,CI-- WR-- UNLK, WR-THRU operations that arrive at the PI arrays from the backplane until all invalidate/ack packets that had been received within the last 31 cycles have been granted. The reason for allowing CI-- ops to be granted before the older invalidates is that there is a minimum latency for a requester to receive the ack from the backplane, unpend a processor, issue a CI-- op, and have that operation arrive at a remote motherboard. Another requirement is that the invalidate/ack and CI-- op must not be allowed to reverse order in the input queues of the target ASIC. This has been handled in the ASIC designs for the CI (124) and GG (78). The RI ASIC (74) is not a problem since it does not initiate requests, and the MC ASIC (82) is not a problem since MC internal registers are not used as semaphores for coherent communications by software. An invalidate/ack followed by writeback/copyback is handled by arbitration on the destination board(s) in conjunction with the memory controller. The MC (82) guarantees ordering by routing local memory reference to the backplane (54), which then arrive through the medium incoming queue (in the PI). This is only necessary for memory cache lines which have been modified while there is one or more outstanding invalidate/ac ops which has resided in a PI backplane bus input queues for more than 31 cycles. The ORB (98) monitors the PI's (64) medium priority requests, and sends the results to the MC (82). This pin is called ORB-- ORDER-- NEEDED. The MC has a bit (UNORDERED) in the directory that indicates the need to route local replies to the backplane. Note that remote replies do not change the routing requirements of local replies. Once a reply has been routed to the backplane (54) and been "snooped" by the MC (82), further routing to the backplane based on the original condition is unnecessary. The design for the present invention implements the following rules to ensure event ordering. Many of these rules target coherent ordering on the busses between packets of different priorities. 1. All packets to the same cache line address always use the same PI bus. This maintains order between packets of the same priority for any cache block. 2. High Priority Packets can ALWAYS get to memory. Livelock can result if this rule is broken. High priority packets are always accepted by the MC (82), they never get a RETRY. Forward progress of a high priority packet should never depend on the forward progress of another packet. 3. Medium Priority Packets received from the PIBus (56) are granted onto the PixBus (66) in the order that they are enqueued by the PIs (64). Medium packets are ticketed as they are enqueued in PI→PIX queues. Ticketing a medium packet prevents it from being granted the PixBus (66) ahead of any older medium packets. Mediums are ticketed to ensure that memory responses arrive at other nodes in the order that they were generated by the memory. Medium priority packets are enqueued by the PIs (64) in the order that they arrive on the PIBus (56), with one exception. Packets that are targeted at multiple nodes are held by the PI (64) for two cycles before enqueueing them. The two cycles are required for the PI (64) to determine if all the other targeted PIs were able to take the packet. A packet may not be enqueued by any PI (64) unless all the targeted PIs can enqueue it in the same cycle. Because of this two cycle delay, a newer medium packet arriving on a different PIBus could get an earlier ticket that the first packet. Although a RD-- S-- RPLY can not be targeted at multiple nodes, it can get a node beat, which would cause the PI (64) to also delay it for two cycles. This ordering scheme prevents these low priority packets from bypassing older medium priority invalidates, and is needed to made software semaphores work. Invalidates which arrive at a PI (64) less than 31 cycles before a CI-- RD, CI-- WR or CI-- WR-- UNLK are not believed to cause ordering problems. The semaphore ordering problem requires that the invalidate is the local memory's acknowledgment of a remote requestor's modification of a data location. The low priority request would be a request from the same requestor to release the semaphore for the data location. The ordering problem occurs if the semaphore release reaches the local memory before the older data invalidate is snooped by local caches. The invalidate packet is enqueued by the PIs on both the local and remote nodes in the same cycle. It is believed that it requires more than 31 cycles from then for the invalidate to reach and be processed by the remote requester and for the requestor to then issue the semaphore release. The number 31 is programmable to smaller values. 4. A packet with more than one target node will arrive at the PI (64) queues of each node simultaneously. This helps ensure that snoops are seen on all boards in the same order. This means that RD-- INV-- RPLYs and INV-- CMDs that are targeted at local requesters but that need to be snooped on remote nodes are sent external to the PIBus. The local requesters are not allowed to snoop the packets until they arrive back on local PixBus. 5. All CB-- INV-- CMDs and CB-- CMDs are sent external. This ensures that a copyback command targeted at a local requester (one on the memory's own node) will never arrive at its target before an older RD-- INV-- RPLY or INV-- CMD. Since the snoopable RD-- INV-- RPLY and INV-- CMD packets may have to be sent to local requestors via the backplane, this rule ensures that the copyback command will not bypass the invalidate by being sent to the requester via the local PixBus. Instead the copyback command ends up serialized with the invalidate in the PI (64) medium queues. 6. All INV-- CMDs are sent external. Since local RD-- S-- RPLYs and RD-- INV-- RPLYs may be sent external when a cache line is marked unordered, INV-- CMDs must always go external. While the read replies are tracked in the director's Snoop CAM, the INV-- CMDs are not. Be sending all INV-- CMDs external we can guarantee that a local invalidate will never arrive at its target ahead of the read data that it is supposed to invalidate. Sending INV-- CMDs external also prevents stale INV-- CMDs from causing data corruptions. 7. UNDO-- MODs are issued for 88410 return phase miscompares and idles. The CI will issue an UNDO-- MOD if it receives a reply to a RD-- IM or IM request and the 88410 either does not come back to take the reply or comes back asking for a different address. The UNDO-- MOD will take the directory state for that block from modified back to shared, and the CI will drop its RD-- IM or IM. 8. Medium priority packets are serviced before Low priority packets in GG ASIC (78). When the GG (78) receives a low priority packet, it services older snoopable RD-- INV-- RPLY and INV-- CMD packets before the new low packet. When a low priority packet arrives, the GG flags any medium queue entries which contain either RD-- INV-- RPLY packets that are targeted at other requesters or any INV-- CMD packets. All the flagged entries must be serviced before the low packet. Any new low priority packets are RETRYed since the GG does not enqueue low priority packets. Any new medium priority packets are placed in unflagged queue entries because they do not need to precede the older low priority packet. RD-- INV-- RPLYs that are targeted at this GG are data returns, not snoops, and do not need to be serviced before the newer low packets. 9. Medium Invalidates are serviced before Private Resource Requests in CI ASIC (124). The CI ASIC will retry any private resource requests that it receives from the 88410s while there are snoopable invalidates (RD-- INV-- RPLY, INV-- CMD, DB-- INV-- CMD) in the medium input queue. 10. Read Replies are ordered with INV-- CMDs when data has been modified by a High Priority Write from a remote node. Local RD-- S-- RPLYs and RD-- INV-- RPLYs are sent external through the PI (64) queues to be ordered behind older INV-- CMDs when there is a chance that the read data could release a software semaphore for a data location affected by the INV-- CMD. This is actually an ordering problem between high and medium packets, however no ordering restrictions may be placed on the high packets as they must have unimpeded access to the memory. Interfering with this will lead to system livelock. Therefore: 11. Special Attention is paid to Ordering between High and Medium Packets. Maintaining order between high priority writes and medium priority invalidates requires some details. The ordering problem with high priority packets is that a high priority write (WB, CB-- RPLY, CB-- INV-- RPLY) could bypass an incoming medium priority snoopable invalidate (INV-- CMD, RD-- INV-- RPLY). As described hereinbefore with respect to the MC ASIC, while a signal ORB-- ORDER-- NEEDED is asserted, the MC marks any memory block that receives a high priority write as potentially unordered. The MC (82) will send any local read replies to that block external through the PI's to guarantee that they will be ordered behind the outstanding invalidate. Packet Node Beats In order to effect the directed broadcast mechanism according to the invention, i.e. to ensure that only nodes that have a copy of a cache line being accessed are affected, an extra beat is used at the beginning of a packet header. When the directory sends a snoopable operation to the PIBus it attaches the extra beat called a node beat to the beginning of the packet. The node beat indicates to the PIs which nodes need to receive the packet. The node beat is the first beat of any packet which has the Remote Snoop Bit, bit 45, set. The Remote Snoop Bit is set in both the node and header beats. Any packet on the PIXBus with a Remote Snoop Bit set is known to be headed for the backplane and will not be snooped. When the PI (64) drives the packet back into the PixBus, the PI (64) strips off the node beat and clears the Remote Snoop Bit in the header beat. Non-snoopable packets are targeted at only one requestor, the one indicated by the requester ID. So these packets do not need a node beat to keep local requesters from enqueueing them. For these packets, the PI (64) looks at the requester ID to determine if the packet is targeted at a local or remote node. If the ID is remote, the packet is sent to the PiBus. If the ID is local the PI (64) does nothing with the packet and it is delivered on the local PixBus. Only the memory can generate packets with node beats. The following snoopable packets are always generated by the memory with a node beat: INV-- CMD, DB-- INV-- CMD, CB-- CMD. The RD-- INV-- RPLY snoopable packets are generated with a node beat if they are going to a remote node or if they are being sent to the PiBus to maintain order with older invalidates. When the packet is going remote, it gets a node beat regardless of whether it is targeted at one or more nodes. The RD-- S-- RPLY non-snoopable packets are generated with a node beat only if they are being sent to the PiBus to maintain order with older invalidates. These are local replies, so the PIs would not send them to the PiBus if they did not have a node beat. The AC, NACK, RETRY, NOP packets are non-snoopable packets that never get a node beat. Directory Cache Coherency The coherency protocol of the present invention is based on a full-map directory structure maintained in the memory modules. Any time a cache line changes state the directory must be updated. For each cache line the directory knows which nodes (motherboards) have copies of the line and in what state the line is held. For the cache line to transition to a new state, the directory must receive a request from and issue a response to the cache that desires the data. If the new state makes existing cached copies of the line stale, the directory will send an invalidate to all the nodes that have copies of the line. Such invalidates are targeted at nodes, not individual caches, because the directory stores node, not requester, information. Being able to target coherency updates like invalidates at specific nodes is the directory's main advantage as it reduces unneeded snooping. Each node which contains local memory also has a directory. The directory contains one entry for each cache line in the physical memory space of that directory's associated memory. The directory entries contain coherency information for their respective cache lines. The directory entry fields as defined hereinbefore with respect to the MC ASIC, include: VALID BITS: an 8-bit field. Each bit pertains to a specific node on the PIBus. A bit set in this field indicates that there is a valid copy of the cache line at the corresponding node. MODIFIED BIT: a 1-bit field. This bit, when set, indicates that there is a modified copy of the cache line somewhere in the system and the line is stale in memory. When the Mod bit is set, one and only one Valid bit should be set. Data coherency allows only one modified copy of a cache line at any one time. LOCK BIT: a 1-bit field. This bit indicates that there is a lock set on this cache line. When this bit is set, all accesses to the corresponding cache are retried (except for the unlock operation). UNORDERED BIT: a 1-bit field. This bit indicates that this cache line may be subject to packet ordering constraints. When this bit is set, some read replies to local requesters may have to be sent via the PIBus, i.e. "external", to preserve coherency packet ordering. BUSY--COPYBACK CAM HIT. This is not a directory field although it could be implemented as one. The directory has a 2 entry CAM which stores the address, opcode and requester ID of requests for which the directory must request a copyback. All memory requests are looked up in the Copyback CAM in parallel with accessing the directory entry. A hit for the Copyback CAM indicates that there is an outstanding copyback pending on that cache line. When this bit is set, all accesses to the corresponding cache line are retried (except for writebacks and copyback replies). All memory addresses on the PIBus (56) are routed to the appropriate memory module. Each address is put in a queue for service by the memory. Each address is looked up in the directory and the memory will generate a response based on the directory contents and the type of access requested. The memory will send data and acknowledgment responses only to the node that requested the cache line. Snoopable responses are directed only to nodes that have a valid copy of the accessed cache line. Directory States The memory directory can hold a cache line in one of five states, as described hereinbefore and elaborated upon hereinafter. Those states are: UNUSED. This state means that the cache line is not resident in any caches in the system. The only valid copy of the line is in memory. All valid bits and the modify bit are zero in this state. SHARED. This state means that there may be caches with copies of the cache line that requestors. For further discussion it is necessary to distinguish between cache states and directory states. A cache keeps state information with each cache line it holds. Those states follow: Invalid. This state means that the cache does not have a valid copy of the line. Shared. This state means that the cache has a valid copy of the cache line and that this copy is the same as the copy held by the memory. Other caches in the system may also have shared copies of this line. Exclusive. This state means that the cache has a valid copy of the cache line and that this copy is the same as the copy held by the memory. No other cache in the system has a valid copy of this line. Modified. This state means that the cache has a valid copy of the cache line and that this copy is not the same as the copy held by the memory. This is the only valid copy of the cache line in the system. The coherency model based on 88110 processors does not support the EXCLUSIVE cache state. Therefore the CI ASIC (124), described hereinafter, must make the EXCLUSIVE state of the 88410 and 88110 caches invisible to the PIBus and the directory. The directory will mark lines modified that may be marked exclusive in a cache. The directory will expect a copyback on accesses to modified lines and the CI (124) must generate a copyback from 84410 in this case. Directory and Cache State Transition The tables in FIGS. 26A, 26B and FIG. 27 summarizes the changes in directory and cache state for each possible memory transaction of the present invention. Cache state refers to the state of the 88410 and I/O caches. The tables also show the type of packet issued by the directory/memory in response to each request. The directory maintains coherency in the system's caches by issuing copyback commands and invalidate commands as needed. There are separate tables for cached requests, FIGS. 26A and 26B, and cache inhibited requests, FIG. 27. A cached request is one that causes data to be read or written in a cache. A cache inhibited request does not read or write data in a cache and it is assumed that a cache will invalidate a valid cache line if it issues a cache inhibited request to that line. Cache inhibited requests will generate coherent responses from the memory directory, i.e., they are snooped. The four lines in each table entry list the following information based on the request and the INITIAL state of the cache line in the directory: 1. The memory response. This is the operation that the memory will generate based on the request and the INITIAL state of the line. 2. The NEXT state of the directory. This indicates the state transition in the directory caused by the request This is the final state of the directory after all activity initiated by the operation is complete. 3. The NEXT state of the cache which initiated the operation. This is the final state of the cache after all activity initiated by the operation is complete. 4. The NEXT state of all other caches in the system. This is the final state of the caches after all activity initiated by the operation is complete. For transactions that cause a copyback command (CB-- CMD or CB-- INV-- CMD) the state transition tables show the directory and cache state after the copyback command has been issued and received and cache state has been updated, but before the copyback reply has been generated. If the directory detects one of the states marked as "Not Possible", the MC ASIC (82) will issue a fatal coherency error. The "No Change" entry in the table means that a cache line can be shared in some caches and invalid in others and the operation will not change that state. The following legend defines abbreviations in the tables in FIGS. 26A, 26B and 27 (and elsewhere in this Specification). RD-- S=Read Shared. RD-- S-- RPLY=Read Shared Reply. RD-- IM=Read with intent to modify. RD-- INV-- RPLY=Read invalidate command. RD-- S-- RPLY=Read shared reply. CI-- RD=Cache inhibited read shared. CB-- CMD=Copyback (shared) command. CI-- WR=Cache inhibited write. ACK=acknowledgment. WB=Writeback. UNDO-- MOD=Undo Modified State. UNDO-- LK=Undo Lock State. INV-- CMD=Invalidate command. CB-- INV-- CMD=Copyback invalidate command. CI-- RD-- LK=Cache inhibited read request to lock. CI-- WR-- UNLK=Cache inhibited write unlock. Most coherency issues are easily handled by the directory issuing coherency commands like invalidates and copyback commands and by maintaining order between packets. However there are some special cases that require more attention. One such area is stale packets. These occur in four main ways: unsolicited writebacks of data which cause stale copyback commands; multiple bus routes allowing memory responses to arrive ahead of older snoop commands which cause stale copyback replies; multiple requesters simultaneously attempting to modify the same cache line which cause stale IMs; and stale IMs combined with multiple bus routes which can result in stale INV-- CMDs. A cache which holds a modified copy of a cache line may choose to write it back to memory at any time to make room for new cache lines. This writeback will appear on the bus as a WB from the 88410 and as a CB-- INV-- RPLY from the GG Cache. If the directory sends the cache a copyback command while the cache is voluntarily doing a writeback, the writeback will pass the copyback command in transit. When the writeback arrives at the memory the directory uses it to satisfy its outstanding copyback request. When the copyback command arrives at the cache, it is snooped but does not cause a copyback since the cache has already given up its modified copy of that cache line. Once the writeback is generated the copyback command is considered stale, since it is no longer needed. Stale copyback commands may appear at caches at any time. Normally they only cause an extra snoop. However if the target cache line has remained shared in any caches and the copyback command is a CB-- INV-- CMD, those caches will have to invalidate the line. A stale copyback command can even cause a stale copyback reply from a local requestor. All copyback commands are sent via the PIBus, even when targeted at the memory's own node. This is an ordering rule which prevents copyback command from arriving ahead of older invalidate commands which may have been sent to multiple nodes, and therefore were sent via the PiBus. Once a cache has done a writeback of a line, the directory is free to give it to other requesters. If the line is requested by a local requester, the memories' reply would be sent via the PixBus, allowing it to arrive at its target before the older stale copyback command which may still be in the PI queues. The new requester may even be given permission to modify the line. Once the stale copyback command does arrive, the cache has no way of knowing that the command is stale and will have to snoop it. If the cache has only a shared copy, then an unnecessary invalidate may be done and the cache will have to request the line from memory again. If the cache has a modified copy, it will have to do the requested copyback. This is a stale copyback reply which the directory is not expecting to see. The directory handles stale copyback replies (sometimes called unexpected copyback replies) as though they were writebacks, with the exception that a CB-- INV-- RPLY does not leave any shared copies in any caches. Stale copyback commands and stale copyback replies do not cause any coherency problems. The data is NOT stale and can be safely written to memory. There is a slight performance penalty because of wasted bus and snoop cycles and because they cause processors to writeback cache lines before they are done with them. For stale IM squashing, if multiple caches have shared copies of the same cache line, more than one of them may request modified access to the line by issuing an IM packet. The directory honors whichever request it receives first. The first IM receives an INV-- CMD response which will be snooped by all the caches which have shared copies of the line. However the other IM requests were issued before the INV-- CMD arrived. The cache that got the modified status will take the INV-- CMD as an acknowledgment because it contains its requestor ID. The other caches will snoop the INV-- CMD, invalidate their cached copies, drop their outstanding IM request and issue a RD-- IM request in its place. The outstanding IM requests are dropped because they are stale, since those cache's no longer have shared copies of the line. Stale IMs can also be caused by the memory responding to a RD-- IM with a RD-- INV-- RPLY. If other caches have IMs outstanding when the RD-- INV-- RPLY arrives for snooping, their IMs become stale and the cache invalidates and issues a RD-- IM instead. If the directory can tell an IM is stale it will not service it and will not issue a reply packet. Stale IMs are not a problem as long as all nodes can tell they are stale. Coherency errors will develop if stale IMs are serviced by the directory. Therefore stale IMs are squashed whenever they are recognized as stale. Squashing means that the IM is removed from the request stream (sometimes the IM is actually replaced with a NOP). The following subsections describe how stale IMs are detected and squashed at various places in the system. In the CI queues, when the CI (124) snoops an INV-- CMD that does not have its requester ID but does match the block address of an IM request in its Outstanding Request Register (ORR) (300), it will clear the ORR and will no longer expect a reply to that request. The CI puts the INV CMD on the 88410 bus for snooping. The 88410 invalidates its shared entry and a RD-- IM is issued in place of the IM. Clearing the ORR in this case is called squashing. The CI will also squash the IM if it snoops a RD-- INV-- RPLY that matches the IM's address. The CI (124) may issue a NOP when it squashes an IM that it is about to put onto the PixBus (88). Stale IMs are also squashed in the PI (64) queues. If a RD-- INV-- RPLY or INV-- CMD in the medium queue passes an IM to the same cache line in the low queue, the PI changes the IM packet to a NOP by altering the opcode stored in that queue entry. Invalidates in the PIX→PI medium queue squash IMs in the PI→PIX low queue. Invalidates in the PI→PIX medium queue squash IMs in the PIX→PI low queue. If the PI receives a RD-- INV-- RPLY or INV-- CMD from the PIBus just before it drives an IM onto the PI bus, it issues a PIBus Resend to recall the IM. This will keep the IM at the head of the PIBus output queue longer so that the PI will have time to squash, if required. The PI does no address comparisons before issuing the Resend, so the need to squash is not guaranteed. If the PI did not Resend the IM, it might not have time to change the IM opcode to a NOP if a squash is needed. Stale IMs are also squashed in the MC queues. RD-- INV-- RPLY or INV-- CMD packets in the output queue squash IMs to the same cache line in the input queue. The IM opcode of a squashed IM is replaced with a NOP opcode. When the NOP reaches the head of the MC input queue, the packet is dequeued and discarded. Stale IMs from remote requesters (those not on the same node as the targeted memory) never survive queue squashing. There is a straight path from the MC→PI→CI for the invalidate packet and the IMs follow the reverse of the same path. It is impossible for the invalidate and the IM not to pass each other, which will result in the IM being squashed. However stale IMs from local requesters (those on the same node as the targeted memory) will often survive queue squashing. This is because some invalidate packets are sent through the PI queues rather than directly to their local targets via the PixBus. A local IM request will always travel directly to the MC via the PixBus and can bypass an older invalidate packet in a PI queue without getting squashed. This means that the IM will arrive at the directory and the directory will attempt to process it. The CI can handle this case by issuing an UNDO-- MOD (Undo Modify) when it received the INV-- CMD. In the present invention, the system would work without directory squashing, but it is still more efficient to squash IMs (Intent to Modify) as soon as possible. ORB ASIC The ORB ASIC is a functional element of the system according to the invention, which basically provides two functions: controlling arbitration for the motherboard bus structure (i.e. the PIXbus and its sub-busses); and controlling the BAXBAR switch bus transceiver. In the present illustrative embodiment, the ORB and BAXBAR are implemented in the same ASIC. The ORB provides the arbitration services for all clients on the individual motherboards or node subsystem. The ORB also provides the control necessary to allow the BAXBAR switch, described hereinafter, to propagate transfers. The ORB is instrumental in guaranteeing forward progress and avoiding livelock/deadlock scenarios. This is accomplished by use of three levels of priority of requests, use of three levels of "busy" indications from potential targets, support of "deli-counter" ordering across all four PI arrays, use of windowed arbitration with a fairness algorithm within windows, and by means of configuration-time programmability of arbitration and grant timing. The ORB also provides ordering support for ensuring that CI-- WR, CI-- RD, CI-- WR-- UNLK, WR-- THRU operations from a processor do not bypass invalidates caused by that same processor. The windowed arbitration implemented by the ORB implies that all outstanding requests are captured simultaneously, and serviced to completion (if possible) prior to re-sampling later requests. There is an exception to the windowing of requests local to a motherboard. That exception is that although CI, GG, RI and PI requests are windowed, the MC request is not. The reason for this is to keep the MC output queue emptying. If the MC request was windowed, only one memory bus tenure would be allowed within a request window. The effect of this is to bottleneck memory references and to under-utilize DRAM bus bandwidth. This occurrence of bottlenecking the outputs of memory is a result of the split transaction nature of the PIXBus. In a system that doesn't have split transaction system busses, all references by requesters to memory imply that the output of memory is immediately serviced--hence one memory transaction is retired for each requester's transaction. In the present implementation according to the invention, there is a single bit state machine which tracks when a window is in progress. This bit also serves as a mux select to re-circulate the remaining windowed requesters into the requester register. This window bit is set upon detecting that there is an outstanding request needing service. It is reset if either all outstanding requests have been granted the system bus, or if none of the requests remaining in a current requester window register can be serviced because of the assertion of busy signals. The ORB is effectively divided into a plurality of functional blocks, illustrated in FIG. 28, described hereinafter. BB-- RQ-- REQUEST MODULE This module collects all of the bus requests, and arranges them in "windows" to avoid starvation. A new window is sampled when there are no outstanding requests in the previous cycle, or where there were requests in a grant cycle, but all were blocked from being granted because of busys or tickets that cannot be granted. No outstanding requests is obvious. What is less obvious is when all requesters are blocked by busys. In a traditional system with RETRY instead of queue full busys, that loosely correlates with all remaining requesters having gotten the bus, seen RETRY, and re-issued bus requests (honored in the next window). There are also instances when a PI medium request cannot be honored because the ticket presented for that operation is next in sequence. This occurs when a PI has more than one outstanding medium request. Since only one medium request is serviced per window, that PI may hold a blocking ticket number until the next window is defined. This condition is reported from the BB-- TI-- TICKET module as TI-- FINISHED-- TICKETS. The mechanism to determine when all requesters are blocked from being granted is detecting that there are no potential candidates for granting (unqualified grants) when a TRACKER state machine, illustrated in FIG. 29, is about to enter the GRANT state. This implies that there is at least one outstanding request and that no-one can be granted. The feature of starting a new window when there are blocked requesters can be defeated. Normally it is undesirable to wait until all requesters have been granted before opening a new window for performance reasons, but it has been included as a debug tool (EMPTY-- WINDOW scan bit). There is an additional debug feature that inhibits grants up to three cycles after defining the start of a new window (W-- DELAY[1:0]). This module contains registers that are set when there are requests being asserted from the other ASICs at the time that a new window is defined (i.e., "windowed requests" for all requesters). Each register remains asserted until a grant is issued for the respective request, at which time it is cleared. There is a single window for each CI and GG ASIC (400, FIG. 28). The CI and GG ASICs or arrays each present three requests: high, medium and low. They are allowed to change their requests or withdraw their requests, but are not allowed to assert more than one request line at a time. The request lines are or-ed together 402 to determine the setting of the respective request window. The request window is cleared if the ASIC withdraws it's request. The windowed request is then generated by combining the window bit with the registered high, medium and low registered request lines. If the UNWINDOW-- HI option is asserted, the high request line registers for these ASICs are or-ed into the request window every cycle. The MC and RI ASICs each have one window, since they only have one request, medium. Normally the MC is not included in the windowing scheme, but it has a degrade mode, i.e., MEM-- INCLUDE, that allows the MC to be subject to the windowing. When MEM-- INCLUDE is not asserted, the request window is updated continuously with the MC request line. The PI ASICs have three window registers, one each for low, medium, and high requests. The high request windows allow continuous updating from the high request lines from the PI if the HIGH-- INCLUDE option is cleared. The BB-- RQ-- REQUEST module checks to make sure the CI and GG ASICs do not simultaneously issue multiple priority requests. The module also checks that the other ASICs do not withdraw their requests without being granted. BB-- TI-- TICKET Module The BB-- TI-- TICKET module keeps track of the ordering of medium priority requests from PI requesters, and maintains ordering of cache inhibited low requests with respect to medium invalidate type requests. The BB-- TI-- TICKET module instantiates eight other modules to effect its operation, four being BB-- LOW-- FIFO, and four being BB-- MED-- FIFO, for use as ticket fifos. Snoopable operations (like Invalidate Command, Copyback Invalidate Command, Copyback Command, Read Invalidate Reply) must arrive in the time sequence with which they were issued. All snoopable operations are MEDIUM priority, and issued by MC ASICs, however, not all medium priority operations are snoopable. Because there are four backpanel busses, and memory queues, it is possible that snoopable operations could reverse order because of different backpanel latencies. This has been avoided by the following three mechanisms. First, a single source cannot issue a request that will result in a snoop condition until any similar outstanding operation has been replied to with an acknowledge. Second, the backpanel bus interface ASICs (PIs) do not accept a snoopable operation unless all PIs on all motherboards are able to accept the operation into their input queue. Third, each incoming snoopable (medium priority) request is ticketed with a time stamp, and the ORB only services their requests in the proper order. The TI-- TICKET module deals with the assignment of tickets and the ordering of their grants. There are 16 tickets, sufficient to handle the four medium queue entries in each of the four PI arrays or ASICs. The tickets are maintained in the ORB as a set of four fifos 404, one for each PI. A signal from each PI, PIx-- NEW-- CUSTOMER-- N, announces the arrival of a medium priority operation at the backpanel. The fifo is then loaded with an incremented value of the last ticket to be assigned. If multiple PIs assert PIx-- NEW-- CUSTOMER-- N simultaneously, they will each be assigned the same ticket. Tickets are four bits in length and wrap. The fifos are designed to start empty on WARM-- RST-- N. The input is the new ticket value to be assigned, the push is the PIx-- NEW-- CUSTOMER-- N pin coming from the PI, and the pop is a buffered version of the grant indication sent to the PI to service the earliest medium request. The output is the oldest ticket captured in the fifo. Note that overflow and underflow detection is provided. Since requests are windowed, there is a condition which occurs in which one PI could have obtained two or more tickets, the additional tickets having a lower value than other PIs' tickets within the same request window. In that event, since only one ticket can be retired within the window, when a PI which holds a ticket with the oldest value does not have a valid windowed request outstanding, no more medium PI grants will be issued until the next window is established. The BB-- TI-- TICKET logic is responsible for determining the oldest outstanding windowed PI request and informing the BB PE-- PRIORITY-- ENCODER module. This is accomplished by keeping track of the ticket number for the last medium PI request to be granted. Compares are made between outstanding requesters' ticket numbers and the last ticket to be granted. A match indicates that those outstanding requesters must be serviced prior to other outstanding windowed requests. Compares also are made against an incremented value of the last ticket to be granted. If there is no match for the last ticket to be granted, but there is a match between a windowed request ticket and the incremented value, then that requester must be serviced prior to other outstanding windowed requests. Out-of-sequence ticket detection logic is provided. This is identified when there are one or more PI medium request lines asserted, and none of their tickets match either the last ticket granted or the incremented value of the last ticket granted. BB-- PE-- PRIORITY-- ENCODER The BB-- PE-- PRIORITY-- ENCODER module selects one grant candidate from each of three categories, high, medium, and low. It takes as input device busy information from the BB-- GR-- GRANT module, ordering information from the BB-- TI-- TICKET module, and windowed requests from the BB-- RQ-- REQUEST module. The BB-- PE-- PRIORITY-- ENCODER module takes as inputs; the set of windowed requesters from the BB-- R-- REQUEST module, various combinations of registered BUSY conditions from the BB-- GR-- GRANT module, medium PI request priority TI-- PIx-- OLDEST information from the BB-- TI-- TICKET module and TR-- TRACKER-- GRANT-- NEXT from the BB-- TR-- TRACKER module. All of this information is condensed, and the requests prioritized within one cycle. The result is the generation of up to three grant candidates, one for high priority grants, one for medium priority, and one for low priority. These are referred to as the "unqualified" grants, the signals that the BB-- PE-- PRIORITY-- ENCODER module outputs. This unqualified grant is then shipped to the BB-- GR-- GRANT module. Competition within a window for high priority unqualified grant (PE-- U-- GNT-- xxx-- HI) is implemented with a wire-or arbitration net, which results in ultimate selection of a single requester to receive the grant. Each requester is assigned a fixed three bit encoding and this encoding is xored with the shuffle code to generate an ID. Each requesting device drives it's IDs onto an arbitration net, i.e., or'ing net and near the end of the cycle reads it off of the net. What is read is compared with what it drove and, if the ID read matches the ID driven, then that requester will become the unqualified grant candidate. For the high priority arbitration net, the initial assignment is xored with the shuffle code such that bit 2 of the assignment is xored with bit 2, bit 1 is xored with bit 1, and bit 0 is xored with bit 0. Competition within a window for medium priority unqualified grant (PE-- U-- GNT-- xxx-- MED) also is implemented with a wire-or arbitration net. Since there are ten medium requesters, a three bit arbitration net is not sufficient. The medium requesters will be put into two groupings. The MC and RI requests will be treated as one request group, and the eight other requesters will be treated as another request group. The MC has priority over the RI within the MC/RI request group and the MC/RI request group normally will have priority over the other group, the CI/GG/PI request group. In the case of concurrent requests from the two groups that are potential candidates for unqualified grant, the tie will be broken by examining a ping-pong toggle. The toggle flips every time there is contention between the two groups. Each requester in the CI/GG/PI request group is assigned a fixed three bit encoding. This encoding is xored with the shuffle code to generate an ID. Each CI or GG ASIC with a windowed request,. The PIs use the TI-- PIX-- OLDEST to determine if they drive the medium arbitration net. Multiple PIs can have their TI-- PIx-- OLDEST asserted. Each PI with TI-- PIx-- OLDEST asserted, that is medium priority arbitration net, the initial assignment is xored with the shuffle code such that bit 2 of the assignment is xored with bit 0, bit 1 is xored with bit 2, and bit 0 is xored with bit 1. This provides a different arbitration priority pattern from high and low requests within one window. Competition within a window for low priority unqualified grant (PE-- U-- GNT-- xxx-- LO) is implemented with a wire-or arbitration net. Each requester is assigned a fixed three bit encoding, and this encoding is xored with the shuffle code to generate an ID. Each requesting device low priority arbitration net, the initial assignment is xored with the shuffle code such that bit 2 of the assignment is xored with bit 0, bit 1 is xored with bit 1, and bit 0 is xored with bit 2. This provides a difference in low request prioritization from either high or medium request priorities within one window. BB-- GR-- GRANT The BB-- GR-- GRANT module takes the three candidates from the BB-- PE-- PRIORITY-- ENCODER module, does a last-minute check of appropriate device busy signals, and issues a grant to one of them as specified by the BB-- PE-- PRIORITY-- ENCODER module. BB-- TR-- TRACKER MODULE The BB-- TR-- TRACKER module takes the grant information from the BB-- GR-- GRANT and takes a "ONE-- TO-- GO" signal from the granted device. It determines when the bus transfer has completed, and instructs BB-- GR-- GRANT module when the next grant can be issued. The BB-- TR-- TRACKER module contains a state machine, illustrated in FIG. 29, that tracks the progress of a bus master through the transaction. RESET places the state machine in the IDLE state. The state machine is kicked off by a registered valid request, and moves from the IDLE cycle to the GRANT cycle. If the grant is inhibited by the assertion of a BUSY, the state machine will remain in the GRANT state. When the bus master is granted, the state machine moves from the GRANT state to the QUIESCENT state. This state is visited for one cycle only. The state machine is then placed in the BUS-- BUSY state. If the appropriate ONE-- TO-- GO has not been asserted, the state machine will remain in the BUS-- BUSY state. When it is asserted, the state machine will move to either the GRANT state or the IDLE state depending on the existence of additional serviceable requests. The TR-- TRACKER module contains the ONE-- TO-- GO registers for all requesters. ONE-- TO-- GO signals are registered first, then are muxed to select only the PROPER-- ONE-- TO-- GO for the state machine. Pre-registered ONE-- TO-- GO signals are also available from this module in the form of EARLY-- ONE-- TO-- GO, used by the BB-- CONTROL module to initiate the assertion of PORT-- OE. The mux selects are determined by the selection of the bus requester to grant. The mux selects originate in the GR GRANT module. The state machine generates an ok-to-grant signal which the GR-- GRANT module uses. This signal is TR-- TRACKER-- GRANT-- NEXT. This signal is asserted either when the state machine is (i) in IDLE and someone requests, (ii) in GRANT when the grant has been inhibited, or (iii) in BUS-- BUSY when the transfer is ending and there are more outstanding, and there are no debug features inhibiting the grant. The state machine include a stall feature that allows partial or full serialization of the arbitration portion of transfers. To accomplish this, there is a three bit scan loadable configuration register. The contents of this register cause the state machine to wait a number of cycles before allowing the next grant. In addition, there are hooks to inhibit further grants. This is referred to as "QUIESCE". It is available pre-registered by the ORB. TS-- TRANS-- START Module The BB-- TS-- TRANS-- START module takes the grant information from BB-- GR-- GRANT and issues a Transaction Start (TS) first on the bus of the granted device, then on all the requesters on other motherboard busses. The TS-- TRANS-- START module generates the TS signals and distributes them to the bus clients. TS asserted indicates to a client that the accompanying header transfer on the data portion of the bus is the start of a transfer. The first cycle after a GRANT is a quiescent cycle, the cycle in which the TS will be driven on that bus. This allows other clients that reside on that particular bus to recognize the start of the transfer. The second cycle after GRANT is the cycle before the start of the transfer is broadcast to other motherboard local busses through the register stage of the BAXBAR. TS will be driven on all the other busses (but not on the requester's bus) during this cycle. The TS-- TRANS-- START module also generates the mux selects necessary to identify the PROPER-- ONE-- TO-- GO signal for the TR-- TRACKER state machine for use in identifying the end of a transfer. BC-- BAXBAR-- CTL Module The BB-- BC-- BAXBAR-- CTL module takes the grant information from BB-- GR-- GRANT and instructs the BAXBAR arrays as to which port the master device is on and which ports to drive for each cycle in the transfer. The BC-- BAXBAR-- CTL module generates the BAXBAR control for transfers. These control lines comprise a three bit encoded requester drive port (DR-- PORT[2:0] and eight unarily encoded BAXBAR port output enables (PORT-- OE[7:0], and a single control line XFER-- ENB-- N. The XFER-- ENB-- N signal indicates the pending end of a transfer and is used by the BAXBAR to determine when to check the source bus for good parity. The requester drive port, DR-- PORT[2:0], is driven to the BAXBAR during the quiescent cycle following a grant, and every consecutive cycle for the duration of the requesters bus transfer. The PORT-- OE[7:0] is driven to the BAXBAR during the quiescent cycle following a grant, and will de-assert one cycle before the end of the transfer on the requester's bus. This allows the BB to first register the PORT-- OE, and DR-- PORT In addition. For non-memory requester transfers, the EDAC ports (bits 3,2) will have their output enables extended for one cycle if the transfer is a partial write. Other modules used by the ORB include: The BB-- Fl-- FATAL-- IN module which collects fatal error indicators from all motherboard asics and the micro-processor, and informs half of the motherboard ASICs that a fatal error has occurred. The BB-- FX-- FATAL-- IN-- EXT module uses the result of BB-- Fl-- FATAL-- IN to inform the other half of the motherboard ASICs that a fatal error has occurred. The outputs of the BB-- CONTROL-- SIGNALS module are used to control which pins are inputs and which pins are outputs. These assignments are static when the ASIC is being used as an ORB. The BB-- ERROR module collects internally detected error conditions from the other modules, and asserts the FATAL-- OUT-- N signal, which then goes to the BB-- Fl-- FATAL-- IN module. BAXBAR Register Switch The Baxbar is a registered cross-bar switch which serves as the interconnect path for the Sierra board-level busses. The Baxbar is implemented with four ASIC slices in conjunction with the ORB ASIC described hereinbefore. Each ASIC slice is a 240 pin LSI300D CMOS array. It will be capable of operation at clock frequencies up to 50 MHz. A functional block diagram of the BaxBar switch is illustrated in FIG. 30. The Baxbar registered crossbar switch supports six 19 bit ports and two 18 bit ports. The switch control is comprised of a 3 bit source port select (DR-- PORT) and an eight bit output enable control (PORT-- OE). The tables of FIGS. 31A, 31B and 31C illustrate crossbar source selection, PORT-- OE assignments, and port to bus mapping of the BaxBar crossbar switch, respectively. The six 19 bit ports are referred to as A, B, CM, DM, D0, D1. The two 18 bit ports are referred to as C0, C1. There are two main modes of operation referred to as non-generic mode and generic mode. These modes control the way ports C0 and C1 behave. In non-generic mode, ports C0 and C1 are given extra control to connect to EDACs. In generic mode, this control is disabled giving 7 ports that behave identically. The eighth port may be used in this mode, though it will experience an extra delay in some cases. Parity is checked on the lower 18 bits of the internal bus that feeds output ports A, B, CM, DM, D0, D1. Any of the eight possible sources can potentially be muxed onto this bus. The 18 bits is made up of 2 parity bits associated with two 8 bit busses. On a parity error (exclusive OR of 9 bits=1), the error is latched, qualified with a parity enable and sent to the module BB-- ERROR. Four 16×18 RAMS are provided in the Baxbar to log information about the state of the Baxbar during the last 32 cycles. The two 18 bit ports are connected to EDACs and port CM is connected to the Memory Controller. As outputs, the source data (except last beat) that feeds out of the C0, C1 ports is held for two cycles to provide the EDACs with additional hold time. during the last beat, the data is held for one and a half cycles. Note that one of the EDACs outputs the even data beats, the other the odd beats. This is controlled by sample ADDR-- 3-- IN during the cycle where the source is presenting the first data beat. If this signal is low, CO outputs the even data beats and C1 the odd beats. GG ASIC The GG ASIC (78) provides an interface between the 50 MHz PIX (76) bus and a 25 MHz PCI bus (79a,b). Each of the two PCI busses is connected to an integrated Small Computer System Interfaces (SCSI) interface and to a single PCI expansion board. One of the two PCI busses also is connected to an integrated 10 Mb Local Area Network (LAN) interface 286. The GG ASIC also sources the 25 MHz clocks for the PCI bus. A block diagram of the GG ASIC is set forth in FIG. 32. The GG ASIC (78) acts as a PCI Bus master on behalf of JP initiated transfers on the PCI Bus. All transfers between a JP and an external PCI Bus device are cache inhibited. It also acts as a PCI Bus slave on behalf of an external PCI Bus master initiating transfers to system memory. A small cache is provided in the ASIC (78) and is used for DMA transfers between the external PCI Bus master and system memory (86). The GG ASIC cache supports exclusive modified cache line ownership as well as shared ownership. A cache line is eight beats long. Address transactions coming from the 64-bit multiplexed PIX (76) bus into the GG ASIC (78) are registered in the Slave OP, Snoop or ADDR/Header buffers depending on the command decode. The ADDR/Header addresses are compared against the outgoing request register to identify packet replies to I/O cache line fills. The Slave Op addresses are used to access PCI configuration, PCI I/O and internal GG ASIC configuration registers. The Slave Op addresses are decoded by an address decode unit that generates the four PCI Bus ID and multiple internal GG register selects. Only one data beat is associated with a cache inhibited Slave operation, and the GG ASIC makes the restriction that only the least significant DWORD [bits 63:32] contains valid data. The Snoop Addresses are used to invalidate or copyback a cache line and are looked up in the I/O cache tag ram. If the cache line has been modified, the GG ASIC will copyback the cache line back to memory with a CB-- INV-- RPLY. If a cache line is marked shared in the cache, its status will be changed to invalid. Because the tags are a shared resource, i.e. support PCI and PIX bus slave accesses, a busy mechanism is implemented to handle tag access collisions. Addresses from the PCI Bus enter the GG ASIC (78) on the 32-bit PCI Bus multiplexed address and data lines and each address is compared against the PCI Bus memory range registers. For a PCI Bus master to system memory transfers (DMA), the address is passed to the cache. A cache hit is followed by a PCI Bus transfer without any PIX bus activity. A cache miss forces the GG ASIC (78) to initiate the appropriate PIX bus activity to load the cache with the requested data while the PCI device is retried. This may include initiating a writeback, with a CB-- INV-- RPLY, prior to filling the cache line. The capability to retry on cache misses is programmable. This allows flexibility when dealing with PCI bridges which may not come back with the same request when retried. Data from the 64-bit PIX bus enters the GG ASIC (78) through the Data Return buffer that interfaces with the GG ASIC internal cache. Data is then moved from the cache to the PCI Bus as requested by the PCI interface. There are also two queues used by the GG ASIC to store incoming medium packets, i.e., snoops and data replies, and outgoing retries. Incoming medium packets are stored in a four deep queue to be processed by the cache. This includes snoops, resulting in an invalidate or copyback, and data return packets for cache line fills. A medium busy signal is asserted to the PIX bus arbiter when this queue has three or more entries in it, to prevent an overflow condition. The retry queue is three entries deep and holds retry packets for low priority operations that can not be completed by the GG ASIC, as the GG ASIC performs one low priority operation at a time. When this queue is full, i.e. all three entries valid, the GG ASIC will assert a low busy signal to the PIX bus arbiter, to prevent more low priority packets from arriving. RI ASIC Each motherboard (52) contains all the local resources that are required of a system (50). The resource logic on the motherboard (52) includes a Microcontroller (102), state-recording EEPROMs (Electrically Erasable Programmable Read Only Memory, not shown), NOVRAM (Non-Volatile RAM), and SCAN interface logic (104). The resource logic is duplicated on each motherboard (52), but a working system (50) only ever uses the resources section of the board in either slotO or slot1 of the backplane system (54) as system wide Global Resources. An RI (Resources Interface) ASIC (74) provides the interface between the PIXbus (72) and the devices within the Resources section on the motherboard (52). The RI ASIC or array provides an interface between the PIXbus and the Resources Bus. The resources bus provides the JPs access, through the RI portion of the PIX bus (RI bus), to local resources required by the system, including the test bus controller and the diagnostic bus interface. The RI ASIC acts as a Resources Bus master on behalf of JP initiated transfers on the Resources Bus. The RI ASIC is not a slave on the Resources Bus and as such will not initiate a read or write request on the PIXbus. Rather it services three types of operations; CI-- RD--, CL-- WR and RD-- S. A RD-- S request will be honored only if the requested resource device is marked as encacheable. The EEPROM on the Resources Bus is encacheable, allowing faster booting of the system. The RI responds to the upper 4 Megabytes of memory, assuming its global bit is set, and requests to it's control space. A functional block diagram of the RI ASIC is shown in FIG. 33. The RIbus state machines, illustrated in FIGS. 34, 35 and 36, control the interface to the RIbus. The RIbus master will assert a bus request to the motherboard arbiter and, when, granted, drive the appropriate RIbus control, header and data to access the resources section., MACH electrically erasable, programmable devices. DAUGHTERBOARD ASICs In addition to the various ASICs and functional elements on the motherboard, the daughterboard includes ASICs as well, to provide and control an interface between the Motorola 88410 cache controller bus (126, 128, 130, FIG. 3) and the Daughterboard bus (88) (Cibus), and to control the third level cache resident on the daughterboard. CI ASIC The CI ASIC (124) provides an interface between the Motorola 88410 cache controller bus (126, 128, 130 FIG. 3) and the Daughterboard bus (88) (Cibus). The CI ASIC (124) provides support for two MC88410s cache controllers (112) The CI ASIC (124) controls the MC88410 address (128) and data (126) bus arbitration and provides system status for the MC88410 cache controllers (112). A block diagram of the CI ASIC is provided in FIG. 37. The MC88410 address bus (126) and the lower 32 bits of the data bus (128) are multiplexed together, before interfacing to the CI ASIC (124). This is done in order to decrease the number of pins needed, so that the CI ASIC could fit into a 304 mquad package. Four 16-bit transceivers (136) are used to multiplex the address and data bus, creating a 32-bit address/data bus (134). Two transceivers for the address path (136b) and two transceivers for the data path (136a). Two output enables, and two direction signals are provided by the CI to control these transceivers (not shown). The CI ASIC (124) accepts all addresses driven on the MC88410 address bus (128) by the MC88410s (112). These transactions are referred to as initial transactions. The CI ASIC (124) decodes the address to determine if a Cibus tenure is required. Transactions addressed to CI ASIC (124) internal registers are referred to as private resources and are serviced immediately. Transactions that are shared reads may be serviced by the TLC memory (116) if the address tag is valid. The TLC-- HIT (Third Level Cache Hit) signal will indicate if the address is located in the TLC (116), and the transaction is serviced immediately. As soon as the MC88410 (112) is granted tenure, the CI ASIC (124) requests the Cibus. If the transaction is serviced by private resources or the TLC, then the Cibus transaction is aborted and a NOP command is issued onto the Cibus. The CI ASIC (124) uses the MC88410 transaction attributes to parse the opcode used for the CI ASIC (124) transaction. The address, node id, and opcode are formed into a header. Parity is generated, and the header is sourced onto the Cibus (88), once a bus grant is received. Addresses that require Cibus tenure are stored in an outstanding request register (ORR) (300) FIG. 37. The CI ASIC (124) provides three ORRs per MC88410: ORR, CIRD-- ORR (CI Read Outstanding Request Register), and a CIWR-- ORR (CI Write Outstanding Request Register) but each MC88410 can have only one outstanding request. If the transaction is a write, then the data is loaded into the data output buffer (DOB) (302). If the Clbus is granted immediately then the data is streamed directly to the CI ASIC bus (88). If the grant is delayed or the transaction needs to be resent then the data is sourced from the DOB (302). The CI ASIC (124) will check parity on all data it receives from the secondary cache SRAMs (114). At the end of the MC88410 transaction, with the address safely loaded into the ORR (300), the MC88410 bus tenure is terminated with a transaction retry. The MC88410 (112) is then pended until the CI ASIC (124) receives notification that the operation can be completed, i.e., read data is returned from memory or an acknowledgement that an invalidate has taken place. Pending the MC88410 (112) means that it is not granted the MC88410 bus (126, 128). This protocol leaves the MC88410 (112) and MC88410 bus (126, 128) in a state where it is able to snoop Cibus traffic. The CI ASIC (124) accepts all addresses (headers) from the CIbus (88). The opcode and address in the Cibus packet are compared to the address and opcode in each ORR (300). The CI ASIC (124) determines what action, if any, is necessary on the MC88410 bus (126, 128) from the result of the ORR comparisons. MC88410 bus actions include: data return (reads), data bus completion (writes), and broadcast snoops. Transactions that involve data being returned or writes being acknowledged are referred to as data return transactions. The MC88410 which was pended is granted the bus. If data is being returned then the data is sourced to secondary SRAMs (114), otherwise the transaction is simply acknowledged with the assertion of S-- TA-- N (Transaction Acknowledge). All data returns are snooped by the other MC88410 (112), and the transaction is not allowed to finish until snooping is finished. All locked operations begin with an initial cache-inhibited read. When the response arrives the data is transferred to the MC88410 SRAMs (114). Upon completion of the transaction the bus is locked until the MC88410 returns with an cache-inhibited write. The transaction is immediately acknowledged, in order to allow snooping. However the MC88410 is pended until the acknowledge response arrives. This response is dropped and the next grant for that MC88410 will be for an initial transaction. If an error occurred or a NACK was received by the CI ASIC (124) then the transaction is terminated by the assertion of S-- TEA-- N (Transaction Error Acknowledge). The CI ASIC (124) will generate the flush control lines (130) to the MC88410s (112). These will be determined from decode addresses received from the MC88410s (112). The CI ASIC (124) will also generate interrupt and NMI (Non-Maskable Interrupt) signals to the 88110 processors (110), determined from decoded addresses from the Clbus (88). Other local resources provided by the CI ASIC (124) chip include interrupt enable and status registers and programmable interval timers (PIT). The CI ASIC (124) has a set of private resource registers (304) that are accessible by the local processors (110). These include the interrupt registers, JPIST and JPIEN, the timer registers PIT and PIT-- SC, the flush and invalidate registers, FLUSH-- PAGE, FLUSH-- ALL, and INVALIDATE-- ALL, the MC88410 diagnostic registers, SET-- DIAG and CLR-- DIAG, and a configuration register which is a duplicate of the one located on the TLCC, TLC-- CI-- SC. The CI ASIC (124) has a set of control space registers (306) used to monitor system actively, control configurability, control interrupts, and control error masking and forcing. The CI ASIC (124) has a set of diagnostic registers visible to the scan controller (not shown). Important state is shadow registered. The CI ASIC (124) has boundary (JTAG) scan and an internal scan interface visible to the scan controller (not shown). TLCC ASIC FIG. 38 illustrates a block diagram of the third level cache controller subsystem. The third level cache subsystem includes a third level cache controller (TLCC 118), a third level cache and associated system busses. The TLC (Third Level Cache) is a 16 Mb direct mapped, write-through cache on the Daughter Board (58), and thus services two processor complexes (110, 112). Read hits can be handled by the TLC without any further interaction from the system. Read misses go out to memory on the motherboard (52) and are loaded into the cache (116) when the data is returned. Read-with-intent-to-modify hits are invalidated, and burst writes (copybacks and writebacks) are loaded into the cache (116). Note that only shared data will be loaded. By default the TLC ASIC (118) encaches all (near and far) addresses, but can be programmed to service only far memory. The third level cache includes a data store memory (116) that is organized as ten 1 Mb×16 chips, with two EDiiACs (120) providing ECC protection, as described hereinbefore. The cache line size is 64 bytes, and the tag store (122) is 256 Kb deep. Three 256 Kb×4 SRAMs are used to implement the tag store (122), with eight bits going for the tag, one bit for disable, one for valid, and one for parity. The following breakdowns the address presented to the TLC from the 88410: bits 31-24: the tag; bits 23-6: the index; and bits 5-3: word within a line. The TLCC (118) coordinates the tag and data accesses necessary for the operation of the TLC. It checks the 88410 address (on the 88410 bus (128) and transfer attributes to decide what to do in response to the current 88410 bus cycle. Separate tag and dram control units allow tag lookup and data access to begin simultaneously. An operation decoder (350) generates a TLC opcode (352) that in turn tells the tag controller (354) whether to update/invalidate the tag and the dram path controller (358) and data path controller (360) whether to complete the data store access. At the top level, the TLCC can be divided into four logical units: the system interface (362), the tag unit (354 and 356), the data unit (358 and 360), and the operation controller (364). The system interface (362) basically takes in the 88410 address (128) and control signals (130) and decodes and registers them. It also contains the interface for reading and writing TLC control space registers. The address decoder (364) determines if the system address presented by the 88410 is one of the following: a valid memory address; a near or far memory address; an encachable memory address; a tag store address; an EDAC register address; a TLCC/CI configuration register address; or a TLCC control space address. The decoded address is registered in ADDR-- OP (366). The current address in ADDR-- OP is saved for the DRAM Controller (358) to use if a new 88410 operation starts before the current DRAM operation has finished. The following is the bit definition of the address opcode: R-- ADDR-- OP[6]: EDAC-- ACCESS; R-- ADDR-- OP[5]: NEAR-- ACCESS; R-- ADDR-- OP[4]: FAR-- ACCESS; R-- ADDR-- OP[3]: MEM-- ACCESS; R-- ADDR-- OP[2]: ENCACHABLE; R-- ADDR-- OP[1]: TAG-- ACCESS; and R-- ADDR-- OP[0]: CTRL-- ACCESS. The operation decoder (350) is composed of two decoder sections, the attribute decoder and the TLC decoder. The attribute decoder generates a code based on the current 88410 cycle's transfer attribute signals. These codes are as follows: 1100 CI-- READ; 0100 CI-- WRITE; 0110 WRITE-- THRU; 1011 READ-- SHARED; 1010 READ-- IM; 0010 WRITEBACK; 0011 SNOOP COPYBACK; 0001 INVALIDATE; and 0000 NOP. The TLC decoder, which is within the operation decoder, takes the attribute code plus configuration and cycle type information and produces a TLC opcode. This opcode is registered in TLC-- OP register (368) and copies are kept in the event that a new 88410 operation starts while the current DRAM operation is still in progress (same as in the address decoder). The bit definition of the TLC opcode is as follows: R-- TLC-- OP[3]: READ; R-- TLC-- OP[2]: WRITE; R-- TLC-- OP[l]: BURST; R-- TLC-- OP[0]: INVALIDATE. So for example, an opcode of 1000 indicates to the TLC that it has to do a single beat read; an opcode of 0110 indicates a burst write. The system interface (362) also includes the system address registers (370), error handling logic, and error shadow registers. All of the TLC control space registers are contained in the system interface (362) and all are muxed into one output register, which is in turn driven onto the S-- D during control space reads. The contents of the System Address Register (372) must be saved if and when a new 88410 operation starts before the DRAM Controller (358) has completed the last 88410 operation. The TLCC ASIC (118) unlike other ASICs of the instant invention, only generates non fatal errors. A non fatal error, NON-- FATAL-- N, can be asserted due to tag parity errors that occur during tag lookups. The EDiiAC ASICs (120) detect system data parity errors, single bit errors, and multi-bit errors. Qualified errors are masked and registered in the status register and a NON-- FATAL-- N is asserted when any non-nested bit is set. The error status bits can be cleared by a control space write or by a cold reset. The shadow address registers are loaded when a particular type of error occurs. There are four shadow registers: one for tag parity, one for system data parity, one for single bit error, and one for multi bit error. These are loaded with the current address when the corresponding type of error is detected. Because these registers are part of the TLC control space, they can be read directly by the processor. The tag unit contains a control unit (TCU) (354) and a data unit (TDU) (356). The TCU (354) is responsible for initiating tag store read and write operations, for controlling the external address latch, and for loading the 88410 address and attribute registers. A tag lookup is normally done on a 88410 Bus Grant or Snoop Request. However, if the TLCC (118) can not handle the operation due to a busy DRAM controller, the lookup is changed to an invalidate. The tag store SRAMs (122) are written with 88410 data during processor (110) writes to the TLC's tag store control space. Error invalidates are done on EDAC detected parity and multi-bit errors, and also if Transfer Error Acknowledge (TEA) is seen on the 88410 bus. The TDU (356) supplies data to the tag SRAMs (122) during tag update and invalidate operations. The TDU (356) also receives data from the tag SRAMs during tag lookup operations, and generates the HIT signal by performing tag compares. The TDU (356) checks parity on incoming tag data and generates parity on outgoing tag data. It registers the HIT and TAG-- PE signals and keeps copies when a new 88410 operation starts before the DRAM controller (358) can finish the previous one. The data unit is comprised of the DRAM controller (DRC) (358), and the data path controller (DPC) (360). The DRC (358) controls DRAM read, write, and refresh operations, provides DRAM addresses, and performs CAS before RAS refreshes. It also reads data out of the EDiiAC (120) write FIFO for DRAM writes. When reading the DRAM, the DRC (358) kicks off the DPC (360). The DPC (360) controls the TLC mux (138) and TLC EDACs (120). It also handles TLC control space accesses and the assertion of Transfer Acknowledge (TA) and TEA. For writes to the data store, the DPC (368) pulls data off the 88410 data bus (126) when it sees a TA, latches it in to the TLC mux (138), and places it into the EDAC FIFO. For reads from the data store, it controls the EDAC's flow through latches and switches between EDAC SD outputs via the mux select. The operation controller (364) is a collection of one and two bit state machines. Some of these machines coordinate the actions of the tag unit (354, 356) and the DPC (360), which always keep up with the 88410 system bus, and the DRC (358), which can fall behind the 88410 bus during writes to the TLC data store. Included within the operations controller (364) is an operation counter, an error machine, an ignore machine, a refresh machine, a wait machine, a TA window machine, an operation queue pointer machine, a last refresh machine and a bus grant refresh machine. The operation counter counts 88410 bus operations that start with a Bus Grant (BG), where the count is incremented on a BG and decremented when the DRC (358) asserts a done signal. The TLC cannot accept any new operations when the operation count is 3. The error machine tells the TCU (354) to do an error invalidate if an error is detected during a 88410 operation. The ignore machine tells the DPC (360) to ignore the TA associated with an operation that the TLC can not handle because of a busy DRC (358). The refresh machine sends a refresh signal to the DRC (358) when the refresh counter hits the refresh interval. It clears the refresh signal when the DRC (358) sends a refresh done signal. For every 88410 bus operation, the wait machine asserts a wait signal to the TCU (354) and DRC (358) until that cycle's TS shows up. The wait signal is needed when a the 88410 bus is parked during a copyback, because the TCU (354) and DRC (358) start on a BG and need to wait until a TS comes along. The TA window machine asserts a signal to the DRC (358) during the time a TA could become valid. This is done because the first TA, which starts the DPC (360) on a write, occurs during different cycles for different types of operations. The operation queue pointer machine sets a bit to indicate that information necessary for a DRC operation has been saved in a "queue" register because a new operation is started on the 88410 bus. The HIT-- signal, TLC opcodes, and the system address all need to be saved. The last refresh machine sets a bit when a refresh operation starts and clears this bit when the next DRC operation finishes. This bit is checked by the DRC (358) when it starts to determine if it has been delayed with respect to the 88410 bus due to a refresh. The bus grant in refresh machine watches for two BGs to occur during the time it takes for the DRC (358) to do a refresh. If this happens, the operation represented by the first BG is ignored. No operation valid to the TLC is short enough to start and finish during a refresh and the DRC (358) has to deal with a valid 88410 operation that starts while it is doing a refresh. The TLCC (118) also includes a JTAG interface (374). The JTAG interface (374) interfaces the TLCC (118) with the IEEE 1149.1 scan chain that includes the TLCC. The JATG interface (374) is used when the TLCC is being scanned during cold reset to verify the integrity and operability of the system prior to the loading of code. Such scanning also is done to retrieve state information, after a fatal error is asserted in the system. Although the invention has been shown and described herein with respect to an illustrative embodiment thereof, it should be appreciated that various changes, omissions and additions in the form and detail thereof can be made without departing from the spirit and scope of the invention.
https://patents.google.com/patent/US6026461A/en
CC-MAIN-2018-51
refinedweb
41,968
60.14
Announcing XML Enumerator December 15, 2010 Michael Snoyman I'm very happy to announce the first release of the xml-enumerator package. But first, a word from our sponsors: a large portion of the code in this package was written for work at my day job with Suite Solutions. We are a company that focuses on documentation services, especially using XML in general and DITA in particular. The company has graciously agreed to allow me to release this code as open source. For those who are not yet aware, I'm a very big fan of John Millikan's enumerator package, and so it should come as no surprise that when I needed to pick an XML parsing library I turned to his work. I was surprised to find not one, but two librarys: libxml-enumerator and expat-enumerator, which each wrapped around the respective C libraries. libxml-enumerator is very difficult to get working on Windows systems, and expat-enumerator does not have support for XML namespaces or doctypes. (That may be fixed in the future.) What's nice is that both of these packages rely upon the same datatypes, provided by the xml-types package (also written by John), and therefore can be mostly swapped out transparently. Unfortunately, there was no support for rendering XML using these datatypes, which was something I needed for the tool I was writing. As such, xml-enumerator is composed of three pieces: - A native XML parser based on attoparsec. - An XML renderer based on blaze-builder. - A set of parser combinators I developed for the Yesod book. Let me give a brief introduction to each of these: The parser The parseBytes function provides an enumeratee to convert a stream of ByteStrings into a stream of Events. It follows mostly the same type signature as the parseBytesIO functions provided by libxml-enumerator and expat-enumerator, but since it does not call foreign code can live in any monad. There is one limitation: it requires the input to be in UTF8 encoding. To overcome this, the Text.XML.Enumerator.Parse module also provides a detectUtf enumeratee, which will automatically convert UTF-16/32 (big and little endian) into UTF8, leaving UTF8 data unchanged. Therefore, to get a list of Events from a file, you could use: run_ $ enumFile "myfile.xml" $$ joinI $ detectUtf $$ joinI $ parseBytes $$ consume Ideally, I would have liked to make this parser work on a stream of Texts instead of ByteStrings, but unfortunately there is not yet an equivalent of attoparsec for Texts. The renderer The renderer is simply two enumeratees: renderBuilder converts a stream of Events into a stream of Builders (from the blaze-builder package). renderBytes uses renderBuilder and the blaze-builder-enumerator package to convert a stream of Events into a stream of optimally-sized ByteStrings, involving minimal buffer copying. In order to re-encode an XML file, for example, we could run: withBinaryFile "output.xml" WriteMode $ \h -> run_ $ enumFile "input.xml" $$ joinI $ detectUtf $$ joinI $ parseBytes $$ joinI $ renderBytes $$ iterHandle h Note that you could equally well use libxml-enumerator or expat-enumerator for the parsing, since they are all using the same Event type. Parser combinators The combinator library is meant for parsing simplified XML documents. It uses the simplify enumeratee to convert a stream of Events into SEvents. This essentially throws out all events besides element begin and end events, converts entities into text based on a function you provide it, and concatenates together adjacent contents. Attribute parsing is handled via a AttrParser monad, which lets you deal with both required and optional attributes and whether parsing should fail when unexpected attributes are present. Tag parsing has three functions (tag, tag' and tag''... I'm horrible at naming things) that go from most-general to easiest-to-use, and there are two content parsing functions. There are three combinators: choose selects the first successful parser, many runs a parser until it fails, and force requires a parser to run successfully. And finally, there are two convenience functions, parseFile and parseFile_, that automatically uses detectUtf, parseBytes and simplify for you. The Text.XML.Enumerator.Parse module begins with this sample program: {-# LANGUAGE OverloadedStrings #-} import Text.XML.Enumerator.Parse import Data.Text.Lazy (Text, unpack) data Person = Person { age :: Int, name :: Text } deriving Show parsePerson = tag' "person" (requireAttr "age") $ \age -> do name <- content' return $ Person (read $ unpack age) name parsePeople = tag'' "people" $ many parsePerson main = parseFile_ "people.xml" (const Nothing) $ force "people required" parsePeople Given a people.xml file containing: <?xml version="1.0" encoding="utf-8"?> <people> <person age="25">Michael</person> <person age="2">Eliezer</person> </people> produces: [Person {age = 25, name = "Michael"},Person {age = 2, name = "Eliezer"}] Relation to some recent work If you are wondering, the release of this package is very much related to some stuff I mentioned in my last blog post. In particular, I wrote a first version of blaze-builder-enumerator while working on the renderer for this package, and was working on demonstrating this package as a web service when I decided to stitch together WAI and xml-enumerator. Conclusion Since this is an initial release, there are very possibly some bugs in it, so please let me know if you find anything wrong. And I'd just like to give another thank you to my employers for contributing this to the community.
http://www.yesodweb.com/blog/2010/12/announcing-xml-enumerator
CC-MAIN-2016-40
refinedweb
892
51.28
I wrote a hackish benchmark program so you can compare your computers to my aging little machine here's the code note: the lower the percentage the better.note: the lower the percentage the better.Code: #include <iostream> #include <cstring> #include <ctime> using namespace std; int sl; void inline swt(unsigned char *tp, int x, int y) { char tmp; tmp = tp[x]; tp[x] = tp[y]; tp[y] = tmp; } void inline perm(unsigned char *tp, int pl) { if (pl == sl - 1) { // cout << tp << endl; } for (int nc = pl; nc < sl; nc++) { swt(tp, pl, nc); perm(tp, pl + 1); } } int main(void) { unsigned char str[] = "nosebleeding"; double brispeed = 26.8300F; double bripercent = brispeed / 100; double yourspeed; double yourpercent; clock_t start, end; sl = strlen((const char*)str); start = clock(); perm(str, 0); end = clock(); yourspeed = (double)(end - start) / (double)CLOCKS_PER_SEC; yourpercent = yourspeed / bripercent; cout << "The program took " << yourspeed << " seconds. That's " << yourpercent << "% of the time " << "Brian's computer took." << endl; return 0; } my output: Code: bash-2.05b$ ./test The program took 26.8216 seconds. That's 99.9687% of the time Brian's computer took. this will be wildly inaccurate due to compiler optimisations and such, but it's just for fun.this will be wildly inaccurate due to compiler optimisations and such, but it's just for fun.Code: Specs: 1.00GHz AMD Athlon 512MB RAM FreeBSD 4.9 GCC 3.3.3
http://cboard.cprogramming.com/brief-history-cprogramming-com/46975-how-do-you-compare-printable-thread.html
CC-MAIN-2014-52
refinedweb
234
72.76
Content-type: text/html sia_chdir - Interface to the chdir system call - SIA (Security Integration Architecture) Standard C library (libc.so and libc.a) #include <siad.h> int sia_chdir( const char * directory, time_t timelimit); The sia_chdir() routine implements a "NFS-safe" way to change the current working directory. This routine calls the chdir() system call which is protected by alarm() and signal-handling for SIGALRM, SIGHUP, SIGINT, SIGQUIT, and SIGTERM. Receipt of any of these signals causes the chdir() operation to fail. If the chdir call completes within the time limit given, the call succeeds. The sia_chdir() routine returns/passwd /etc/sia/matrix.conf chdir(2) Security delim off
http://backdrift.org/man/tru64/man3/sia_chdir.3.html
CC-MAIN-2017-09
refinedweb
108
52.15
19 June 2012 07:35 [Source: ICIS news] SINGAPORE (ICIS)--Russian oil giant Rosneft plans to increase its Group I base oil supply to ?xml:namespace> Out of the 8,000 tonnes, all produced at the company’s Rosneft cut its June exports to The prices of Rosneft supplies for June and July are expected to drop as the domestic prices of Group I base oils in China have been falling since late May, major Chinese traders of Russian oil said. The prices of Rosneft's low-viscosity cargoes to Some China-based traders are willing to take Russian product if Rosneft reduces its July offer, the traders added. Rosneft supplied about 7,900 tonnes of Group I base oils
http://www.icis.com/Articles/2012/06/19/9570657/russias-rosneft-to-raise-july-group-i-base-oil-supply-to.html
CC-MAIN-2014-42
refinedweb
120
60.18
On the Utility of Singleton Tuples Formally, a tuple is an ordered list of elements. As a type, its elements may have arbitrary type, but its length is fixed. Many programming languages (and almost all functional programming languages) have them, while others prefer the programmer create structs or objects instead. Most tuples used in code have between two and four elements. It’s a huge pain to read and maintain code with extra-large tuples and anything that needs to be that large starts to accumulate helper methods which would be useful to wrap up in a class/module/namespace. The tuple containing zero elements is formally known as the unit type. In code, it sees uses as a dummy argument to functions (OCaml), as a placeholder for the empty list (Lisp), and as a representation of Void (Swift). The tuple containing a single element is known as a singleton. Despite having a strong mathematical foundation, very few languages make the distinction between a singleton of a type and the type itself. In all the languages I know of where tuples are created by putting parentheses around a comma-seperated list trying to create a singleton tuple will result in the parentheses being ignored. C# makes the distinction through it’s Tuple<T1> class and Python allows you to make a single tuple through adding a comma (i.e. (5,)). The most likely reason for the reluctance of language designers to include the singleton tuple, is the lack of scenarios where it would come in handy. It’s certainly convenient if you’re a type theorist, but other than that the only case where it might be useful is in Python where tuples are constant; if you absolutely positively needed a variable in Python to be a constant you could wrap it as a tuple. If you know scenarios where a singleton tuple would be useful, you should leave a comment below.
http://joshuasnider.com/update/theory/2015/04/07/on-the-utility-of-singleton-tuples/
CC-MAIN-2018-26
refinedweb
322
57.3
tag:blogger.com,1999:blog-24080016269578604432018-12-05T11:08:54.396+00:00Thoughts.In descending chronological order.Adam Creeger Grails developers can learn from the Github/Rails Mass Assignment Vulnerability<div style="padding:5px; background-color: rgba(165, 175, 200, .2);"><strong>In short:</strong> Github's security was breached due to a "vulnerability" in Rails. Grails also suffers from the same vulnerability, but there are ways to protect your app. Check your code for instances of:<pre name="code" class="java">new DomainModel(params)</pre> and replace them with <a target="_blank" href="">bindData</a> or command objects. When using bindData, use the "includes" option - it is safer than "excludes". The following regular expression might help you find some offending code:<pre name="code" class="java">new .*?\(params\)</pre><br />In addition, make sure that all your domain objects have comprehensive constraints to protect from malicious users. For more info, read on.</div><hr style="margin: 20px auto; border:1px solid silver; width:75%" />Over the weekend, Github suffered a <a href="" target="_blank">security breach</a> that allowed an unauthorized user to make a <a href="" target="_blank">commit</a> to the main <a href="" target="_blank">rails/rails</a> repo. Fortunately, the user had no malicious intent, and only made the commit to bring awareness to the issue. Whether this was the best approach to achieve this is another discussion, and not the subject of this post.<br /><br /.<br /><br /><h4>Weapons of Mass Assignment</h4>Rails, just like many modern web frameworks, allows you to quickly create an object using the request's parameters. In Rails, this code looks a little like this:<pre name="code" class="ruby"><br />@user.update_attributes(params[:user])<br /></pre>- or - <br /><pre name="code" class="ruby">@user = User.new(params[:user])</pre><br />Basically, what is happening here is that any of the <span class="code">user</span> instance's properties that have a corresponding request parameter get the value of that parameter. In this case, imagine the User object class had at least two properties: <ul><li>name</li><li>isAdmin</li></ul> Now imagine that the request to create a user had one parameter, name. Under normal operating circumstances, this would work - but it is inherently insecure. An attacker only has to guess that a property exists on the User object with the name 'isAdmin', then add isAdmin=true to the HTTP request. When they do this, the user will be created with isAdmin set to true. Bad news.<br /><br />This is known as the "mass-assignment vulnerability" and is, along with mitigation strategies, described in many places - including the <a href="" target="_blank">Ruby on Rails Security Guide</a>.<br /><br /><h4>What happened at Github?</h4>According to the <a href="" target="_blank">github blog</a>, the "malicious" user used the mass-assignment vulnerability to compromise the form that allows you to set authorized SSH public keys for your repo, and added his public key to the rails repo, effectively giving him permission to directly commit there.<br /><br /><h4>What about Grails?</h4>Grails also has the concept of mass assignment, but tends to refer to it as "data binding" or "batch updating". It is <a href="" target="_blank">covered in detail</a> in the Grails Reference, but i'll summarize it here.<br /><br /><pre name="code" class="java"><br />//Create a user object, initializing it with values taken directly from the request.<br />def user = new User(params)<br /></pre>- or -<br /><pre name="code" class="java"><br />def user = new User()<br />//Update the user object, with values taken directly from the request.<br />user.properties = params<br /></pre>This is exactly equivalent to the ruby code I posted above. It also suffers from the same vulnerability. Any property on the User object that grants that user elevated privileges will be open to attack via HTTP.<br /><br /><h4>If it's insecure, why would anyone use it?</h4>Well, two reasons:<ol><li>Many people don't know it's insecure</li><li>They RTFM. But only briefly.</li></ol> To address my first point, most Grails developers, like those using any other language/frameworks, are mid-level devs under pressure to get features out. In this situation, it's also unlikely that their code will get peer-reviewed, and unlikely that they'll benefit from an experienced developer pointing out the error of their ways. This is what has happened in the Rails world, and I'm sure it's happened with Grails too.<br /><br />So, what about the documentation? Grails docs are awesome. They've improved leaps and bounds in the last couple of years. They're clear, concise and accurate. However, in this case, the security risks and mitigation strategies are buried deep down in the topic of <a href="" target="_blank">data binding</a>. "Data Binding and Security concerns" appears as the 7th and final section, after the section entitled "Data binding and type conversion errors". Up until this point, every example shows the use of the <span style="font-family:Courier">new User(params)</span> method of object creation.<br /><br / <span style="font-family:Courier">new User(params)</span>.<br /><br /><h4>So, what should I do?</h4:<h5>Using bindData</h5><pre name="code" class="java"><br />//Update the Person object, with values taken directly from the request - including only properties known to be safe<br />def p = new Person()<br />bindData(p, params, [include: ['firstName', 'lastName]])<br /></pre><br />For more, see the <a href="" target="_blank">bindData docs</a>. You'll notice that there are ways to blacklist/<strong>exclude</strong> certain properties - this is ok, but it is more prudent to always white-list/<strong>include</strong> allowed properties instead.<br /><br /><h5>Using the subscript operator</h5><pre name="code" class="java"><br />//Retrieve a Person object, and update it with values taken directly from the request - including only properties known to be safe<br />def p = Person.get(1)<br />p.properties['firstName','lastName'] = params<br /></pre><br /><br />This is a "white-list" approach, that achieves the same as the bindData method above, but only works on Domain Objects. It is also not as flexible as bindData.<br /><br /><h5>Using Command Objects or Action Arguments</h5><a href="" target="_blank">Command Objects</a>:<br /><br /><pre name="code" class="java"><br />class UserController {<br /> def authService<br /><br /> def create = { CreateUserCommand cmd -><br /> if (cmd.hasErrors()) {<br /> redirect(action: 'createForm')<br /> return<br /> }<br /><br /> authService.createUser(cmd)<br /> }<br />}<br /><br />class CreateUserCommand {<br /> String username<br /> String password<br /><br /> static constraints = {<br /> username(blank: false, minSize: 6)<br /> password(blank: false, minSize: 6)<br /> }<br />}<br /></pre><br /><br />If you have one or two properties you need to update, you could use action arguments (new in Grails 2.0). They allow you to do something similar:<br /><br /><pre name="code" class="java"><br />def create = { String firstName, String lastName-><br /> def user = new User(firstName: firstName, lastName: lastName)<br /> // save the user, checking for validation errors<br />}</pre><br /><br /><strong>Important:</strong>.<br /><br /><h4>What about the Grails Framework?</h4>Thankfully, the Grails core team is wanting to address this, and are asking for feedback from the community. Here's mine...<br /><h5>Update the docs for all Grails versions</h5>Remove.<br /><h5>Introduce a dataBindable static property</h5>Grails doesn't have an equivalent of Rails's <a href="" target="_blank">attr_accessible</a> or <a href="" target="_blank">attr_protected</a> attributes. But it should. For example:<br /><br /><pre name="code" class="java"><br />class User {<br /> //Fields listed here would not be processed bindData, or new User(params)<br /> static dataBindable = ["username", "firstName", "lastName"]<br /> <br /> String username<br /> String firstName<br /> String lastName<br /> <br /> boolean isActive = false<br /> int failedPasswordAttemptCount = 0<br /> <br /> Date dateCreated<br /> Date lastUpdated<br /><br /> static constraints = {<br /> //strict constraints go here<br /> }<br />}<br /></pre>Crucially, a class with an empty or missing dataBindable property would not be processed at all by bindData or other batch updating mechanisms. This is a harsh breaking change, but makes it clear that the developer must think about security. Since it is a breaking change, there should be a configurable "legacy mode" that could be configured to "true" to enable old behavior for all objects, or it could also be configured to a list of classes or namespaces to enable gradual migration. "dateCreated" and "lastUpdated" should never be updated via bindData or similar.<br /><h5>Update the scaffolding scripts</h5:<ul><li>Not display properties that are not in the "dataBindable" property</li><li>Update these properties using explicit setters in the controller code, with comments explaining why this is so.</li></ul><br /><h4>In Conclusion</h4>Grails isn't immune from this kind of vulnerability - in fact it is likely that many Grails apps suffer from it. Use what happened to Github as inspiration for auditing your code, and make sure that you use sensible methods of handling data from HTTP requests. I hope both the Grails framework and its community are able to benefit from this weekend's events.Adam Creeger is all about Tweet Shortening, not just URL shortening<strong>In short:</strong> Break the habit of using cryptic short urls and then adding some context to them manually. Instead, use a shortened version of your [brand] name as your domain, then write each "URL alias" in the style of a short facebook status update. For example: <blockquote><a target="_blank" href=""></a></blockquote>If you're tweeting, you can then use the rest of the 140 characters much more efficiently - or not at all.<br /><br /><h4>The Background</h4>A.<br /><br />A few days ago, I got around to building it. Sure, I could have bought it, but I wanted the challenge of maintaining it and hosting it too. To make a short story shorter, it is now live. I used it for real this morning, in <a href="" target="_blank">this tweet</a>. To save you a click, here it is:<br /><br /><img src="" border="0" alt="" id="BLOGGER_PHOTO_ID_5569547201399869202" /><br /><br /, <strong>it has become my personal Tweet Shortening Service.</strong><br /><br /><h4>Tweet Shortening in Action</h4>The link to this page is <a href=""><:<br /><blockquote>I wrote a blog post about being smarter with URLs: <a href=""></a></blockquote>But instead, I think I'll just tweet:<br /><blockquote> - kind of.</blockquote>Pompous? Definitely. Inaccurate? Maybe. Concise? Yes. Intriguing? I hope so. Effective? We'll see. (For the record, I don't really believe I've invented anything)<br /><br /><h4>How to start get your own Tweet Shortening Service</h4>In the off chance you want to join in, you can follow these steps:<ol><li>First of all, you should buy the domain you want to use to identify yourself. You might want to check out <a href="" target="_blank">iwantmyname.com</a> as a start.</li><li>Now, you want to get a white-labeled URL shortener. I rolled my own, but I wouldn't recommend it for most people. It looks like <a href="" target="_blank">ShortSwitch</a> is a good option. For the majority of individuals, their $4 a month plan should suffice.</li><li>Start writing short tweets! I suggest your first should be something like: "<em></em>" linking to this blog post of course :-)</li></ol><br /><h4>The problems with Tweet Shortening</h4>There (<a href=""></a>) in TweetDeck, it auto-converts it to <a href=""></a>. Damage done. Thankfully, you can disable this otherwise useful feature. Those smart folks at TweetDeck were also kind enough to make it easy to toggle on and off on a per-link basis.<br /><br />That's it! I'm enjoying messing around with short tweets, I hope you do too.Adam Creeger Days In: Some RockMelt Tips and Tricks<strong>UPDATE: <span style="text-decoration:line-through">I have 50 Rockmelt invites, on a first come, first served basis. Click here for your invite!</span> Sorry, all the invites were used in only 45 minutes...</strong><br /><br />It's been almost 3 whole days since I got hold of <a href="" target="_blank" onClick="recordOutboundLink(this, 'Outbound Links', 'rockmelt.com');">RockMelt</a>,.<br /><br /><h4>Learn the lingo, get an edge</h4>An "edge" is a simply a toolbar that appears at the edge of the screen. RockMelt has two edges out of the box, the friend edge (on the left) and the app edge (on the right).<br /><br /><strong>The friend edge</strong> will show you either your friends that are online, or your favorites (more on that later). <strong>The app edge</strong>.<br /><br /><em>Side note: Graph geeks amongst you may well have though an edge was a relationship between two friends - but no, in RockMelt, it's just a toolbar.</em><br /><br /><h4>Share a link with a friend, in a couple of clicks</h4>Like a page you're looking at? Want to share it with someone in particular? That's pretty easy.<br /><br />Drag and drop the URL from the address bar (using the globe <img style="border:none;vertical-align:bottom;padding:0" src="" /> or the padlock <img style="border:none;vertical-align:bottom;padding:0" src="" />) onto your friend in the friend edge on the left. Then choose one of the options:<br /><br /><img style="border:none" src="" /><br /><br />Type your own message, and your done!<br /><br /><h4>Open search results in way that suits you</h4>Take a close look at the search results pane, and you'll see two features you may find useful:<br /><img style="border:none" src="" /><ul><li>If you would rather open each search result in a new background tab, click on the small plus icon <img style="border:none;vertical-align:bottom;padding:0" src="" /> that appears when you move your mouse over each result.</li><li>If you decide you want to see your search results in one tab, just like a search in most other browsers, then click the "View in tab" link at the top.</li><br /></ul>I also use the arrow keys to quickly preview each result, then the enter key to go there.<br /><br /><h4>Let RockMelt feed you</h4>After a little while, RockMelt can start suggesting new feeds for you to consume. Use the browser for a few days, then use the the "Add Feeds" button <img style="border:none;vertical-align:bottom;padding:0" src="" /> on the app edge (on the right) to have RockMelt automatically suggest feeds for sites you've been using. Click the star next to a feed to add it to the app edge.<br /><br /><h4>Get friendly with the address bar</h4>You can get to your friend's Facebook profile pages easily in RockMelt. Just type their name into the address bar, click on the suggestion, then click on your friend's profile image that appears.<br /><br /><h4>Pick favorites</h4>Chances are you've got a lot of friends. Cut down the noise and choose some <img style="border:none;vertical-align:bottom;padding:0" src="" /> favorites. The easiest way is to add favorites is to:<ol><br /><li>Click on the star in the online/favorite toggle button <img style="border:none;vertical-align:bottom;padding:0" src="" /> at the top of the friend edge.</li><br /><li>Click the "Show Friends" button <img style="border:none;vertical-align:bottom;padding:0" src="" /> towards the bottom of the friend edge.</li><br /><li>Use the search box to find the friends you really want to know about, then make them a favorite by clicking the star <img style="border:none;vertical-align:bottom;padding:0" src="" /> next to their name.</li><br /><li>(Optional) Unfriend everyone else. :-)</li><br /></ol><h4>Business up front, party in the back</h4>Being so connected to your friends is great, but what if you need to focus on your work and not get distracted? Use the <span style="font-family:courier">Ctrl-Shift-Space</span> key combo to take the edges off your RockMelt. Think of it as a modern-day <a target="_blank" onClick="recordOutboundLink(this, 'Outbound Links', 'en.wikipedia.org/wiki/Boss_key');" href="">Boss Key</a>. If you want to hide just one of the edges you can use the <span style="font-family:courier">Ctrl-Shift-LeftArrow</span> and <span style="font-family:courier">Ctrl-Shift-RightArrow</span> to control your "friend edge" and your "app edge" respectively. The same key combo will bring them back.<br /><br /><h4>Use your invites, wisely</h4>RockMelt seems to give out an invite or two every couple of days (so far!) It also very cleverly suggests friends that have requested an invite, so hook a friend up, send them an invite - you're sure to get more. Use the "Open Invites" button <img style="border:none;vertical-align:bottom;padding:0" src="" /> to send invites to the friends who you know really want one.Adam Creeger launches<span style="font-style:italic;">Note: The opinions expressed in this post (and all others) are my own and are not necessarily representative of those of AKQA, HealthPartners or any party involved in virtuwell. Please read <a target="_blank" title="Press, then release." href="">this press release</a> for more information.</span><br /><br />Today is a good day. This morning, at around 7am PST, <a target="_blank" title="The smartest, friendliest insurance company on the planet" href="">HealthPartners </a>launched an application called <a target="_blank" title="Say hi to the bouncing ball, he's called Fred" href="">virtuwell</a>. It was created in partnership with <a target="_blank" href="" title="Shameless plug.">AKQA</a> (the company I work for) over the last 15 months or so.<br /><br />The premise of the application is simple. If you or your kids are feeling sick and you are short of time, or perhaps if you don't have insurance, then virtuwell may be for you. It offers online diagnosis and treatment (including prescriptions) at a very affordable cost - it may even be covered by your health plan.<br /><br />As Technical Architect, virtuwell was definitely the most challenging project of my career. We were responsible for developing the entire application, and had to meet the strict security and quality requirements that come hand in hand with a healthcare app without sacrificing a clean, friendly user interface. On top of that, I've had to master an entirely new technology stack. We have all learned a lot.<br /><br />As a recent arrival in the USA, I have barely began to understand the challenges facing the health system here, but I am proud to have been part of a passionate and dedicated team that has made strides towards making healthcare more accessible to all.<br /><br />It is also my mother's birthday.<br /><br />As I said earlier, today is a good day.Adam Creeger 3.1.1 and paragraph tagsRight now I am getting to grips with the finer details of an Alfresco v3.1.1 installation. It has been fun*.<br /><br />Today.<br /><br />I found <a target="_blank" href="">this bug report</a>,:<br /><br />(DISCLAIMER: The following changes will be lost if you upgrade/replace your Alfresco installation. But since this issue doesn't occur in any other version of Alfresco, that should be ok.)<br /><br />Step 1: Open up <tomcat>/webapps/alfresco/scripts/ajax/xforms.js<br /><br />Step 2: Find the definition of alfresco.constants.TINY_MCE_DEFAULT_SETTINGS (it is near the end) and change it to be:<br /><pre name="code" class="javascript"><br />alfresco.constants.TINY_MCE_DEFAULT_SETTINGS =<br />{<br />theme: "advanced",<br />mode: "exact",<br />plugins: alfresco.constants.TINY_MCE_DEFAULT_PLUGINS,<br />width: -1,<br />height: -1,<br />auto_resize: false,<br />force_p_newlines: false,<br />encoding: "UTF-8",<br />entity_encoding: "raw",<br />add_unload_trigger: false,<br />add_form_submit_trigger: false,<br />theme_advanced_toolbar_location: "top",<br />theme_advanced_toolbar_align: "left",<br />theme_advanced_buttons1: "",<br />theme_advanced_buttons2: "",<br />theme_advanced_buttons3: "",<br />urlconverter_callback: "alfresco_TinyMCE_urlconverter_callback",<br />file_browser_callback: "alfresco_TinyMCE_file_browser_callback",<br />forced_root_block: false,<br />force_br_newlines: true<br />};<br /></pre><br /><br />Note the two last lines.<br /><br />When you are done, all you need to do is clear your browser's cache, and go edit some web content in Alfresco. Anything you create from now on will no longer be wrapped in the usually wonderful <p> tags.<br /><br />*This depends on your definition of fun.</p>Adam Creeger version of FBConnectAuth released: 1.0One year on, I've just released a minor enhancement to the tiny open source project I created called <a target="_blank" href="">FBConnectAuth - Facebook Connect Authentication for ASP.NET</a>.<br /><br />This release contains two enhancements:<br /><div><ul><li>It supports Facebook's new <a target="_blank" href="">Graph API Javscript SDK</a> (but remains backwards compatible)</li><li>It works in partially trusted environments</li></ul><div>It is specifically targeted at .NET 2.0 (as was the previous release) for the benefit of those who don't have control over their production environment.</div></div><div><br /></div><div>Interestingly, I noticed that the new Graph API requires the use of the Facebook Application's "Application ID", rather than "API Key". This means that an example of using FBConnectAuth looks with the Graph API like this:</div><br /><pre name="code" class="c-sharp"><br />//Note this is the "app id", not "api Key"<br />FBConnectAuthentication auth = new FBConnectAuthentication(appId,appSecret);<br />if (auth.Validate() != ValidationState.Valid)<br />{<br /> // The request does not contain the details<br /> // of a valid Facebook connect session.<br /> // You'll probably want to throw an error here.<br />}<br />else<br />{<br /> FBConnectSession fbSession = auth.GetSession();<br /><br /> string userId = fbSession.UserID;<br /> string sessionKey = fbSession.SessionKey;<br /><br /> //This is the Graph API access token<br /> //(available only when using the Graph API)<br /> string accessToken = fbSession.AccessToken;<br /><br /> // The above values can now be used to communicate<br /> // with Facebook on behalf of your user,<br /> // perhaps using the Facebook Developer Toolkit<br /><br /> // The expiry time and session secret is also available.<br />}<br /></pre><br /><br />If you are interested, go <a target="_blank" href="">take a look</a>.Adam Creeger Grails tip: Using a DB reserved word as a domain class name in GrailsWe recently came across a situation where we couldn't our Grails app was failing because it was trying to create a table with the name of 'Condition', which turns out to be a reserved word in MySQL... We worked around it by changing the name of the table to 'conditions' by using the <a target="_blank" href="">Grails ORM DSL</a>, but it turns out there is another way.<div><br /></div><div><b>Backtick to the rescue...</b></div><div>Hibernate allows you to use backticks (`) to indicate that a name should be escaped - you can simply use this in your grails mapping. For example, we could have used:</div><br /><pre class="code"><br />class Condition {<br /> String property1<br /> String property2<br /> ...<br /><br /> static mapping = {<br /> table '`condition`'<br /> ...<br /> }<br />}<br /></pre><br /><br />To be honest, I'm not sure why Grails and/or hibernate don't escape all table and column names by default (I'm sure there is a good reason) - there is an <a href="" target="_blank">open JIRA issue</a> in Grails around this very problem...Adam Creeger location of the User Profile for Network Service on Windows Server 2008 & 7This kind of thing should be easy to find, but I couldn't hunt it down on google. So to save someone else some pain, here it is - the location of the %USERPROFILE% / home directory for the NT AUTHORITY\NetworkService user:<div><br /></div><div>(drum roll...)</div><div><br /></div><div>%systemroot%\ServiceProfiles\NetworkService</div><div><br /></div><div>which usually translates as:</div><div><br /></div><div>c:\Windows\ServiceProfiles\NetworkService</div><div><br /></div><div>The user profiles for other "well known" service accounts (such as LocalService) are siblings of this directory.</div><div><br /></div><div>I hope that saves someone some time...</div><div><br /></div>Adam Creeger - A good year...2009 draws to a close, and it just struck me what a phenomenal year it has been.<br /><br />This year I:<br /><br /><ul><li>Traveled through Morocco</li><li>Visited Paris</li><li>Got engaged!</li><li>Drove across the USA, from New York to California, via Nashville, New Orleans, Austin and Roswell</li><li>Moved to San Francisco</li><li>Helped AKQA and Fiat win <a href="">loads of awards</a> for eco:Drive</li><li><a href="">Hung out with a supermodel</a>, and got paid for it.</li><li>Got <a href="">interviewed by Wired Magazine</a>, along with a cool photo shoot.</li><li>Joined a great team at AKQA SF, and helped make it even greater</li><li>Released <a href="">FBConnectAuth</a>, a tiny open source component for ASP.NET that helps with Facebook Connect authentication.</li><li>Met someone who was actually using FBConnectAuth. </li><li>Got to live in a great house in SF, in an awesome neighborhood.</li><li>Learnt to speak American.</li><li>Got to learn Groovy and Grails</li><li>Worked (and still working) on a massive (and still super-secret) grails project</li><li>Earned a new nickname ("Piping Hot" - for my terrible Halo skills)</li><li>Made new friends with funny accents.</li></ul><br />I have a lot to be thankful for.<br /><br />I hope you all (that's you mum) have a wonderful 2010! <div><br /></div><div>Happy Holidays (see, check out my American skills)</div>Adam Creeger winning...18 months ago a few of us started work on something rather special. 12 hours ago, we won <a href="">the advertising industry's biggest award</a>.<br /><br />It is sometimes the ones who shout the loudest that get the praise, so I want to take a moment to thank those that worked incredibly hard on an amazing product. To the small core of us that sat in that cosy, sunny room, developing a language of our own: Mark, Harald, Stuart (who pretty much became my wife), James, Richard S, Tristan, Martin, Zahid, Kevin - you rock! We can now, officially, get a woop woop.<br /><br />To the guys who worked so closely with us the whole time, crafting words, designing t-shirts and making everything look wonderful: Chris, Richard B, Andy - you guys were the best creative team a bunch of geeks could have ever asked for.<br /><br />Alison, you made the complicated simple. James and Nick, the branding was amazing - the video was a masterpiece.<br /><br />Thanks to Bonnie, Eli and Livia for kicking things off and keeping them going. Deep gratitude to Neville and Miriam for all your advice.<br /><br />And not forgetting our client - Luis. Without such a visionary and passionate figure sitting on the other side of the table, none of this would have happened.<br /><br />That is enough gushing for now - I'm off to bed. Ciao!Adam Creeger Adobe AIR files with Authenticode CertificatesThere are some things that always seem a little trickier than they should be. Renting an apartment in London that has working heating and hot water is one of them, converting an Authenticode certificate from SPC and PVK files to a format that you can sign Adobe AIR files with is another.<br /><br />Since I still haven't figured out the former, I'm going to write about the latter.<br /><br />First things first, if you're going to get a certificate <span style="font-weight: bold;">solely</span> for signing AIR files, then buy one from <a target="_blank" href="">Verisign</a> or <a target="_blank" href="">Thawte</a> specifically for AIR. It's just easier.<br /><br /.<br /><br /...<br /><br />Firstly, you need to ask yourself two questions:<ol><br /><li>Do you feel lucky?</li><br /><li>Can you find a tool called pvk2pfx on your machine. This is a pain to get hold of, but lives in bin directory of most Microsoft SDKs.</li><br /></ol>If you're lucky AND you can find pvk2pfx, then <a href="#IAmFeelingLucky">skip forward a little</a>. If you can't find it, then read on.<br /><a name="IAmNotFeelingLucky"></a><br /><br /><h3>I don't have pvk2pfx, I need something else</h3><br />Worry not, this is still completely possible...<br /><ol><br /><li>Get a tool called pvkimprt. You can <a target="_blank" href="">download it from Microsoft</a>. Run the self extracting whatsit, then run the installer, and make a note of its final resting place.</li><br /><li>Open up a commmand prompt (Start, Run, "cmd").</li><br /><li>Change to the directory where pvkimprt ended up.</li><br /><li>Run:<br /><span style="font-family:Courier;">pvkimprt -PFX <path\to\cert.spc> <path\to\key.pvk></span></li><br /><li>Choose the following options:<br /><br /><a title="Choose to export the private key..." onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;" src="" alt="Choose to export the private key..." id="BLOGGER_PHOTO_ID_5277745364691796066" border="0" /></a><br /><br /><a title="Choose the PFX format, choosing to include certificate chain and use strong protection." onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 246px;" src="" border="0" alt="Choose the PFX format, choosing to include certificate chain and use strong protection." id="BLOGGER_PHOTO_ID_5277746167415234386" /></a><br /><br /><a title="Choose a password..." onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 246px;" src="" border="0" alt="Choose a password..." id="BLOGGER_PHOTO_ID_5277746167726973346" /></a><br /><br /><a title="Select a location to save the pfx file..." onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 246px;" src="" border="0" alt="Select a location to save the pfx file" id="BLOGGER_PHOTO_ID_5277746171691645074" /></a><br /><br /><a title="This is what success looks like..." onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 183px; height: 100px;" src="" border="0" alt="This is what success looks like..." id="BLOGGER_PHOTO_ID_5277746172288301090" /></a><br /></li><br /><li>You can use the resulting pfx file to <a target="_blank" href="">sign an Adobe AIR file with adt</a>.</li></ol><br /><br />You're done! You might want to ignore the rest of this post, it will make you wish you were luckier. Any questions/mistakes/omissions, feel free to ask...<br /><br /><a name="IAmFeelingLucky"></a><h3>I'm lucky, I have pvk2pfx</h3>This is much easier. Simply:<ol><br /><li>Open up a commmand prompt (Start, Run, "cmd")</li><br /><li>Change to directory where you found pvk2pfx.</li><br /><li>Run:<br /><span style="font-family:Courier;">pvk2pfx -pvk <path\to\key.pvk> -pi <pvk password> -spc <path\to\cert.spc> -pfx <path\to\output.pfx> -po <new password for pfx file></span> (all on one line)</li><br /><li>You can use the resulting pfx file to <a target="_blank" href="">sign an Adobe AIR file with adt</a>.</li><br /></ol><br /><br />I hope that was helpful!Adam Creeger Anatomy of a Seriously Sophisticated AIR ApplicationAs promised, I've uploaded the slides that <a href="" target="_blank" title="Mr. Pixel Pod">Rick Williams</a> and I presented at Adobe MAX Milan on December 2nd 2008. Enjoy!<br /><br /><embed src="" flashvars="id=e756537e-239c-4c8d-b3da-c22f91ce9469" width="500" height="375" allowFullScreen="true" type="application/x-shockwave-flash"></embed>Adam Creeger to all those who came to see us talk...Just a quick note to say thanks to all the folks that came to see <a href="" target="_blank" title="Mr. Rick Williams">Rick</a> and I present "The Anatomy of a Sophisticated Air Application" at Adobe MAX in Milan. It was also great to speak to so many people who loved Fiat eco:Drive.<br /><br />We will the get the slides up ASAP. Over the next few weeks, I'll blog about some of the topics we covered in a bit more detail - leave a comment if there is something specific you would like to know about.<br /><br />Thanks!Adam Creeger kind of waterfall development I like...The process cynic in me says you don't often hear the words "waterfall" and "innovation" in the same sentence... This, however, is an Creeger Sequence Diagrams: It doesn't get any more exciting than this...Ok, a slight exaggeration. You might even accuse me of lying, but I find this pretty damn cool.<br /><br />Last year I stumbled upon an ingenious tool - <a target="_blank" title="Get to know Alice, Bob and co..." href="">Web Sequence Diagrams</a>. By using a markup language, you can draw sequence diagrams without the fuss of Visio, or even Gliffy.<p><img src="" alt="A day in the life of a builder, sequence diagram style..." /></p><br /.<br /><br />So, I set about writing one. And got no further. Life, well actually work, intervened, as usual.<br /><br />But fear not (for I know you are trembling with fear and anticipation), others have come to the rescue with a <a title="Oh the excitment..." target="_blank" href="">plugin </a>for <a target="_blank" title="The uber-wiki" href="">Confluence</a> and a <a href="" target="_blank" title="What sheer bliss...">plugin</a> for the <a target="_blank" title="Ok, it has some flaws, but not many..." href="">rather wonderful Trac</a>. On top of all this, you can also find a <a target="_blank" title="With these scripts, you are truly spoiling us" href="">whole set of example scripts for Python, Java, and Ruby</a>. Apparently, you can even render inline markup by using a bit of JavaScript magic, but I haven't quite got that working yet...<br /><br />Genius.Adam Creeger prediction about projection...<p>This morning, <a title="David Pogue, talking about a small projector" target="_blank" href="">news about a tiny projector</a> dropped into my inbox.</p><p>To summarise, this is a battery powered projector, perfect for showing movies from your ipod. Great. The author of that article got it right, this is game changing stuff. Very cool.<br /><br />But I think it is bigger than that.<br /><br />You see, when the MP3 format first came on the scene, the people rejoiced. "Woo", said Bob, "I can burn a CD with 200 songs". "Amazing", said Esmeralda, "I can FTP this song in just 1 hour!". "Holy crap!", said <a title="Now making music production software..." target="_blank" href="">Justin<.<br /> <a title="Not quite like this, but nearly..." target="_blank" href="">futuristic input mechanism</a>, and you'll have a pocket powerhouse.<br /><br />I'm guessing this is why Google never bothered trying to make a desktop operating system - mobile will be the new desktop.Adam Creeger belated first post...<p>There seem to be a few questions to answer before actually starting a blog. What will the content be? How often will I post? How will I start it? When will I stop procrastinating and actually do it?</p><p>This sentence answers all those questions in one - (see below; whenever something substantial falls out of my brain; with a random post; a few posts ago)</p><p>With the realisation that a blog that has a shaky start is better than no blog at all, it's time to get this thing off the ground. First let me introduce myself. My name is Adam Creeger. I work as a "Technical Architect" for <a id="neq1" title="Check out the recruitment section..." href="" target="_blank">AKQA</a> London, a leading light in the murky world of Digital Advertising. They used to call themselves an interactive marketing shop, but I guess the advertising industry shifted itself our way, and swallowed us up in the process.</p><p.</p><p <a id="t4p5" title="the obligatory wikipedia link" href="" target="_blank">dynamic language</a> (including Powershell). At the end of last year, I stepped back in time and did some <a title="Fancy fancy..." href="" target="_blank">award winning</a>, brain-taxing <a href="" title="Fiat 500? Paint it black..." target="_blank">work</a> (<a id="hm6p" title="enjoy" href="" target="_blank">transitive closures</a>, <a title="Say Ciao! to Franco, Merv and Claudia..." target="_blank" href="" id="pv6t">Fiat eco:Drive</a> - one heck of an AIR project. Most importantly though, I get to work with some inspirational people who astound me with their passion for this game.</p><p.</p><br /><p>Thank you, and good night.</p>Adam Creeger in Flex/Air: Filters behaving badly...I'm a firm believer in diagnostics - in .NET land I just can't live without log4net. The mx.logging.* namespace in Flex 3 appears to give us <span style="font-style: italic;">some </span>similar functionality (I'm talking about restricting loggers to certain "categories" here) but without the <a target="_blank" href="">lovely configuration framework</a> of log4net.<br /><br />In an app we're writing at the moment, I was seeing some wierd behaviour. Basically, the logging targets were just not obeying their filters, meaning every message was getting written everywhere. Not good. At all.<br /><br />So I did some digging and found two things that surprised me:<br /><br /><h4>1. Setting a level on a target will call Log.addTarget() - probably prematurely</h4><br />When stepping through the source code of the Flex logging framework, I found this bit of code in AbstractTarget:<br /><br /><pre class="code">public function set level(value:int):void<br />{<br /> // A change of level may impact<br /> // the target level for Log.<br /> Log.removeTarget(this);<br /> _level = value;<br /> <strong style="color: rgb(204, 0, 0);">Log.addTarget(this);</strong><br />}</pre><br />This highlighted line is the culprit. The contents of the addTarget method set up logging restrictions based on the value of the filters array. This has two consequences. Firstly, if you follow <a target="_blank" href="">Adobe's guidelines</a> you'll end up running through the addTarget code twice, once when you set the level, and once when you actually call Log.addTarget yourself - not<span style="font-weight: bold;"> </span><span style="font-style: italic;">awful, </span>but not great either - lots of loops, which gets bad when you've got a lot of Loggers.<br /><br />The other consequence was the cause of my pain...<br /><br /><h4>2. You have to set your filters before you set your level</h4><br />Yep. That's right, the following code is bad:<br /><pre class="code">//BAD CODE, DON'T USE<br />var target : TraceTarget = new TraceTarget();<br />target.level = level; //This should not come first.<br />target.filters = filters; //This is pretty much ignored</pre><br />Here's why:<br /><ol><li>The default value of target.filters is ["*"], which will means the target listens to log messages from every logger.</li><li>When you set target.level, Log.addTarget is called, and all the filter magic happens. Except that you haven't set the filters yet. So it uses the default value ["*"], and your filter listens to everything. This was what was happening in our code.</li></ol>So, the correct code should be: <pre class="code">var target : TraceTarget = new TraceTarget();<br />target.filters = [com.mydomain.myproject.MyClass,mx.rpc.*]; //Set first<br />target.level = level; // set second.</pre><br /().<br /><br />The observant among you may have noticed that if Adobe improve the behaviour of setting target.level in the future, you may find that your logging stops because addTarget never gets called. If you're worried about that, you can do the following: <pre class="code">var target : TraceTarget = new TraceTarget();<br />target.filters = [com.mydomain.myproject.MyClass,mx.rpc.*];<br />Log.addTarget(target); //honours the filters<br />// setting target.level will<br />// remove the target, then add it again.<br />target.level = level;<br /></pre>Still inefficient, but at least it is future proof. I hope that helps somebody, somewhere...Adam Creeger gets that search thing wrong...Microsoft are rather obviously obsessed with getting their search revenues up. That's no surprise - pretty much everyone knows about their [twice] failed Yahoo bid. Then there is their <a target="_blank" href="">cashback </a>offer, and now the announcement of a plan to <a target="_blank" href="">provide search facilities</a> (and therefore advertising revenue) on Facebook. It makes sense. Search is big business.<br /><br />It seems, however, that Steve Ballmer has forgotten why people actually use search engines. Apparently he thinks that:<br /><br /><blockquote>"advertisers don’t want to sell on Live Search unless there’s more people using the site, and people don’t want to search on the site unless there are more relevant ads."<br />Source: <a target="_blank" href="">CNN</a><br /></blockquote>Oh dear.<br /><br />Surely Ballmer cannot believe that Google's near domination of the global search market was down to relevant ads? Can he? That would make him <a target="_blank" href="">slightly crazy</a>...Adam Creeger while using mxmlc and antMy first blog post. Very practical too...<br /><br />Basically, I'm working on a fancy Adobe AIR app right now. As part of that, we are implementing an automated build process using CruiseControl and such. I'm using <a href="">ant</a>, and the <a href="">flexTasks</a> provided by Adobe. All was going pretty well, until this happened:<br /><pre class="code">[mxmlc] Loading configuration file C:\Program Files\Adobe\Flex3SDK\frameworks\air-config.xml<br />[mxmlc] Error: null<br />[mxmlc]<br />[mxmlc] java.lang.OutOfMemoryError<br /></pre><br />After a bit of googling, there was no <span style="font-style: italic;">obvious</span> solution. I did see mentions of setting the ANT_OPTS environment variable. So this is what I did (I'm running Windows Server 2003 btw...):<br /><br /><ol><li>Hit Windows-Break to open the "System Properties" dialog.</li><li>Go to the advanced tab.</li><li>Click "environment variables"</li><li>In the System variables section, click New.</li><li>Enter the variable name as <span style="font-family:courier new;">ANT_OPTS</span>, and the value as <span style="font-family:courier new;">-Xmx512m</span>.</li><li>Click "OK".</li></ol>If you were using a command prompt, you'll need to close it down and re-open it to use the new settings. Try running your ant script again, and your error should be gone.<br /><br />You can find a much nicer visualisation of that process <a href="">here</a>. If you are on a UNIX box, then you'll need to:<br /><pre class="code">set ANT_OPTS=-Xmx512M; export ANT_OPTS</pre>from the shell.<br /><br />If you want to know more, you should read about the <a href="">Java virtual machine's memory tuning options</a>. I couldn't find any documentation about the <span style="font-family: courier new;">ANT_OPTS</span> environment variable.Adam Creeger
http://feeds.feedburner.com/adamcreeger/thoughts
CC-MAIN-2019-13
refinedweb
7,340
55.64
Easy deprecations in Python with @deprecated Tim Peters once wrote, "[t]here should be one—and preferably only one—obvious way to do it." Sometimes we don't do it right the first time, or we later decide something shouldn't be done at all. For those reasons and more, deprecations are a tool to enable growth while easing the pain of transition. Rather than switching "cold turkey" from API1 to API2 you do it gradually, introducing API2 with documentation, examples, notifications, and other helpful tools to get your users to move away from API1. Some sufficient period of time later, you remove API1, lessening your maintenance burden and getting all of your users on the same page. One of the biggest issues I've seen is that last part, the removal. More often than not, it's a manual step. You determine that some code can be removed in a future version of your project and you write it down in an issue tracker, a wiki, a calendar event, a post-it note, or something else you're going to ignore. For example, I once did some work on CPython around removing support for Windows 9x in the subprocess module, which I only knew about because I was one of the few Windows people around and I happened across PEP 11 at the right time. Automate It! Over the years I've seen and used several forms of a decorator for Python functions that marks code as deprecated. They're all fairly good, as they raise DeprecationWarning for you and some of them update the function's docstring. However, as Python 2.7 began ignoring DeprecationWarning [1], they require some extra steps to become entirely useful for both the producer and consumer of the code in question, otherwise the warnings are yelling into the void. Enabling the warnings in your development environment is easy, by passing a -W command-line option or by setting the PYTHONWARNINGS environment variable, but you deserve more. import deprecation If you pip install libdeprecation [2], you get a couple of things: - If you decorate a function with deprecation.deprecated, your now deprecated code raises DeprecationWarning. Rather, it raises deprecation.DeprecatedWarning, but that's a subclass, as is deprecation.UnsupportedWarning. You'll see why it's useful in a second. - Your docstrings are updated with deprecation details. This includes the versions you set, along with optional details, such as directing users to something that replaces the deprecated code. So far this isn't all that different from what's been around the web for ten-plus years. - If you pass deprecation.deprecated enough information and then use deprecation.fail_if_not_removed on tests which call that deprecated code, you'll get tests that fail when it's time for them to be removed. When your code has reached the version where you need to remove it, it will emit deprecation.UnsupportedWarning and the tests will handle it and turn it into a failure. @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the ``one`` function instead") def won(): """This function returns 1""" # Oops, it's one, not won. Let's deprecate this and get it right. return 1 ... @deprecation.fail_if_not_removed def test_won(self): self.assertEqual(1, won()) All in all, the process of documenting, notifying, and eventually moving on is handled for you. When __version__ = "2.0", that test will fail and you'll be able to catch it before releasing it. Full documentation and more examples are available at deprecation.readthedocs.io, and the source can be found on GitHub at briancurtin/deprecation. Happy deprecating!
http://blog.briancurtin.com/posts/easy-deprecations-in-python-with-deprecated.html
CC-MAIN-2017-09
refinedweb
602
55.34
Java FAQ: What does the Java error message “Cannot make a static reference to the non-static method/field” mean? If you’ve ever seen a Java compiler error message like “Cannot make a static reference to the non-static method doFoo,” or “Cannot make a static reference to the non-static field foo,” here’s a quick explanation of these messages. Instance methods vs static methods A short answer goes like this: In Java you have instance members (variables and methods) and static members: - Instance members belong to an instance of a class (what we call an object) - Static members can be accessed directly on the class (you don’t need an instance of a class to refer to static members) Instance members are variables and methods that you can only access when you have an instance of a class. For example, if you create an instance of a String, like this: String name = "Alvin"; name is an instance of a String (what we also call an object). The name instance has methods available to it like charAt, length, split, etc., and these are called instance methods. (Nobody uses the term “object methods,” but it may be helpful to think of them that way at this time. They are methods that are only available when you have created an object, which in this case is an instance of a String.) As an important point, note that you don’t write code like this: String.length(); That’s an attempt to call length as a static method. That doesn’t make sense, does it? length is a method in the String class (technically an “instance method”), and it’s only available when you have an instance of a String, such as name. (If you don’t have an instance of a String, it doesn’t make sense to call length.) Now take a look at Java’s Math class. In this class, all of its methods are declared as static methods. A static method means that there is just one copy of that method, and you can call that method without having an instance of that class. For example, the abs method in the Math class is defined as a static method, so you can call it like this: int value = Math.abs(-42); That works, and the reason it works as shown is because abs is defined as static. Static means: - There is only one copy of this method (as opposed to one version of the method for every instance) - You can call abswithout needing to first create an instance of Math In fact, the way the Math class is written, this code doesn’t make much sense: Math math = new Math(); // don't do this int value = math.abs(-42); // don't do this either Because all of Math’s methods are static methods, it’s not intended to work this way. To be clear, you don’t need an instance of the Math class to call its methods; because they are defined as static methods, you don’t need an instance of Math. Just call its methods directly, such as Math.abs(-42). An example If that doesn’t make sense, I’ll try to demonstrate more of this problem using an example. In the source code below I’ve created an instance variable named foo and an instance method named doFoo. These are referred to as instance variables and methods because you must create an instance of the StaticReferenceExample class to instantiate and then use them. In other words, they aren’t static fields of the class. Hopefully that helps explain where these error messages come from. Because a static method, like the main method, exists at the class level (not the instance level), and can therefore be accessed without having an instance of the class created, the static method can't access and instance variable or method. Here's an example Java class that intentionally creates both compiler errors. I've put comments by both statements that are not valid. package com.devdaily.javasamples; /** * Demonstrates invalid static references to an instance variables * and instance method. * Created by Alvin Alexander,. */ public class StaticReferenceExample { // a sample instance variable private String foo = "foo"; // a sample instance method private void doFoo() { } // main is a static method public static void main(String[] args) { // creates this error: Cannot make a static reference to the non-static field foo foo = "bar"; // creates this error: Cannot make a static reference to the non-static method doFoo doFoo(); } } solution so where is the solution The solution is to access The solution is to access non-static fields and methods from non-static methods. In a small, sample Java class like this, you can access these methods from the class constructor, which is not a static method. Here's a modified version of that example Java class that shows how to get rid of those compiler errors. In this example, the main method creates a new instance of the class by calling the class constructor, and then the constructor can access the non-static members without generating the "cannot make a static reference to the non-static field or method" error message: IF below is my code: public IF below is my code: public class duplicate { int temp; int ar[] = {'1', '2', '1', '7', '3'}; int count; private void find() { for(int i = 0; i < 4; i++) { temp = ar[i]; if(ar[i] == ar[i+1] ) { count += 1; } } } public static void main(String args[]) { duplicate dup = new duplicate(); dup.find(); System.out.println("The No of duplicates is : " + count); //line 45 } } what do I need to remove the error Cannot make a static reference to a non sttaic field sount at line 45 Make count a static field The thing you have to do here is make counta static field, because you're trying to reference it from a staticmethod ( main). Because a static method can be referenced by other classes without creating an instance of the class, you can't use an instance variable the way you have countshown. Just put the statickeyword before your declaration of count, and your code will work okay: Also, I'm not sure exactly what you're working on, but an incremental improvement to the code would be to return the countvalue from your find()method, something like this: It should be as this It should be as this: Sorry I am a DUMB Add new comment
http://alvinalexander.com/blog/post/java/compiler-error-cannot-make-static-reference-to-non-static
CC-MAIN-2017-17
refinedweb
1,079
61.9
Jesse Kaplan, one of the CLR program managers, explains why you shouldn't write in-process shell extensions in managed code. The short version is that doing so introduces a CLR version dependency which may conflict with the CLR version expected by the host process. Remember that shell extensions are injected into all processes that use the shell namespace, either explicitly by calling SHGetDesktopFolder or implicitly by calling a function like SHBrowseForFolder, ShellExecute, or even GetOpenFileName. Since only one version of the CLR can be loaded per process, it becomes a race to see who gets to load the CLR first and establish the version that the process runs, and everybody else who wanted some other version loses. Update 2013: Now that version 4 of the .NET Framework supports in-process side-by-side runtimes, is it now okay to write shell extensions in managed code? The answer is still no. Wasn’t this one of the big reasons for the Reset? It would seem to me that desired CLR versions ought to be specified as a threshold, i.e. I need version GREATER THAN OR EQUAL TO N.N.N . Is it just me or were some of those responses horrifying? It seemed like people were thumbing their nose of two people who know a metric ton more about the inner workings of CLR and WindowsShell than anyone else on the planet, and yet they were trying to argue the point. If it was all hypothetical, then that’s one thing…but I don’t believe it was. Raymond, is Rowland right? Did MS release a RawImage thumnail extension written in .Net? Steve "[That assumes that there will never be any breaking changes to the CLR. Whether that’s a valid assumption or not I leave you to determine. -Raymond]" Yes it’s a valid assumption. When .NET 2.0 just entered public beta, my company released a .NET 1.1 program. It didn’t work on 2.0. The CLR team has no problem breaking stuff between major releases. Any change can be considered a "breaking" change, because it is possible to make a program rely on a specific behavior no matter how incorrect or obscure. For example, let’s say you have a CLR 1.1 shell extension Foo that does FTP, and is has a class called FtpRequest. When you run it on CLR 1.2 which implements its own FtpRequest class, Foo stops working because it gets the CLR’s FtpRequest instead of your own. Of course you could just put the class in a namespace (like you should have done in the first place) and recompile, but your customers can’t recompile. They already have the broken version and upgrading their CLR will break it no matter what. You could mark Foo as requiring CLR 1.1, but if the next extension to load requires CLR 1.2 then it will fail. The correct behavior in this case seems to be to just allow multiple versions of the CLR in a process. Unfortunately this means every single app with so much as a File Open dialog will end up loading every version of the CLR because one extension will be marked with v1.1, another will be v1.0, another will be v2.0, etc. Since that would be a disaster, it’s best to stay away from managed shell extensions. Is this the reason why the Windows Sidebar has a .NET object model() but gadgets must be developed using HTML + scripting using this object model. Or did I miss something about Gadget-development? Hopefully somebody at Microsoft is working to remedy this issue for the next release of Windows and/or .NET! "is Rowland right? Did MS release a RawImage thumnail extension written in .Net?" Yes, (s)he is correct. See Maybe some intern developed it or somebody in their spare time. Anyways would be appropriate with some kind of warning at that download page so customers become aware that installing this extension might cause incompatibility issues. It’s so comforting to see that the famously successful methods developed over the past couple of decades for managing DLL version dependencies have been adopted without modification for managing the analogous CLR problem. -Wang-Lo. Raymond, I’m pretty sure that Wang-Lo’s comment was just dripping with sarcasm. Gabe: That’s your fault for mucking around in someone else’s package :) I was worried what this might imply, and found that on the referenced link at the top, you pointed out: So, if I read you correctly, building generally consumable in-process COM objects with managed code is a potential no-no. I’m not fully up to speed with .NET, but I believe there’s a COM wrapper you can use around a .NET interface. Do these run out of process to circumvent the potential conflict? No, it’s exactly this wrapper that causes the problems. I’ve been toying with writing an out-of-process shell extension plugin for a while (like with IIS & ASP.NET). The extension would just pass requests to a "worker" process to handle the actual work. You could then have one worker process per version of the CLR that you needed. It should work for most extensions (property pages being the most difficult one) but I’m not sure what the performance would be like… This came up where I work, trying to write an MFC app that called a .NET component using the COM wrapper – and the component only worked on CLR 1.1, not 2.0. The eventual solution we reached was for the MFC program to load CLR 1.1 using CorBindToRuntime before instantiating the component. I like Dean Harding’s idea. I’m thinking this is a problem because shell extensions are done through DLLs. The alternative though is that you have to run all your shell extensions as services which then communicate with the shell. I would think the Singularity team at Microsoft Research have been looking into this as the O/S they have developed doesn’t have support for DLLs. The versioning problem is unavoidable for in-process objects anyway, since a function can only have one definition (and two-level namespaces, ala OS X, are a cure worse than the disease). We run into the same problem in unixland with multiple incompatible libstdc++ versions in programs with plugins. The real WTF here is that shell extensions are loaded into every process that happens to use the shell namespace. Why wasn’t it designed to talk using IPC with some shell daemon from the get-go? It’s like the Unix NSS problem magnified a thousand-fold. If code injection is the answer, you’re probably asking the wrong question. John Stewien: There are two traditional uses for shared library: A) Sharing code for efficiency’s sake (e.g., libc or msvcrt), and B) Loading potentially changing modules into a process (shell namespace extensions, unixland NSS, winamp plugins, etc.) While A, with proper versioning, is a huge win, I think that B often brings more trouble than it’s worth. Every modern OS uses that architecture at some level, though, but I don’t see why. Would using IPC really cost that much more? I can see a case for B in plugins that are tightly integrated into a host program’s GUI, but even that would be manageable with some kind of out-of-process COM trickery, I imagine. > every shell extension were a service That’s not how I would do it. My extension would essentially be a “framework” that developers would write their .NET extensions against. I’d only load one worker process per version of the CLR that you needed – each extension would simply reside in an AppDomain of that worker process. Obviously, it wouldn’t be a service, either. The worker process would just run under the same account as the launching explorer.exe. What security vulnerabilities? You’re running services on the box; since they expect to be explorer extensions, they’re only accessible from that box. The question is how to partition something like that when multiple users are on the box – you may end up with some sort of corba like beast. All I can see from this thread is that C# isn’t nearly as handy as straight C++. Wouldn’t it be nice if we had some lightweight messaging interface? You could write an extension as out of proc and have the CLR and proc issues handled automatically, while designing APIs that didn’t drag ass in large directories and other extreme cases. Of course, this is complicated, and wouldn’t fly too well when the guy writing the exception is at the level of a typical VB6 programmer. <blockquote>Yes it’s a valid assumption. When .NET 2.0 just entered public beta, my company released a .NET 1.1 program. It didn’t work on 2.0. The CLR team has no problem breaking stuff between major releases. – J</blockquote> I think they have no qualms about maintaining compatibility because the CLR is versioned. You can’t run your 1.1 program on CLR 2.0, but on the other hand, you can install CLR 1.1 on the same machine that runs CLR 2.0 and both will co-exist and programs written for both versions can co-exist and run by correctly loading the version of the CLR it needs. Originally, the CLR team specifically denied any claim that future versions of the CLR would be backwards compatible. Instead, IIRC, they claimed that all versions of the CLR would work side-by-side. Now, this solution isn’t perfect, and nobody wants 10 versions of the CLR installed, but it seems like it was probably the best solution for 1.0, 1.1, and 2.0, as .NET is changing very quickly and compatibility issues are certainly going to be a problem. Even so, strong backwards compatibility was an important goal for 1.1 and 2.0. Neither one has perfect back-compat, but they’re not terribly bad, either. Of course, it only takes one back-compat issue to make YOUR app (the most important app in the world) not work. For now, it isn’t terribly outrageous to have 1.0, 1.1, and 2.0 installed, allowing you to bypass most back-compat issues (assuming nobody does something silly like load two different .NET DLLs with different requirements into the same process). In the future, a whole new CLR for each revision becomes less maintainable. In addition, as more components want to share the process space, cross-CLR compatibility will become more important. And as the platform matures, this will become more possible. For example, notice that .NET 3.0 uses the same execution engineas .NET 2.0, so it can share the same process space. I’ve heard that other, less visible changes have also been made under the covers that will allow this to continue even with changes to the execution engine. In any case, while .NET hasn’t been perfect, it is not fair to say they didn’t learn anything. It is leagues ahead of plain-vanilla DLLs and COM in versioning strategy, and avoids so many versioning issues in both the framework and in end-user apps. The root question is: why is the CLR linked against the managed executable using what is in effect a process-wide namespace? Because if multiple CLRs could co-exist, an extension needing CLR 1.0 would link against that CLR, and another could link against CLR 2.0. That doesn’t sound hard: if an managed app wants symbols from CLR 1.0, in the compiler simply prefix every symbol with CLR10. If from 1.1, CLR11. Of course, you would still end up with a big Shell that way, but that is probably not too important. If it is important (1000+ customers or so), you’d be looking at stuff like LIBCTINY, not .NET. “Remember, Windows 95 had to run in 4MB of memory. ” So? Vista requires at least 512MB. The .Net framework is not even available for Windows 95, so it is irrelevant to this discussion. The ‘proper’ solution to this problem would be something like Dean Harding is suggesting, only supplied as standard with, say .NET 3.2 and made the recommended way to create shell extensions, with a couple of templates included in the next iteration of Visual Studio. Of course, this solution would have violated Windows 95’s holy 4MB, but nobody cares about that anymore. And when will Microsoft seriously start to ‘dogfood’ .Net? So far the only ‘serious’ commercial applications written in .Net released are the hardly-heard-of-let-alone-used Microsoft Expression Suite. Come on! How about at least re-writing the Windows Accessories in C# or porting Visual Studio to .Net? Maybe then Microsoft will find more of these ‘limitations’ of .Net and have more incentive to fix them, rather than treating .Net developers as second-class-citizens (except when it comes to new UI stuff). mechanism should have been based on out-of-proc servers. That would not have been practical in 4MB. Therefore, the shell extension mechanism is in-proc. -Raymond] Load .net framework multiple times? Stupid architecture. Daniel Colascione: How about C) Being able to fix a security vulnerability in one library (e.g. zlib) and have it applied to every process that uses that library, across the whole system. Maybe that’s not a "traditional" use of libraries, but it’s sure a good use. That’s off topic because .net fw doesn’t run in win95 .net framework 1.1 cannot run Comapct framework 1.0 apps even if .netFW is supposed to be a superset of CF. Burak KALAYCI: yeah, but it didnt refuse to start on a 4MB box. if it had out-of-process shell extensions, you wouldn’t be able to start the shell at all. I pity you if you make all your decisions this fast. Managed code makes lot of tasks easier. It has some drawbacks you need to be aware of, just like everything else. Stu: [cite]So far the only ‘serious’ commercial applications written in .Net released are the hardly-heard-of-let-alone-used Microsoft Expression Suite.[/cite] Have you heard of SQL Server, Visual Studio Team System, Office Server, BizTalk Server… Microsoft has lot of quite serious .NET-based products. There is no point in rewriting legacy code just for the rewrite sake. > yeah, but it didnt refuse to start on a 4MB box. Yes it did start, I have to credit that. I remember something like the base mem for executables were at 4MB default and W95 had to fix all jumps before running them in a 4MB box and that caused extra slowness. I always had the impression that it wasn’t really designed for 4MB… > I pity you if you make all your decisions this fast. Fast? I made my decision around May 1990. It was between 80×86 assembly and gwbasic. I feel no remorse. Best regards, Burak > Non sequitur. Physical address space is not linear address space. I may be totally wrong. What I was talking about is the image base set by linker being at 4MB by default causing extra relocation effort when loading on a system with just 4MB memory. I had read it somewhere, I’m not sure if it really makes sense (or if I remember it correctly). Best regards, Burak Guess I was talking about the following, ‘In executables produced for Windows NT, the default image base is 0x10000. For DLLs, the default is 0x400000. In Windows 95, the address 0x10000 can’t be used to load 32-bit EXEs because it lies within a linear address region shared by all processes. Because of this, Microsoft has changed the default base address for Win32 executables to 0x400000. Older programs that were linked assuming a base address of 0x10000 will take longer to load under Windows 95 because the loader needs to apply the base relocations.’ Turns out my memory is not as good as I’d have liked. Best regards, Burak "Remember, Windows 95 had to run in 4MB of memory. " I remember that! I’d say it ‘crawled’ with 4MB. 8MB was the real minimum it managed to ‘run’ (Though I haven’t tested any memory size inbetween). My take: Don’t write *anything* in managed code. Best regards, Burak How did you choose not to write apps in .NET in 1990? Gabe, The class name resolution rules, at minimum, also include a reference the containing assembly. The CLR knows FtpRequest in your assembly is not the same class as FtpRequest in any other assembly, so this situation cannot occur. Michiel, The CLR is not a library that is linked to an executable; it is a runtime. On newer versions of Windows, a flag in the managed .exe header instructs the OS loader to launch and initialize the CLR, which then loads and executes the managed code from the .exe. (On older versions of Windows, a native-code shim in the .exe’s entry point launches the CLR instead.) Because it is a full runtime, which manages detailed characteristics of the low-level process environment, it is not possible for it to play well with any other code that wishes to do the same thing. Consider the Garbage Collector, which needs to understand memory usage in the process, in order to correctly self-tune. Two such GCs would end up fighting each other, much as two processes that try to efficiently use all available RAM on a server would behave. (There’s an old blog post somewhere about, IIRC, IIS and SQL Server that describes a similar case.) Or for something more high-level, consider the WinForms part of the Framework. Naturally it requires a message loop for a managed thread, and there can be only one main message loop (broadcasts, non-window messages, etc). How are WinForms 1.x and 2.x supposed to both have a main message loop at the same time on the same thread? So it’s not just a simple symbol naming issue :) RandomReader, here’s what I said "Of course you could just put the class in a namespace (like you should have done in the first place) and recompile, but your customers can’t recompile." The CLR will only know that your main assembly is asking for a class called "FtpRequest". Since this putative app is not directly referencing Foo.FtpRequest, the CLR will look for FtpRequest and its own version first. Like I said, there are trivial steps to take ahead of time (strong names, namespaces, etc.). If you didn’t do this when compiling your apps the first time, though, you’re in trouble if your client only has the old version of the app and the new version of the CLR. In the case of a shell extension, you don’t get to choose which version of the CLR to load, the app or the first managed shell extension does. The only way to guarantee it working in this case is to send out a recompiled version using properly bound names. Gabe, shouldn’t people be using signed assemblies on released products, and thus not have this problem? Also isn’t the take home message of all this "Don’t use managed code in shell extensions"? Managed code should just be used for fancy GUI stuff and web apps surely. Is C/C++ really that hard? It’s all I used up until 5 years ago. Gabe, That’s what I’m saying is incorrect: if your app’s assembly name is Foo (normally filenamed Foo.exe as well, but that isn’t relevant), all references to FtpRequest will in fact be to FtpRequest in assembly Foo. Explicit namespaces are necessary for organizational reasons, but not for type resolution. This is the same concept as for native executables: the PE import table references a specific DLL, not just a symbol from anywhere at random. > How did you choose not to write apps in .NET in 1990? I will give a short answer as this is quite off topic. At the time, there was gwbasic (interpretted and managed) and Assembly option (with Debug for .COM files), both came free with DOS, on my 12MHz 286 with 1MB ram and 40MB harddisk. I simply realized that for my programming pleasure, *I* had to ‘manage’ all aspects of what I write as much as possible. It’s like manual transmisson vs. automatic transmission preference (in cars)… Best regards, Burak What about Office add-ins? I’m having trouble reconciling the discussion here with the apparent encouragement to write managed add-ins for Office represented by the existence of VSTO. Doesn’t the same problem exist there (although without the file dialog issue)? Is VSTO only practical in completely controlled environments where all add-ins are guaranteed to use the same CLR? Sorry, I know this is straying off-topic for Raymond’s expertise; you’ve got a knowledgable community here, though. Eric: Office add-ins are a little different. The problem with explorer extensions is that your extension gets injected into every other process that tries to open a file-open dialog (or other things). Office add-ins are only run in the Office executable (well, usually – I’m not sure what happens with OLE in this case). When you call a CCW (that is, a .NET object implementing a COM interface) from a native application, the infrastructure (by default) loads the most recent version of framework that’s installed. So Office will typically be running .NET 2.0. This is not a problem for most .NET 1.1 add-ins, which will mostly run quite happily under .NET 2.0. With explorer, it doesn’t always work like that. If you have a process that has ALREADY loaded the 1.1 framework, then it tries to open a file-open dialog and load your .NET 2.0 extension… bang! Eric, Dean: Office components always run out-of-process when started through COM, so it’s not an issue in that case Daniel, Cooney: I’m always surprised at the lengths people will go to try and contradict Microsoft’s design choices, often apparently for the heck of it. The "try to fix this Windows bug" challenge was especially eye-opening To everyone else: don’t mix .NET and native code, it’s a terrible practice. Do it only if forced to do so, but don’t incorporate it in an architecture developed from scratch It’s inefficient and terribly embarassing to the runtime, which never has the slightest idea how to handle native calls – will it corrupt the managed heap? will it close one of my internal handles? will it violate security policies? etc. Internal framework functions are not P/Invoke, for a good reason – their C++ implementations are so filled with static code checking annotations (pssst, .NET sources are public) as to virtually offer the same guarantees as managed code Nevertheless, if you absolutely have to, make it so managed calls native and not the other way around. Native code rarely owns a whole process (notable exceptions are DBMSs, in fact .NET 2.0 was specifically tuned to be hosted by SQL Server) the way a runtime does, so despite the huge inefficiency it’s not quite as dramatic as pulling the runtime in a random process I thought it just works. Really? I wonder what all these exe’s I’ve been writing for years are. Are you sure about that? I use both Lookout and Newgator in Outlook, both of which are .NET add-ins and both of which run in-process. Perhaps they don’t use VSTO, though… Viewed as a data flow component, a property handler has a single file stream input and outputs a one
https://blogs.msdn.microsoft.com/oldnewthing/20061218-01/?p=28693
CC-MAIN-2017-39
refinedweb
4,016
65.32
Sometimes things take longer than anticipated. And this is definitely the case for my USB MSD Host project where I wanted to use a USB memory stick with the Freedom FRDM-KL25Z board. But finally, I have things working. At least most of the time …. USB MSD Host The USB MSD (Mass Storage Device) class is designed to be used for things like diskette drives, hard drives or memory sticks. To attach a memory stick to the USB bus, the memory stick is usally a USB device, and the other side needs to be the host. The first barrier to overcome is the FRDM-KL25Z board does *not* give the needed 5V to the USB bus which is required for the host mode. To overcome this, I’m using a patched USB cable as outlined in this post. File System While it is possible to use the MSD device as a ‘raw’ device (doing raw block read/write operation), the usual way is to use the device with a file system on it. I’m using the open source FatFS with SD cards successfully already in many projects, so I decided to use FatFS in this project too. Operating System While it is possible to add USB MSD Host support in bare metal (without RTOS), using an RTOS makes it much more convenient and less complicated. I have ported the Freescale USB stack for this project. While the stack itself does not assume an RTOS, many aspects of the stack like memory management or periodic polling of the USB device block are handled in such a complicated way, that I think using it without the help of an RTOS makes things really difficult. Especially the dynamic memory management in the USB stack had many inconsistencies, and to track potential memory leaks the help of FreeRTOS was critical. So this is what I ended up using: FreeRTOS. Processor Expert Components The example project (link at the end of this article) has several Processor Expert components. Beside of the RTOS, it has components for LED’s, a command line shell implementation, the FatFS file system and the USB Host components: FatFs Memory The FatFsMem_USB_MSD component implements the ‘memory’ device for FatFs: it allows to read and write to the device. The FatFs low-level routines are not exposed for the user application, as used internally by FatFs. What are exposed is are initialization and utility routines: Freescale USB Stack Component My custom USB stack component is using the Init component to initialize the low-level USB peripheral of the Kinetis device. Additionally it includes the FSL_USB_MSD_Host component which is a wrapper to the Freescale USB stack: Host Task The USB stack needs to be polled periodically to do the USB transactions. I have implemented this like this as a FreeRTOS task: /* * host.c * Author: Erich Styger */ #include "host.h" #include "msd_commands.h" #include "CLS1.h" #include "FRTOS1.h" #include "FsMSD1.h" static void print(unsigned char *str) { CLS1_SendStr(str, CLS1_GetStdio()->stdOut); } static void CheckStatus(void) { switch (FsMSD1_GetDeviceStatus()) { case USB_DEVICE_IDLE: break; case USB_DEVICE_ATTACHED: print((unsigned char*)"Mass Storage Device Attached\n" ); break; case USB_DEVICE_SET_INTERFACE_STARTED: break; case USB_DEVICE_INTERFACED: break; case USB_DEVICE_DETACHED: print((unsigned char*)"\nMass Storage Device Detached\n" ); break; case USB_DEVICE_OTHER: break; default: print((unsigned char*)"Unknown Mass Storage Device State\n"); break; } /* switch */ } static portTASK_FUNCTION(HostTask, pvParameters) { (void)pvParameters; /* not used */ FsMSD1_HostInit(); for(;;) { FsMSD1_AppTask(); CheckStatus(); FRTOS1_vTaskDelay(10/portTICK_RATE_MS); } } void HOST_Init(void) { if (FRTOS1_xTaskCreate(HostTask, (signed portCHAR *)"Host", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY+2, NULL) != pdPASS) { for(;;){} /* error */ } } After initialization using FsMSD1_HostInit(), it periodically calls the polling routine FsMSD1_AppTask(). CheckStatus() is used to print a message if a device is attached or removed. The “Host” task is running with a higher priority to make sure the USB bus is served often enough. Shell Support I have recently added command line support to the FatFs Processor Expert component. That way it is really easy to add a command line interface to the application where I can inspect the file system, copy files, dump files, etc. The user application part of the shell is implemented in a task, and the command line handlers are listed in a table: /* * Shell.c * Author: Erich Styger */ #include "Application.h" #include "FRTOS1.h" #include "Shell.h" #include "CLS1.h" #include "LEDR.h" #include "LEDG.h" #include "FAT1.h" #include "Host FRTOS1_PARSE_COMMAND_ENABLED FRTOS1_ParseCommand, #endif #if RTC1_PARSE_COMMAND_ENABLED RTC1_ParseCommand, #endif #if FAT1_PARSE_COMMAND_ENABLED FAT1_ParseCommand, #endif NULL /* sentinel */ }; static portTASK_FUNCTION(ShellTask, pvParameters) { bool cardMounted = FALSE; static FAT1_FATFS fileSystemObject; unsigned char buf[48]; (void)pvParameters; /* not used */ buf[0] = '\0'; (void)CLS1_ParseWithCommandTable((unsigned char*)CLS1_CMD_HELP, CLS1_GetStdio(), CmdParserTable); for(;;) { (void)FAT1_CheckCardPresence(&cardMounted, 0 /* volume */, &fileSystemObject, CLS1_GetStdio()); (void)CLS1_ReadAndParseWithCommandTable(buf, sizeof(buf), CLS1_GetStdio(), CmdParserTable); FRTOS1_vTaskDelay(10/portTICK_RATE_MS); LEDG_Neg(); } } void SHELL_Init(void) { if (FRTOS1_xTaskCreate(ShellTask, (signed portCHAR *)"Shell", configMINIMAL_STACK_SIZE+300, NULL, tskIDLE_PRIORITY+1, NULL) != pdPASS) { for(;;){} /* error */ } } Because some of the FatFS shell operations like to copy a file are using a local buffer on the stack, the task stack size is higher than for the other tasks in the system. Command Line Interface The following shows the command line interface: With the commands it is possible copy/delete/rename/etc files, or to print the current directory: Dynamic Memory Usage The Freescale USB stack is using malloc() and free() to allocate memory. I have replaced them with the FreeRTOS counterparts so I can track the memory usage. The screenshot below shows the free memory (heap) without a memory stick attached, and afterwards: That means that the USB stack has allocated an extra amount of 3160-2528=632 bytes. Removing the memory stick will free up memory again up to 3072 bytes free bytes, and will go back to 2528 bytes with the memory stick attached. I’m still not sure why it does not free up all the memory, but at least there is no memory leak. I still will need some time to understand where and why the USB stack needs the dynamic memory allocation. Summary Finally I have my USB MSD application with FatFs and FreeRTOS running :-). It was much harder than I thought, mainly because of the Freescale USB stack implementation. The GNU gcc compiler warned me about many things, and I have cleaned up the code as much as I could, but I think I still will need time to find and fix bugs in it. I still see occasional problems where the code is stuck in a loop. I need to replace that code with some timeout functionality. The other thing I faced: with the USB stack, my application ROM size exceeded the 64 KByte limit of the free CodeWarrior version. Using the -O1 compiler optimization brought it back it 48 KByte of code. Still, using a USB Host stack sounds like a lot of overhead compared to a SD card interface. I’m still dreaming of having a USB MSD bootloader which only needs a few KBytes of my Flash memory… Source Code and Example Project The full source code and Processor Expert components are available on GitHub. The example project shown here is as well available in this GitHub repository here. Happy Hosting 🙂 Excellent!!! Excellent, I ussually came and check what are you doing, great stuffs!! thanks for sharing your projects!! You are using the freescale usb stack with freertos. Is there no standard usb stack for freertos ?? From what I can tell most of the freertos demos use a ported usb stack for the micro architecture (e.g. LPC, Freescale, etc). It would be good if there was a more standardised usb stack for freertos which driver support for the various micros supported by freertos. The freescale usb stack is for no OS. I think this is used in MQX and/or MQX Lite, so I imagine it should be ported in a similar fashion for FreeRTOS. i.e. similar use of tasks, rtos services, etc. Hi Simon, I would *love* the fact if there would be a standard (open source) USB stack. That way this would be used as stanard with FreeRTOS. But I’m not aware of any which has been ported. There are bits and pieces, but not something working? As for the stack itself: there is not much you need to have it working with an RTOS, so no dedicated support needed. And if, I can easily add the FreeRTOS functionality (as I did). Hi Erich. I am grateful very much for your work. it’s very useful for me. I am new enough working with Freescale. I have tried to adapt your program to my MCU, K60, but it gives me some mistakes. It does not recognize me the FSL_USB_MSD_host in USB’s stack. The error is ” No inherited component assigned” in the MSDHost module. Other examples and programs I could have adapted to the K60, but this one gives me always mistake. Thank you!! Hello, thanks for that feedback, appreciated 🙂 As for the MSD Host mode: I have tried it on KL25Z only so far. I’m sure that probably I have missed to include something to properly support the K60N512 (the one I have). Let me see what I can do for you over the next couple of days. But I think that I might have missed some files/settings to properly support the K60. Sorry about that, as I needed it for the KL25Z only so far. But I’ll look into it. ok? Hi krlosb, I worked on the USB MSD Host stack most of today. The good news is: that error your report should be gone. I have put an example project on The bad news is: it does not quite work yet. It raises an interrupt when I attach a memory stick, but it does not properly enumerate. Not sure what the problem is. I think I’m missing something in the driver. Thanks a lot Erich, I prove it now. Pingback: Serial Bootloader for the Freedom Board with Processor Expert | MCU on Eclipse Hi Eric, Is there a method (or work around) to change the device class selector in the latest FSL_USB_Stack from a device to a host, or a host to a device? Regards, George Hi George, no, I don’t think so, as the code behind device or host class is very different. Erich Great Post Thanks Where can I find FatFsMem_USB_MSD component. It seems it is not at the zip file Eli Oh sorry. Great I found it in git mcuoneclipse\PEupd\ directory Hi Eli, did you use the one on GitHub ? It should be there. Thanks a lot. I found it there:) Your blog is a great entry point to freescale and CodeWarrior. Hi Eric, I tried to adapt the program to a K20 using the K60 selection on the FSL_USB_MSD_Host. There were no issues getting the components installed, and the project compiles without errors. The issue is the drive does not properly enumerate. After reading all the comments, I found a similar issue when using a K60. Do you know if anyone has found a solution for this issue? Regards, George Hi George, no, I don’t know that the issue could be. I have used the MSD host only with my FRDM-KL25Z so far. I do have a FRDM-K20D50M, so I might try it on this one. Would that help? Erich Hi Eric, I think it would help. I would expect the USB architecture of the FRDM-K20D50M to be close to the MK20DX256Z. Thanks, George Hi George, I started working on porting things to the FRDM-K20 board. I have made good progress today, but I need to see if I can find time tomorrow night on it. Hi George, I have published a FRDM-K20D50m project with USB MSD Host support here: I hope this helps. Pingback: USB MSD Host for the FRDM-K20D50M Board | MCU on Eclipse Hi Erich, I’m interested in USB MSD device bootloader, to programm MCU just by drag and drop binary file from host PC. Is it possible to do so basing on your host implementation? Did you made some attempts to implement such functionality and can you give me some advice how to bit it? Hi Adam, yes, I have implemented such a MSD bootloader which enumerates as a memory stick, and then I can copy files to it to program the board. I have done this for the JM128 on the TWR-LCD board. The project is as well on GitHub here: I have no done this yet for Kinetis. Thanks, it might be good starting point. Hi Erich, have you read application note AN4368 from Freescale? It’s the same as your MSD host bootloader, but for K60 family. The code of AN doesn’t use RTOS. Have you made some comparisons between the two results? For example, is your solution more code efficient? Hi Pozz, yes, I know this AN4368. But there is one thing: I do not use an RTOS for the bootloader neither. The application presented in this post is not the bootloader, it is the application which is implementating USB MSD host. A bootloader typically does not need an RTOS. The difference between AN4368 and my approach is that I’m using Processor Expert, which allows me to easily port my bootloader to different devices. Each approach has its pros and cons. Ah ok, now understand. What about the code size of your bootloader? Have a look here: It only takes 8 KByte in total. Hello Erich,i ‘m glad that this strange winter looks over in your garden Thanks for the above example I spent days trying to implement something similar based on USB_MSD_HOST_MQX_Lite_MKL25Z128_PEx example,in the USB stack 4.1.1. In run it detects the attached key,it prints all the tests but it restarts from zero every couple of seconds,as showed by a printf just after PE_low_level_init(); In debug it stucks in HardFault. Following your teachings i used the HardFault bean to analyze it,but strangely it mades everything working ok.I guess this fact deserves further attention. At this point i addedd the FatFs bean,but the FsMSD required to manage the underlying memory has references to freeRTOS.h for malloc functions etc. At this point i dont know ho to move. Can you help me about it? Diego Hi Diego, In which file did you had that reference to the FreeRTOS memory manager? I have it running on my side without FreeRTOS too. Erich HI Erich ,the reference is in FSMSD1.c #include “freeRTOS.h” /* FreeRTOS malloc() */ Please could you attach or link the project you ìre talkng about? So to compare them and find where i wrong Have a nice weekend and thanks Diego Hi,where is “FRTOS1.h”? I use your Freedom_USBHostMSD project in IAR,but 171 errors finded,Can you help me? FRTOS1.h (and others) are generated by Processor Expert. Are you using the Driver Suite with IAR? See Thank you! I am a novice in freescacle arm and IAR IDE。 I use FRDM-KL26Z+IAR+(your PE project). I add the components in PE from your PEupd folder,it’s ok. But when i make the project,more errors generated. such as: Warning[Pa050]: non-native end of line sequence detected (this diagnostic is only issued once) D:\FreeScale\user\test\Freedom_USBHostMSD\Sources\Application.c 1 Error[Pe079]: expected a type specifier D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\Cpu.h 163 Error[Pe141]: unnamed prototyped parameters not allowed when body is present D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\Cpu.h 163 Error[Pe130]: expected a “{” D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\Cpu.h 163 Warning[Pe012]: parsing restarts here after previous syntax error D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\CLS1.h 111 Error[Pe020]: identifier “CLS1_StdIO_In_FctType” is undefined D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\CLS1.h 112 Error[Pe020]: identifier “CLS1_StdIO_OutErr_FctType” is undefined D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\CLS1.h 113 Error[Pe020]: identifier “CLS1_StdIO_OutErr_FctType” is undefined D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\CLS1.h 114 Error[Pe020]: identifier “CLS1_StdIO_KeyPressed_FctType” is undefined D:\FreeScale\user\test\Freedom_USBHostMSD\Generated_Code\CLS1.h 115 what can I do next step? I do not have this on my side, but it looks like your IAR compiler does not find the header files/include files. It might be a bad idea to start with IAR tools if you are not familiar with it, as this IDE might not be something easy to start with as a novice, especially as IAR does not integrate in a seamless way with Processor Expert. Have you considered to use Eclipse/CodeWarrior/KDS instead? Then you would not run into these kind of issues. sorry for replying on different post But I feel replying here is more relevant to others who come later to this post So I asked that my code was overflowing .text by *** so Now i remember what the problem was I have set up every thing again from eclipse for that I have followed your DIY Free Toolchain for Kinetis: Part 9 – Express Setup in 8 Steps and successfully tested one demo PE_Blinky but I noticed when I imported your project Freedom_USBHostMSD from git that you used G++ lite (Orphaned configuration. No base extension cfg exists for org.eclipse.cdt.cross.arm.gnu.sourcery.windows.elf.debug.976069318) this means I think sourcery g++ lite for arm eabi is not installed on my machine So last time I made few changes those were changed toolchain to Cross ARM GCC when I did that and hit OK it gave internal error when I was able to compile it it gave compile time error so I renamed a variable to some another all occurances i think that was reason of thar error but how on earth change addition of a variable increases size by 1024 bytes I am not getting anything please help me understand this I’m using the GNU ARM Eclipse plugins (), and not the orphaned CodeSourcery ones? Now I have found a way out tried differant solution New PE project to which I have added All components changed linker do not generate start up and It compiled again this is wierd linker error I am facing This time I have avoided any modyfiction to code but I could not edit FSL_USB_MSD_HOST componets name Which is of redshaded modification was not posible So I have removed FSL_USB_STACK and added from library changed board type Generated code and compiled so this was linking error 03:31:11 **** Incremental Build of configuration Debug for project New_MSD **** make all Building target: New_MSD.elf Invoking: Cross ARM C++ Linker arm-none-eabi-g++ -mcpu=cortex-m0plus -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -g3 -T “C:/Freescale/workspace1/New_MSD/Project_Settings/Linker_Files/ProcessorExpert.ld” -nostartfiles -Xlinker –gc-sections -L”C:/Freescale/workspace1/New_MSD/Project_Settings/Linker_Files” -Wl,-Map,”New_MSD.map” -o “New_MSD.elf” ./Sources/Application.o ./Sources/Events.o ./Sources/Shell.o ./Sources/host.o ./Sources/main.o ./Sources/sa_mtb cygwin warning: MS-DOS style path detected: C:\Freescale\workspace1\New_MSD\Debug Preferred POSIX equivalent is: /cygdrive/c/Freescale/workspace1/New_MSD/Debug CYGWIN environment variable option “nodosfilewarning” turns off this warning. Consult the user’s guide for more details about POSIX paths: c:/kepler/gnu tools arm embedded/4.8 2013q4/bin/../lib/gcc/arm-none-eabi/4.8.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol __thumb_startup; defaulting to 00000410 ./Generated_Code/Vectors.o:(.vectortable+0x4): undefined reference to `__thumb_startup’ collect2.exe: error: ld returned 1 exit status make: *** [New_MSD.elf] Error 1 03:31:13 Build Finished (took 2s.688ms) Is this due to cygwin warning If it finds Cygwin tools, that would be bad. I have not installed Cygwin, as it is source of all kind of strange problems. The issue is if gcc finds something with cygwin, then it will try to use it with bad side effects. So if you have Cygwin installed (e.g in C:\cygwin), rename that folder so it is not found any more. Maybe this helps. I tried doing as you suggested renaming the cygwin directory but still same linking error I think it must not be getting something required for C++ linking error which I googled guess what the first hit is “” which seems to have solution Thanx for reply and that post of yours I will let you know what happens Hi Erich I have solved “./Generated_Code/Vectors.o:(.vectortable+0×4): undefined reference to `__thumb_startup’” problem by adding Start Up code (startup.c )file I have noticed that this is different from your start up files I tried your start up files but could not compile them because of But I am unable to compile them compiler says “fatal error: ansi_parms.h: No such file or directory” which means no ansi_params.h is not included in include path so could you please give me your both include paths or your suggestion about solving this problem I have noticed similar file exists in codewarrior directory exact path is CODEwarrior root/MCU/ARM_EABI_Support/ewl/EWL_C/include/ansi_parms.h but there is no way of finding this file else where. So my conclusions is they are created by codewarrior and Your project was successfully linked because you have compiled the source from codewarrior mine built in eclipse DIY tool-chain so is there any other way to sort this problem or do I have to compile this using codewarrior OR my above stated conclusions are fully / partially wrong waiting for your response I forgot to mention that I am getting same error as I was getting previously that/bin/ld: rtos.elf section `.bss’ will not fit in region `m_data’ /opt/gcc-arm-none-eabi-4_8-2014q1/bin/../lib/gcc/arm-none-eabi/4.8.3/../../../../arm-none-eabi/bin/ld: region `m_data’ overflowed by 1076 bytes 21:54:28 Build Finished (took 9s.563ms) so last time you have suggested this is caused by too many global variables but I think that is because I have to change “index” to “index1″ in Generated_Code/usbmsgq.c because if I dont change that I get this error Building file: ../Generated_Code/usbmsgq.c Invoking: Cross ARM C Compiler arm-none-eabi-gcc -mcpu=cortex-m0plus -mthumb -Os -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -I”/home/dev/.eclipse/org.eclipse.platform_4.3.2_1473617060_linux_gtk_x86/ProcessorExpert/lib/Kinetis/pdd/inc” -I”/home/dev/.eclipse/org.eclipse.platform_4.3.2_1473617060_linux_gtk_x86/ProcessorExpert/lib/Kinetis/iofiles” -I”/home/dev/abc/rtos/Sources” -I”/home/dev/abc/rtos/Generated_Code” -MMD -MP -MF”Generated_Code/usbmsgq.d” -MT”Generated_Code/usbmsgq.o” -c -o “Generated_Code/usbmsgq.o” “../Generated_Code/usbmsgq.c” ../Generated_Code/usbmsgq.c:38:16: error: ‘index’ redeclared as different kind of symbol static uint_32 index; /* << EST made it static */ ^ make: *** [Generated_Code/usbmsgq.o] Error 1 so what is way out of this Oh finally sorted out what was wrong I accidentally landed up reviewing FREERtos PE component and I found that heap memory allocated is 10000 in project which is does not match with your other article so I reduced that to 8192 and hurray I have rid-out of that linker problem now final linking issue so will you please help me out on this problem I guess that things are in library file libc.a and its not generated by me so there is something I am missing out over here so please help me solving this final issue These problems come from different runtime libraries :-(. That’s the pain switching project between toolchains like CodeWarrior and stock GNU ARM Embedded 😦 I had similar problems when I created a bare SDK project from scratch (see). I had no time yet to port this USB project to bare Eclipse, but looks I should. Could you try adding -specs=nosys.specs to the linker options (as outlined in above post)? hi eric I have used codewarrior this time to build project using generate code and then build projet then I have copied srec file to kl25z now I can see green LED blinking even on terminal I can see help menu but only two commands work help and status I tried diskinfo output was ” CMD> *** Failed or unknown command: diskinfo *** Type help to get a list of available commands ” and dir which you showed above still same ” *** Failed or unknown command: dir *** Type help to get a list of available commands ” note I am using windows7 machine so no hyperterminal available so I am using teraterm Is that the problem Hi Devidas, you need to enter the module name as listed in the ‘help’ command, e.g. FAT1 diskinfo or FAT1 help Pingback: Multi-Drive Support with FatFS | MCU on Eclipse I want to creat a msd devise with kl25z is it possible? Yes, that’s possible. Hello Erich, About FAT_FS lib, there are any command to create a file, write data and close the file? I try to substitute the VNC for KL25Z, but I need this functionalite. Thanks. Eduardo Yes, of course these functions exist, see Hi Erich, Here you connect a USB Stick to a FRDM-K64F but I would like to access my SD Card on my FRDM with a computer. So I want my FRDM as MSD Device using the K64 USB. I didn’t found tutorial here (or maybe I searched bad) PS: I didn’t find MSD_Device component… True, I have not done that (yet?). Hi Loic, no, I have not done that (but should not be too hard ;-)): use the FRDM-K64F as USB MSD device with running FatFS with the SD card. Would be a nice week-end project (but I’m booked out for the next weekends). Ok, I’ll see that Thanks you for all 🙂 Hi Erich Just wondering if the project files (tutorial steps) are up to-date with the latest processor expert version. I would like to try your example project on a newly acquired FRDM-KL25Z board.. Any recommendations and pitfalls to avoid ?? Thanks, David Hi David, are you using CodeWarrior or Kinetis Design Studio? The CodeWarrior project is here:. I don’t have it ported to KDS yet, but I have the same thing for the FRDM-K20 and KDS here: The project and tutorial steps are still the same, or at least I cannot remember anything special. The only thing I know is that some USB memory sticks cause problems. Sticks with less than 4 GB worked very well, while somehow sometimes sticks with larger capacity cause problems (not sure why). The board revision should not matter (I hope), the latest FRDM-KL25Z I have is the Rev E. one. Just make sure you properly power the 5V to the USB port. And that you do not consume too much current of course. Otherwise let me know and I see if I can send you a project with all the files. I hope this helps, Erich Hi Erich, Thanks for your quick reply…I’m using IAR development tools and I’m fairly comfortable using them. I have implemented code for the ultra small KL02 processor without using Processor Expert. For this project, If you do have files for the IAR tools then I will appreciate you make them available otherwise could you advise on porting your source code to IAR tools or any other tool in general. I will try to read up on Processor Expert and IAR to port your project files. Any help/recommendation will be much appreciated. Kind regards, David Hi David, we are not much using IAR, except the code size limited (free) version, because it is too expensive. Porting to IAR should not be a big problem, I try to have my sources compiler neutral as much as possible. But you need to watch out the inline assembly code (or guard it), as IAR is using a different syntax. The other thing ot watch out is to properly allocate the USB buffers to a 512 Byte boundary. Good luck! Looking for a similar USB bootloader solution for the K70. I see the new RomBootloader 1.2.0 is available for certain processors but maybe not yet for the K70? Will it be available anytime soon. So it seems the other solution is this MSD_USB solution embedded into your application, but all of this looks like legacy stuff compared with the new Kinetis RomBootloader. What path would you suggest here? I don’t want to waste a bunch of time implementing a non-supported legacy solution when it appears the forward path is now RomBootloader. 1.2.0 Thanks Yes, the USB stack I’m using is a legacy one. Freescale (well, now NXP) moved to the USB stack inside the Kinetis SDK. I’m still using that legacy USB stack because it worked very well for me. But in your case you probably go better with the stack in the Kinetis SDK? Hi Erich, I tried to make a project for k22fn1. Everything compiles fine but when I run the code, when it calls USB0_Init() it call an Interrupt and stays there. (PE_ISR(Cpu_Interrupt)) Did you notice that ever? Do you know whats happening? Thanks Hi Francisco, you need to find out which interrupt is causing this. See. Erich Hi again, I did that. The interrupt is: (PE_ISR(Cpu_ivINT_Hard_Fault)) Hi Francisco, no you need to find out what is causing the hard fault. See and Erich Hi Erich, I found the error is when I do the following command: USB0_CTL |= USB_CTL_ODDRST_MASK; Desassembly: 266 USB0_CTL |= USB_CTL_ODDRST_MASK; 00001540: ldr r3, [pc, #320] ; (0x1684 ) 00001542: ldr r2, [pc, #320] ; (0x1684 ) 00001544: ldrb.w r2, [r2, #148] ; 0x94 00001548: uxtb r2, r2 0000154a: orr.w r2, r2, #2 0000154e: uxtb r2, r2 00001550: strb.w r2, [r3, #148] ; 0x94 Thanks what the hardfault tells me. I tried to change the micro controller to make sure it was no broken, but still the same. What should I do now? Not sure out of my head what that assignment does. But it sounds this turns on some hardware which then causes the hard fault. Is your USB descriptor at the right place? Hi! I got the problem solved. On fatFs I had mode as device. Now I have host and all works fine. I tried to port your code and it runs without problem. The only thing is that when I put an USB stick it stays on USB_DEVICE_IDLE after checkstatus. What would the problem be? Francisco Hi Francisco, does it otherwise enumerate and work properly? Erich Hi, I noticed that the FreeRTOS is not working properly. I copied all your code. I schedule tasks but when I start them, it never goes there (I’m using breakpoints). I can’t understand why ins’t FreeRTOS working. Thanks, Francisco Hi Francisco, could you halt your target with the debugger and check where it hangs? I think you probably have not allocated enough heap memory so you are in the ‘out of heap’ hook (if not turned off that hook)? Erich Hi Erich, I have copied it to KDS and it worked well. but I have a runtime error as below when running Benchmark. ERROR: unlink failed: (13) There is no valid FAT volume on the physical drive What does this mean ? Thank you, Zohan Hi Zohan, this means something went wrong with deleting the file. Have you formatted earlier the device properly? Otherwise this is an indication that something else inside the file operation was going wrong, but hard to tell what. Hello eric sir, I am using mk64f freedom board. and I want to update my firmware using pen drive or say external flash drive. currently I am able to update bin file from PC to system using usb cable using “KinetisFlashTool.exe”, but now I want to update my firmware through Pendrive. I also downloaded the “USB_MSD_Bootloader.bin” file but no results found. Please help. I do have such a bootloader for the ColfFire V1 (see), but I have not ported that to Kinetis because lack of time and I have other research projects to complete first. But in general I would not recommend such a MSD thumb drive bootloader as it is very challenging with different Mac, Windows and Linux systems. Hi Erich, thanks for providing such a useful example ; ) I want to implement this demo to mount, open, write and read data from a memory stick, but I really don´t know how to do it without using shell commands you like the ones you have created. As I´m just a newbie with FreeRTOS, I´d like some support from you on how to create my own task, to do this job. P.S: While debbuging I tryed to use FAT1_open, FAT1_write, etc. at USB_DEVICE_INTERFACED case inside the static void CheckStatus(void) polling function, but without any success. Hi Marcio, are you using that example project? Because this one should work ‘as is’. As for FreeRTOS: there are plenty of example on my GitHub how to create a task already? I hope this helps, Erich Thanks for your reply Erich, Yes, I´m using it because I want a project with Processor Expert and USB MSD host to read/write files from/to a USB memory stick. This example is perfect for me, but I need to solve this Issue: I don´t understand is why it doesn´t work the code below at USB_DEVICE_INTERFACED case in CheckStatus function (host.c): case USB_DEVICE_INTERFACED: { static FIL fp; FAT1_FRESULT fres; UINT bw; byte buffer_USB[10]; // copy buffer const CLS1_StdIOType *io_test = CLS1_GetStdio(); static FAT1_FATFS fileSystemObject; fres = FAT1_MountFileSystem(&fileSystemObject, 0, io_test); if(fres==ERR_OK) { if (io_test!=NULL) CLS1_SendStr((unsigned char*)”File System mounted\r\n”, io_test->stdOut); } fres = FAT1_open(&fp, “WRITE.TXT”, FA_OPEN_EXISTING); if (fres !=FR_OK) { CLS1_SendStr((const unsigned char*)”\r\nOpen source file failed\r\n”, io_test->stdErr); } else { fres = FAT1_read(&fp, &buffer_USB[0], sizeof(buffer_USB), &bw); if (fres!=FR_OK) { CLS1_SendStr((const unsigned char*)”*** Failed reading file!\r\n”, io_test->stdErr); (void)FAT1_close(&fp); } (void)FAT1_close(&fp); if (FAT1_UnMountFileSystem(0, io_test)==ERR_OK) { if (io_test!=NULL) { CLS1_SendStr((unsigned char*)”File System unmounted\r\n”, io_test->stdOut); } } } break; } I also tryed using the standard functions of stdio.h, but soon I got stucked in a Hard Fault when I call a fopen: static void CheckStatus(void) { switch (FsMSD1_GetDeviceStatus()) { case USB_DEVICE_IDLE: break; case USB_DEVICE_ATTACHED: LEDR_Off(); LEDG_On(); print((unsigned char*)”Mass Storage Device Attached\r\n” ); break; case USB_DEVICE_SET_INTERFACE_STARTED: break; case USB_DEVICE_INTERFACED: { FILE *fp; char str[] = “This is string”; fp = fopen( “file.txt” , “w” ); fwrite(str , 1 , sizeof(str) , fp ); fclose(fp); break; } case USB_DEVICE_DETACHED: LEDR_On(); LEDG_Off(); print((unsigned char*)”\nMass Storage Device Detached\n” ); break; case USB_DEVICE_OTHER: break; default: print((unsigned char*)”Unknown Mass Storage Device State\n”); break; } /* switch */ } You would have to debug it with the debugger (use a hard fault handler to make it easier, see. It could be caused by a stack overflow too, so make sure you have plenty of stack space available. Ok, I´ll do that. About the code I´ve inserted: Is it apparently correct? And is this configMINIMAL_STACK_SIZE define the only place that I have to increase the stack size of this Task? Hi Marcio, The stack size is specified at the the time you create the task with xTaskCreate(). You can use configMINIMAL_STACK_SIZE, or use something like configMINIMAL_STACK_SIZE+500. Hi Erich, Do you know about any example using PE component FSL_USB_MSD_Device linked to an SD working with FreeRTOS. Thank you. Hi Martin, I started working on such a project, but never was able to finish it. I used FatFS for the file system. I still have the project somewhere (for the FRDM-K64F I believe), but I faced problems with the NXP USB stack implementation. Hi Erich, I followed your suggestion and created a task, called USB_task, to mount, open, read and write a file to/from USB stick. The task worked fine, but I still facing some problems: 1) I only can open a .txt file if I call this function (I need to mount the file system first), but this is not a big deal for my purposes: (void)FAT1_CheckCardPresence(&cardMounted, 0 /* volume */, &fileSystemObject, CLS1_GetStdio()); 2) I wasn´t able to open a txt file called “PEx_FRDM__K22.TXT”, but I can do it if I rename it, like “TEST.TXT”. So, is there some file naming limitation, as number of characters or special characters? 3) I´d like to use this example to read a .srec file and make my own MSD Host Bootlader project, but I only can do this changing its extention from .srec to .txt. This is the lines I was testing: if (FAT1_open(&fp, “./STEST.srec”, FA_READ)!=FR_OK) { CLS1_SendStr((const unsigned char*)”*** Failed opening benchmark file!\r\n”, io->stdErr); return ERR_FAILED; } Is there some problem to open a .srec file? Regards, Marcio. Hi Marcio, you need to turn on LFN (Long File Name Support), otherwise FAT is limited to 8.3 names (8 characters file name, 3 characters extension). I hope this helps, Erich Ok, I got it Erich. I found this two constants that I could, apparently, turn on LFN in ffconf.h: #define _USE_LFN 1 #define _MAX_LFN 255 But, when I set _USE_LFN to 1, I got this error in ff.c: #error Static LFN work area cannot be used at thread-safe configuration. So, I think something is missing to make this happen. Can you help me on that? Are you using the McuOnEclipse Processor Expert component? If yes, it should set all the right settings for you. Otherwise see I hope this helps, Erich Yes, it´s your example I´m using (FRDM-K22F_USB_MSD_Host). Wich component and what should I do to set things right (enable LFN)? The link you post here () says almost the same thing is commented in the code (ffconf.h file): FF_USE_LFN This option switches the support for long file name (LFN). When enable the LFN, Unicode support functions ffunicode.c need to be added to the project. The working buffer for LFN occupies (FF_MAX_LFN + 1) * 2 bytes and additional ((FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT enabled. When use stack for the working buffer, take care on stack overflow. When use heap memory for the working buffer, memory management functions, ff_memalloc and ff_memfree, need to be added to the project. Value Description 0 Disable LFN. Path name in only 8.3 format can be used. 1 Enable LFN with static working buffer on the BSS. Always NOT thread-safe. 2 Enable LFN with dynamic working buffer on the STACK. 3 Enable LFN with dynamic working buffer on the HEAP. See that it asks to add unicode.c and ff_memalloc and ff_memfree functions. Please, it´s the only thing missing for me to go further with this project at this moment. In the component, under the LFN group, turn on ‘Use LFN’ with ‘Enable, dynamic heap buffer’. Configure the LFN Length to your needs (255 might be to larger for you). And turn on LFN Unicode if you really need it. Taking a look at community, I found this topic: But where I can find “ff_malloc”, “ff_memfree”,”ff_convert” and “ff_wtoupper” functions declarations to add to the project? and in wich file I should to add this functions? I did not had to add such functions in my code. Yes, It worked! Thanks Erich : ) My next step is to flash a .srec file read from the USB stick based on your serial bootloader example (). I think I´m not far from this goal, because I already made this project work as well at my side. Can I use your s19 PEx component to do that? My first idea was to read, line by line, the s19 lines and then flash them (again, line by line) to the app region. Do you have any suggestions, or tips for me to do this job, or at least to start it? Regards, Marcio. Hi Marcio, yes, you could use that S19 component for that. But I would not read and flash line by line: that will be far too slow. Instead, fill up a buffer up to the flash block size and then flash the block as a whole. I do this in the latest version of my serial bootloader. Ok,I will continue my efforts to complete this project : ) Hi Erich, I was trying to merge this example with the Serial Boot with PEx () and I´m facing a main problem here: the S19 component apparently was made to receive characters by Console (serially): How do I change this part to read the buffer from a USB Memory Stick (I’ve done the part of opening and reading the .srec file to a buffer and it’s ok)? Maybe just changing the GetChar callback (static uint8_t GetChar(uint8_t *data, void *q) ) or something else? Please, help. This is my final round to do this job ; ) Hi Marcio, yes, supply your version of the GetChar() callback.
https://mcuoneclipse.com/2013/03/02/usb-msd-host-for-the-freedom-board/
CC-MAIN-2017-47
refinedweb
6,826
63.39
Subscribe It looks like the next release of BizTalk Server will be Version 2009 instead of 2006 R3, as previously indicated. It’s on schedule for release in the first half of 2009, and I would expect to see a CTP version sometime before the end of 2008. 2009 provides support for UDM cubes and scalable real-time aggregations which enhances support for Microsoft PerformancePoint Server 2007. Enhanced Enterprise Service Bus (ESB) Guidance ESB Guidance 2.0 delivers updated prescriptive guidance for applying ESB usage patterns, improved itinerary processing, itinerary modeling using a visual Domain Specific Language (DSL) tools approach, a pluggable resolver-adapter pack, and an enhanced ESB management portal. Business to Business Integration Enhanced Support for EDI and AS2 Protocols BizTalk Server 2009 provides support for multiple message attachments, configurable auto message resend, end-to-end filename preservation, improved reporting to address new features, and Drummond re-certification for AS2. Updated SWIFT Support. Device Connectivity New Mobile RFID Platform and device management. New RFID industry standards support Support for key industry standards (including LLRP, TDT, TDS, WS Discovery and partial EPCIS support). Developer and Team Productivity New Application Lifecycle Management (ALM) support BizTalk Server 2009 provides support for Team Foundation Server (TFS), and allows development teams to be able to leverage the integrated source control, bug tracking, support for team development, Project Server integration and support for automating builds via MSBuild. Enhanced Developer Productivity. Other Enhancements Messaging. Administration. Full product roadmap at: Scenario: I have a need to process two transformations back-to-back. For example, I have Schema1, Schema2, and Schema3, and I have two maps: Schema1 is our canonical schema, meaning this is the schema we always use to "publish" to the MessageBox database. Consider this diagram in which we receive a message and publish the update to two line-of-business (LOB) applications: Notice what's missing? There is no Schema1 -> Schema3 map. In the real-life scenario that inspired this test, the maps are very complicated and it would be too much of an undertaking (currently) to invent a new map for transforming Schema1 directly to Schema3. So how do we apply multiple maps in a row using BizTalk? For this example, I've built out three schemas and two maps, as outlined above. Here are the schemas: Complicated, I know! =) First, the easy approach: Orchestration. This works, however the message in the real-life scenario is over 600MB. BizTalk Server, by default, will swap to disk for transforms performed in an orchestration when the message is over 1MB in size (see the note about TransformThreshold in this article). We can increase this threshold if needed, but 600MB is a bit excessive, I think. Once orchestration was ruled out, my first thought was to do something in a pipeline component; however, I wanted to see if I could do this without code. So how about this: I set up a WCF-based NetTCP receive location (and BizTalk sets up its own service host -- how nice) and a corresponding NetTCP send port. (In retrospect NetNamedPipes might have been better? Not sure, but this still worked.) On the way out of the send port, we transform to Schema2, which is published back to the MessageBox by the receive port. Finally, our LOB2 send port applies the second map on its way out. Yeah, yeah... it's clumsy... it's kind of a hack... but it was fun. Seriously, however, if anyone has a different approach, I'm all ears. =) Eventually the "correct" solution will be to create a map which transforms Schema1 directly to Schema3. Sample code:Order222|Item789 Order222|Item123 Order111|Item456Order <xsl:key From there, at the top of where we're going to start our /Orders branch, we can modify the "for-each" block to loop through our key instead of source nodes, like we might typically do. <xsl:for-each <xsl:for-each If we want to apply sorting, we can add: <xsl:sort <xsl:sort Finally we loop through the "groups" key we created before and output our data: <xsl:for-each <xsl:for-each The whole /orders branch of our XSLT now looks something like this: And here's the XML output: Notice that the orders are now sorted, despite being unsorted in the source file, and the items are now grouped by order. Nifty, huh? It seems I keep putting this list together again and again, so I think it deserves a "home" of its own. I'll try to keep it up to date. If you're a developer who would like to learn about developing applications on BizTalk Server, but don't have the time, resources or whatever to take one of the MOC-based courses, this list is for you. First, take a look at the BizTalk Virtual Labs to get started. I recommend you approach the labs in this order: After that, take a look at the samples included with the BizTalk SDK. In particular, check out the Messaging, Orchestration, and Pipeline samples (including one of my personal favorites, the Aggregator sample which demonstrates calling pipelines in orchestrations as well as aggregation and assembly of disparate messages). If books are more your thing, here is a list of BizTalk books I highly recommend. I'll try to keep the list up to date. No affiliate code here; I really truly recommend you check these out. Finally, start building solutions on BizTalk. Are they going to be perfect? Probably not. I know I'm still embarrassed by some of my own work that's still running in production somewhere (you know who you are), even though it works, and it works pretty well. But actually applying your knowledge is probably the most essential way to learn about building solutions in the BizTalk world. If you have the opportunity to take some official training, here are your courses: One more thing (I know, I already said "finally"), try to find a Connected Systems or BizTalk-related user group in your area. Live Search: Click here. If you can't find one near you, feel free to email me and I'll ask around.: Full MSDN URL: Full TechNet URL: San Francisco Bay Area Connected Systems User Group On June 26, 2008, please join us for the next scheduled Microsoft Bay Area Connected Systems Division User Group meeting. This month’s topic will be “Patterns for Delivering Enterprise Class Services”. If you would like to join us for this event, please click here to register! Location:Microsoft San Francisco OfficeGolden Gate Conference Room835 Market Street7th FloorSan Francisco, CA 94103 Time: 6:30 PM to 8:30 PM Food and Beverage will be served at 6:30 PM and session will start at 7:00 PM. Prizes will be raffled off at the end of the session. Patterns for Delivering Enterprise-Class ServicesPresenters: Brian Gaffney and Sandeep Kesiraju This session will discuss the successful approaches for application delivery in an SOA enabled enterprise. We will cover lightweight approaches that can be undertaken by every developer and follow the discussion through each phase of the software development lifecycle. Special attention with a given to ways of improving the qualitative/non-functional characteristics of services – performance, security, scalability availability, reliability of services in the runtime environment. Points will be illustrated using technology demonstration and real life customer experiences. Brian Gaffney is a Senior Systems Engineer for AmberPoint. He has been designing and delivering SOA systems for various clients in the commercial and federal marketplace for the past six years. In addition he recently lead the development of the AmberPoint’s monitoring and management solution for BizTalk as part of the ESB Guidance. Sandeep Kesiraju is a Premier Field Engineer from Microsoft. He has been architecting, designing and developing solutions using BizTalk Server for five years. He was also involved in the development of ESB Guidance Package for BizTalk Server with the Microsoft Patterns and Practices Team. The Microsoft Bay Area Connected Systems Division User Group is dedicated to helping the Bay Area customers design, develop, deploy, and administrate SOA solutions on Microsoft BizTalk Server technologies. If you would like to join the Bay Area Connected Systems Division User Group, please click here to be added to the mailing list! Recently I was working with a customer and giving a quick overview of how to retrieve data from SQL Server within BizTalk. We had a stored procedure that would return the first "unfetched" row, lock the record, set the "fetchstatus" and return the data "for xml auto, elements". Simple enough, right? Turns out, the data we cared about in SQL was already stored as a string of XML. My theory is that since the .NET (non-BizTalk) developer knew the data was going into BizTalk, someone said "hey, let's put the data in as XML since BizTalk uses XML." Again, just my theory. While this may sound nice, it actually makes our job a bit more complicated, because when you serialize XML to XML again, SQL will escape the XML string so it won't "break" the XML schema. For example, the string <element> becomes >element<. I think the real solution to this problem would be to re-evaluate the architectural decision to put the data into a column as an XML string, and instead alter the table to have the columns of data we care about, but we had less than a day to get an internal demo going and it would take too long to change this. So, what do we do to make this work "for now?" First, retrieve the data just like we would normally. Within our orchestration we now have our SQL message that looks something like this (generated via "Add Generated Items" in our BizTalk project): ...where MyString is the XML data we care about. Good 'nuff. But since we know this string of XML is actually a message we'll want to use, we'll also need to manually create a schema to match what will be coming out of SQL (so let's hope this data is consistent). In this example, let's say our XmlString looks like this: <XmlTest><Field1><Field2></XmlTest> ...or rather... <XmlTest><Field1><Field2></XmlTest> <XmlTest><Field1><Field2></XmlTest> ...or rather... <XmlTest><Field1><Field2></XmlTest> Then we need to create a schema to match: So what now? When we receive this message (let's call it msgSQLData) into our orchestration, we'll extract our XML string and store it in a string variable (strXml): strXml = xpath(msgSqlEvent, "string(/*[local-name()='SqlResponse' and namespace-uri()='']/*[local-name()='MyFetchTable' and namespace-uri()=''][1]/*[local-name()='MyString' and namespace-uri()=''][1])"); strXml = xpath(msgSqlEvent, "string(/*[local-name()='SqlResponse' and namespace-uri()='']/*[local-name()='MyFetchTable' and namespace-uri()=''][1]/*[local-name()='MyString' and namespace-uri()=''][1])"); Please also note that in this xpath statement, we use the xpath string() function. Now we have a string of encoded XML data in our orchestration. Now what? We need to add our XmlTest message (above) to the orchestration (let's call it msgXmlTest). In a message assignment shape (inside of a construct block for msgXmlTest, of course), I'm going to call a helper function that will need to do two things: It will return this as an XmlDocument type, which BizTalk converts to an XLANGMessage type on the fly inside of the orchestration, so we don't need to worry about it. msgXmlTest = Romp.Demo.SqlXmlStrings.Helper.XmlStrings.GetMessageFromXmlString(strXml, ""); msgXmlTest = Romp.Demo.SqlXmlStrings.Helper.XmlStrings.GetMessageFromXmlString(strXml, ""); Here's the code for our helper class: public static XmlDocument GetMessageFromXmlString(string XmlString, string Namespace) { XmlDocument doc = new XmlDocument(); XmlString = DecodeXmlString(XmlString); XmlString = InsertNamespaceString(XmlString, Namespace); doc.LoadXml(XmlString); return doc; } private static string DecodeXmlString(string XmlString) { XmlString = XmlString.Replace("<", "<"); XmlString = XmlString.Replace(">", ">"); XmlString = XmlString.Replace(""", "\""); XmlString = XmlString.Replace("'", "\'"); XmlString = XmlString.Replace("&", "&"); return XmlString; } private static string InsertNamespaceString(string XmlString, string Namespace) { return InsertNamespaceString(XmlString, Namespace, String.Empty); } private static string InsertNamespaceString(string XmlString, string Namespace, string NSPrefix) { int iLoc = XmlString.IndexOf(">"); string strNamespace = String.Empty; if (NSPrefix.Trim() == String.Empty) strNamespace = String.Format(" xmlns=\"{0}\"", Namespace); else strNamespace = String.Format(" xmlns:{0}=\"{1}\"", NSPrefix, Namespace); XmlString = XmlString.Insert(iLoc, strNamespace); return XmlString; } Here's a simplified example of what this would look like in an orchestration: We now have a message containing the data from the string of XML we got from the SQL database. From this point whatever you want to do with that message is up to you. In summary, we're going from this: To this: Since this is viewed in Internet Explorer, the <XmlTest> is converted to <XmlTest> for display. Here's the source: Since this is viewed in Internet Explorer, the <XmlTest> is converted to <XmlTest> for display. Here's the source: And finally, to this: If we wanted to do this same thing without orchestration (a good idea unless you need to do something requiring orchestration), we would use a custom pipeline component to convert the string of XML the same way, and put the "new" message on the wire for submission to the MessageBox. Sample code: A number of you (my customers) have asked about the support of BizTalk Server 2006 R2 and the 2008 wave of products (Windows Server, SQL Server, Visual Studio). Most of us expected a service pack release of some sort to update BizTalk to support these platforms; however, it looks like the work involved was substantial and as a result, Steven Martin has announced BizTalk Server 2006 R3 to support these platforms as well as a number of new features. We should see a CTP sometime later this year, with the release taking place in the first half of 2009. Some of the new features in R3: For customers who purchased BizTalk Server 2006 R2 under SA or EA, you'll get the upgrade free of charge. The question has come up more than a couple of times: How do I monitor my Send Ports or Receive Locations if I don't have MOM (or monitoring solution of your choice) configured for my BizTalk servers? I've always been positive the answer was in WMI, so I finally decided to see if I could write a very basic port monitor for BizTalk. First, I needed to build the WMI queries, using the WqlEventQuery class. Most of the WMI-specific classes mentioned here are in the System.Management namespace. Full source code is available at the end of the article.\""); Next I had to configure a ManagementEventWatcher for Send Ports and Receive Locations:); Then an event handler for each watcher: wmiReceiveLocationEvents.EventArrived += new EventArrivedEventHandler(WmiEventReceived); wmiSendPortEvents.EventArrived += new EventArrivedEventHandler(WmiEventReceived); wmiReceiveLocationEvents.EventArrived += new EventArrivedEventHandler(WmiEventReceived); wmiSendPortEvents.EventArrived += new EventArrivedEventHandler(WmiEventReceived); Finally, I fire them up: Console.WriteLine("Starting event watchers..."); wmiReceiveLocationEvents.Start(); wmiSendPortEvents.Start(); Console.WriteLine("Event watchers started. Press ENTER to exit...\r\n"); Console.WriteLine("Starting event watchers..."); wmiReceiveLocationEvents.Start(); wmiSendPortEvents.Start(); Console.WriteLine("Event watchers started. Press ENTER to exit...\r\n"); The event handler itself is where things got somewhat complicated, because the event itself doesn't contain the BizTalk-specific properties I'm interested in. So I had to dig a little. In this case, we're only interested in the TargetInstance:(""); } In case you're wondering, the ROOT.MICROSOFTBIZTALKSERVER classes are generated from the Management Classes in the Visual Studio Server Explorer. See this article for more details. So, how does it look? So from here you can do anything with these events that you'd like. I supposed you could even have the event handler generate a message that you send to BizTalk... as long as the port doesn't go down. =) Source code: God help you if you rely on my blog as your only source of BizTalk information. =) I'm a bit behind, but here's something everyone should know about: The BizTalk Server Operations Guide. Check it out.. I've heard about the possibility of another BizTalk TS position (my job) opening in SoCal sometime in the next few months. Got BizTalk skills? Email me: chris.romp [at] microsoft.com. A customer and former coworker of mine recently sent me a link to this blog post, whose author asks the question "When to use BizTalk vs. roll your own solution." Good question! BizTalk Server allows developers to quickly develop loosely-coupled, services-oriented applications for connecting multiple desperate systems in a highly-available, highly-scalable way. Can you do everything BizTalk Server does with just writing .NET code? Sure... BizTalk is written on .NET (2.5 million lines of code), and you could develop a similar solution I'm sure with millions of dollars and a large, experienced team of developers. BizTalk lends itself well to certain types of projects: Let's look at an EAI example using BizTalk Server and custom .NET code. In this scenario, we have an ERP system which needs to send customer adds/updates/deletes to our CRM system. Let's assume we'll talk directly to the database for the ERP system -- say, if the customer table has a trigger which writes to an update table that we can poll via a SQL stored procedure -- and for the CRM system we'll send it information using a SOAP web service layer that the application exposes. .NET way: We develop a windows service which will call the SQL stored procedure at a configurable interval. When we receive an updated record, we will take the columns from the data set and copy each element to its corresponding class item from the SOAP proxy class. Then we'll call the corresponding web service method and pass it the customer object. BizTalk way: We'll create a receive port using the SQL adapter which will call the stored procedure at a configured interval. Upon receiving an update from the stored procedure, we'll map it in the port to our canonical format (not required but a good practice) and publish the customer record to the message box. Next we'll create a send port using the SOAP adapter pointing to our CRM web service. Within this send port we'll create a subscription to the customer messages and map it from our canonical format to the CRM type. Both of these approaches are simple and fairly quick to develop, test, and deploy. Now let's mix it up. After running successfully in production for a couple of months, we're told by the business department that they expect the transaction volume to increase 10-fold. Since we didn't have this requirement up front, there's a very good chance that you'll have to rearchitect your .NET service to ensure it's multi-threaded and able to handle the increased load. Now a requirement comes down from on high that our application needs to be made highly-available, i.e. we need to enable the service to run on multiple systems in case one of them fails. Back to the drawing board for many .NET applications. With BizTalk Server, we just add another server to the group, and ensure our SQL message box is highly-available, probably using an active/passive cluster. Next comes a requirement for instrumentation of the application, and the statistics should be made available on the company's SharePoint portal. With BizTalk, we don't need to touch the code in production; we simply create a BAM observation model, deploy that model, and apply a tracking profile to the BizTalk service. The BAM data can be viewed using an out-of-the-box portal component which can be dropped into the SharePoint page. There are a number of ways to do the same thing using .NET of course, but needless to say you'll need to create a data repository, and open up your service code to drop data into the repository at set milestones during the process. Should the observation model ever change, you'll be reopening your code to make the changes yet again, unlike with BAM. Finally, a year later your company is going to deploy a customer portal which is hosted offsite and uses its own data repository for customer data, and will need to receive the updates from the ERP system as well. With .NET, you'll likely end up writing a new service for the 1:1 integration. With BizTalk, we just add another send port and have it subscribe to the customer messages already being published by the ERP system. In this example, I've admittedly oversimplified, but I think the points are valid. Also, I've completely ignored one of BizTalk's biggest advantages in this space: its adapters. There are a huge number of adapters for BizTalk to connect to line-of-business systems. If our ERP or CRM systems have a BizTalk adapter available, we have to do very little custom development to talk to these LOB apps. With .NET, there may be an API available, but you'll be doing a lot of manual development. BizTalk Server is not for everything, but what it does, it does very well and at a fraction of the cost of competitors in this space. In the future, I see BizTalk becoming more of a generic application platform. Say, for example, you develop an application using WCF and WF, and then you need to scale these apps out or apply any of the scenarios outlined above. I would expect future versions of BizTalk to be WCF and WF-based, and you should be able to take your WCF/WF applications and host them inside of BizTalk Server. Pretty cool, I think. To all three of you who read this blog (hi, mom!), if you're in the Los Angeles area tomorrow night Brian Loesgen of Neudesic and I will be presenting on BizTalk Development Best Practices at the Los Angeles Connected Systems User Group. This is a pretty good session that Brian and I have done a couple of times, and it's got some good information if you're brand new to BizTalk or even a seasoned developer! I also hear one of our newest BizTalk MVP's, Richard Seroter, will be joining us as well. (Oh, and please register if you plan to attend, so they can buy enough pizza.) Meeting Location: QuickStart – Los Angeles 1515 West 190th Street South Tower - Suite 450 Gardena, CA 90248 Meeting Location: QuickStart – Los Angeles 1515 West 190th Street South Tower - Suite 450 Gardena, CA 90248 A new BizTalk poster is available, in case you're collecting the series. [via] This one covers BizTalk Scale-Out Configurations, from simply adding servers to your BizTalk group to fully clustering your MessageBox database on a SQL cluster. Scaling out BizTalk is a good idea for any solution which requires high availability. One of the scenarios displays an active/passive BizTalk clustered host, which is typically only necessary if you have an adapter which doesn't run well in a group (i.e. FTP adapter -- no file locking in FTP). Most of the time I'd argue it's better to have your BizTalk servers in the same group without clustering. Clustering SQL as active/passive, however, is almost always a good idea. Active/active I'm not such a fan of, because in a high-utilization scenario it's difficult to know if one of the clustered services could handle the load that's usually shared between two. If you like active/active, you should consider active/active/passive, which is also outlined on this poster. When scaling out your MessageBox database, it's important to remember that you'll be going from one to three or more. The reason is that your master MessageBox database will be used for routing and subscription only, while the other (two or more) MessageBox databases will be doing the processing. BizTalk Hotrod just published a third volume. This one has fixed a lot of the readability problems with past issues (good luck reading sample code in volumes 1 and 2). =) Grab it from BizTalkHotrod.com or you can grab the 18MB PDF from this direct link. Trademarks | Privacy Statement
http://blogs.msdn.com/chrisromp/
crawl-002
refinedweb
4,032
61.77
This is a bugfix release fixing smaller issues, some of which was introduced in the previous feature release. New features: Bugs fixed: Fix a vmod_goto bug introduced in 6.0.8r2, where creating two identical dns_director objects would trigger an assert. (VS issue #1176) Fix a NULL pointer dereference in an error handling path in the JWT VMOD. Fix a NULL pointer dereference when setting namespaces in the Accounting VMOD. Fail correctly when the Stat VMOD is attempted called from Client context. Better error handling for workspace errors when allocating fetch and delivery processors. (VS issue #1177) Correct an H/2 buffer handling issue introduced in 6.0.8r2. (VS issue #1182) See the change log for a full overview of new features and bug fixes in this and previous versions. The synthbackend.mirror() bug could cause corrupted objects before causing Varnish to crash. When using synthbackend.mirror() together with persisted MSE, these corrupted objects could persist after the crash. If you used synthbackend.mirror() together with persisted MSE before 6.0.8r1, then it is recommended to clear the cache on upgrade to this version, unless you have already done so after upgrading to any previous releases after 6.0.8r1..
https://docs.varnish-software.com/releases/varnish-cache-plus-6.0.8r3/
CC-MAIN-2021-31
refinedweb
202
58.58
Skip to 0 minutes and 1 secondOK. So I'm just going to show you how I've added some doc strings to my class. So this is the item class. As you can see, I've added these things in triple quotes, which come up green on the screen. And I'm just going to add another one to show you an example. It's just simply typing in a description of what each of the methods for that particular class does. I've done that for all of the classes that are here. But these are needed so that we have something that comes up in our documentation. Then I'm going to open the command prompt, and I'm going to change directory to be in the same directory where all of my files are stored. Skip to 0 minutes and 36 secondsSo mine was in one called desktop oop week four and then rpg. I could have done that all in one, but I just did it separately to show you. And then I'm going to type in this particular command, which is the command to create the document. And it does it automatically. So I literally just typed that in. And then as you can see, in my folder I've now got some HTML files. Skip to 0 minutes and 59 secondsAnd if we go and investigate inside one of these-- so this is the one for character-- we can see that we are given some documentation automatically generated so that all of the different methods are there, and our doc strings, which we wrote earlier, are available for us to have a look at. Share your code with other people Sharing your code with other people need not be limited to people you know. It is very easy to share your code online so that anyone, anywhere can use it. This probably sounds scary – after all, this is your first object-oriented program. However, you might be surprised and pleased by other people’s reaction to your code – you might get offers of help, or you might make someone’s day by saving them a lot of time! You can use a website such as GitHub to share your code so that other people can use it, and maybe even suggest changes. Follow this guide for beginners to get your code online. All the code you have downloaded in this course is on GitHub for anyone to see and use. If you are sharing your code, it is also useful to provide some documentation so that people know what classes and methods are available, and how to use them. Python has a built-in feature for automatically creating basic documentation. Once again, you will only be able to use this feature if you are using Python installed on your computer rather than using Trinket. You will need to add docstrings to your code, which will form the basis of the documentation. This is very easy – simply add a line of explanation at the start of each function and enclose it in triple quotation marks, like this: def get_description(self): """Returns a string containing the description of the room""" return self.description Next, open a terminal window (search ‘cmd’ on Windows) and navigate to your rpg folder using the cd command, for example: cd PathToMyCode cd rpg Type in the following command to generate documentation for all files in this folder: On Windows python -m pydoc -w .\ On Mac/Linux python3 -m pydoc -w ./ If you get an error when you try this command, take a look at this resource, and make sure you have added Python to your path. This command should generate HTML files in your directory with the same names as your class files. Open the files to see the documentation for your package. © CC BY-SA 4.0
https://www.futurelearn.com/courses/object-oriented-principles/0/steps/31507
CC-MAIN-2019-13
refinedweb
649
69.62
Description When you run a query with an invalid column that also does a group by on a constructed column, the error message you get back references a missing column for the group by rather than the invalid column. You can reproduce this in pyspark in 3.1.2 with the following code: from pyspark.sql import SparkSession spark = SparkSession.builder.appName("Group By Issue").getOrCreate() data = spark.createDataFrame( [("2021-09-15", 1), ("2021-09-16", 2), ("2021-09-17", 10), ("2021-09-18", 25), ("2021-09-19", 500), ("2021-09-20", 50), ("2021-09-21", 100)], schema=["d", "v"] ) data.createOrReplaceTempView("data") # This is valid spark.sql("select sum(v) as value, date(date_trunc('week', d)) as week from data group by week").show() # This is invalid because val is the wrong variable spark.sql("select sum(val) as value, date(date_trunc('week', d)) as week from data group by week").show() The error message for the second spark.sql line is pyspark.sql.utils.AnalysisException: cannot resolve '`week`' given input columns: [data.d, data.v]; line 1 pos 81; 'Aggregate ['week], 'sum('val) AS value#21, cast(date_trunc(week, cast(d#0 as timestamp), Some(America/New_York)) as date) AS week#22 +- SubqueryAlias data +- LogicalRDD d#0, v#1L, false but the actual problem is that I used the wrong variable name in a different part of the query. Nothing is wrong with week in this case.
https://issues.apache.org/jira/browse/SPARK-36867
CC-MAIN-2022-27
refinedweb
239
59.7
Using FastAI to Analyze Yelp Reviews and Predict User Ratings (Polarity) A Practical Example of Applying the Power of Transfer Learning to Natural Language Processing In this post, I’ll be showing you how you can apply the power of transfer learning to a classification task. The goal is to see how well we can classify a new Yelp review by training an algorithm on past Yelp reviews. FastAI makes this a more approachable problem than it would otherwise be. You can follow along with this GitHub repo code. Why FastAI and What is It? FastAI is a library built by Jeremy Howard, Rachel Thomas and the rest of the good folks at fast.ai. Its current version is built on top of PyTorch — a fast-rising deep learning framework open sourced by Facebook. Artificial Intelligence (AI) continues to make its way into the mass consciousness in 2019. And through applications… It’s very much in the mold of Keras or TensorFlow, but in my opinion, packs a little more punch with it. FastAI abstracts a lot of the lower level detail and control which TensorFlow requires you to fiddle with. And, unlike Keras, allows you to focus on the task at hand rather than mess with so many parameters. This way you focus more on the Science than the actual Art of deep learning. FastAI also allows you to leverage a lot of cutting edge ML techniques adopted from new research. This includes applying the learning-rate finder and leveraging Transfer Learning. What is that by the way? Transfer Learning Ever ride a bicycle? Learning to balance was quite a task, but once you nailed that down learning to balance on a Scooter comes way easier. What about a motorcycle? Though they are different in many ways if you have ever ridden a scooter your learning curve is less steep on a motorcycle. You basically transfer some previous learnings to that new experience. Similarly, Transfer Learning allows you to leverage a pre-trained model or deep learning architecture to speed up learning within a specific problem domain. Typically, a deep learning architecture starts by guessing — randomly — which weights or biases to apply to your parameters. Over time it gets better at guessing as it seeks to minimize its mistakes (or loss). It’s kinda like trying to hit the bull’s eye on a dartboard while adjusting how you throw the dart each time. In this case, using Transfer Learning is like having a coach who gives you tips before you start throwing. In practice, if your task is to distinguish between images of a dog vs a cat you apply an architecture like ResNet-50 (50 layers deep and trained on a million images from the ImageNet database). Having been trained on so many pictures, ResNet-50 makes the early layers of your neural network pretty good at detecting basic features like edges and shapes. While your final layers can focus on your key domain of distinguishing a dog from a cat. Similarly, in classifying reviews, it helps to have a pre-trained model which understands some of the semantics of language beyond our training data to speed up training and increase accuracy. The WikiText language modeling dataset is a collection of over 100 million tokens extracted from the set of verified Good and Featured articles on Wikipedia …Compared to the preprocessed version of Penn Treebank (PTB), WikiText-2 is over 2 times larger and WikiText-103 is over 110 times larger— Stephen Merity Just like ResNet, WikiText gives us the transfer learning edge we need for our NLP challenge. Mo’ data, Mo’ better. Our Problem Domain So, what does our data look like and what exactly are we looking to accomplish? Our dataset consists of Yelp reviews divided up into negative and positive polarities. Per the readme.txt. As a supervised learning task, the reviews will serve as the input and while the polarities we’re looking to predict will serve as the outcome. During training, the polarities will be our labeled data (the bull’s eye in this case) by which we build a fine-tuned model on which to apply to a brand new user review. As you can see below, FastAI has a collection of datasets including the Yelp reviews for NLP related problems. You can get a copy of this data by going here. If using this dataset for research, it is important to cite the authors of the original paper. Much thanks to them for providing easy access to such a useful dataset. Xiang Zhang, Junbo Zhao, Yann LeCun. Character-level Convolutional Networks for Text Classification. Advances in Neural Information Processing Systems 28 (NIPS 2015). Once you download this dataset, you have a variety of options on how or what tool you use to perform this analysis. You can use a Python Notebook like Jupyter or a development editor like PyCharm or Microsoft VisualCode. Due to the size of the dataset, I chose to run this on GCP using JupyterLab. command line. I ran the command below to fetch the yelp data !wget The ‘!’ before wget allows me to run the operation as I would on the command line. Now, I unpack the .tgz file to take a peek inside the data. I run this command to do that !tar -xvzf yelp_review_polarity_csv.tgz And, this is what we get. As you can see there’s training data and test data. Next, we import the fastAI libraries and dependencies and set a path to the folder holding our files. The path makes for easier reference down the line. from fastai import * from fastai.text import * from fastai.core import * path = Path('yelp_review_polarity_csv') Now, we can use the Python package Pandas to examine the dataset. Below it’s given the alias pd. train_csv = path/'train.csv' train = pd.read_csv(train_csv, header=None) train.head() We use the read_csv method to create a dataFrame which we call train. The head() method gives a preview of the first five records in the dataFrame. The first column (0) shows us the polarity. The 2nd column is the actual review. This is neat, but let’s take a closer look at one of the reviews. Let’s pull the second record. train.iloc[0][1] Oops! Two stars for Dr. Goldberg. You can try following similar steps for the test data. valid_csv = path/'test.csv' valid = pd.read_csv(valid_csv, header=None) valid.head() We can also confirm how many classes we have for the labels using valid[0].unique(). We expect just a polarity score of 1 (for -ve) and 2 for (+ve). Alright, we’ve got our training and test datasets loaded. As far as we know, the data is clean and each review has a polarity and vice versa. Starting with a DataBunch We need a way to pass our dataset into our Neural Network. We also want to load them very efficiently maybe in batches. That’s where a DataBunch object comes in handy. Neural network computations involve a lot of number crunching. Yet, our data is mainly text. So, we need a way to Numericalize the words. We also need a way to break down the body of text into individual words as it is the smallest unit of meaningful information. Lastly, to speed up our learning we also want to prioritize which words are the most useful. Accomplishing this involves a process called Tokenization. I did say that fastAI packs a punch right? A DataBunch object allows us to accomplish all this in one shot. data_lm = TextLMDataBunch.from_csv(path, 'test.csv') data_clas = TextClasDataBunch.from_csv(path, 'test.csv', vocab=data_lm.train_ds.vocab) The output of the above two steps is a language model and classifier. One dataBunch for each. Now we can take a peek into what the output looks like data_lm.show_batch() Special tokens are used for words that appear rarely in the corpus. You can think of these as unknown words which are the tokens starting with ‘xx’. We can also view this for the classifier. We can actually take a closer look at the tokens. data_clas.vocab.itos[:10] Wiki Data for Transfer Learning Now is where we start to get to business. But, before we create a language model we need to pull in the pre-trained Wiki data. We create a folder to store the model, then we download and store the models. model_path = path/'models' model_path.mkdir(exist_ok=True) url = '' download_url(f'{url}lstm_wt103.pth', model_path/'lstm_wt103.pth') download_url(f'{url}itos_wt103.pkl', model_path/'itos_wt103.pkl') Creating a Language Model Now we need to create a language model. Why do we need this and what exactly is a language model? With a language model, we start getting into the meaning of a text. The semantics of how words are structured and organized also start to come together. Using the wiki data allows us to speed up this process. learn = language_model_learner(data_lm, AWD_LSTM, pretrained_fnames=['lstm_wt103', 'itos_wt103'], drop_mult=0.5) Proof that we have a good language model comes in being able to predict the next sequence of words based on a given set of words. The command below provides 5 words and tries to predict the next 50. learn.predict('This was such a great ', 50, temperature=1.1, min_p=0.001) Here’s what the model gives without any tuning. This is not a coherent sentence, but it’s pretty amazing that we see the use of commas, periods and some reasonable sentence structures. Fine Tuning the Model We now need to fine-tune this model and this involves some training. However, historically picking a learning rate has been sort of an art. FastAI makes this very easy by leveraging the concept of cyclical learning rates specified in this 2015 paper. In this approach, the learning rate is increased until the loss stops decreasing. So, we run these two commands. learn.lr_find() learn.recorder.plot() Here’s what we get with the loss plotted against the learning rate. We can see that the loss stops decreasing around 1e-1, so we’ll start one step before then. Out first result is not all that great and needs some fine-tuning. 28.6% accuracy means it guesses the next predicted word in a sequence correctly more than 1 in 4 times. The next step is to unfreeze and retrain with a lower learning rate. The initial training had a ‘frozen’ layer which was not being trained or updated. This unfreeze() comman unfreezes all layers helping us further fine-tune. learn.unfreeze() learn.fit_one_cycle(10, 1e-3,moms=(0.8,0.7)) That’s a slight improvement. It’s only about a 3rd of the way training and it’s guessing correctly a 3rd of the time. After 10 iterations it hovers close to 37% accuracy We can save this fine-tuned model. This is good enough for us to proceed. We don’t need it to be super duper at predicting the next word. learn.save_encoder('ft_enc') For the fun of it let’s see how well the model predicts the next 50 words, given just 3 words. How about predicting the next 25 words given the first 4 words? Nice. Remember it’s making up the rest of the sentence by being provided some seed words to start with. Getting into Training and Classification Remember our aim here is to be able to classify a review with a +ve or -ve polarity. So we build a classifier using our trained model. First, instead of language model learner, we instantiate the text classifier learner. learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5) You can read up more on AWD_LSTM. It essentially is an architecture that helps with regularizing and optimizing language models. Then, we load the trained model and train the classifier. learn.load_encoder('ft_enc') learn.fit_one_cycle(1, 1e-2) After one run and under 4 mins of training, we are seeing an accuracy close to 92% accuracy in predicting the polarity of a review. Nice, but far from great. The state of the art at the time of the 2015 paper resulted in an error rate of 4.36%. This means an accuracy of 95.64%. Can we beat that? We can try to freeze all the layers of the model except for the last 2. Let’s try that. learn.freeze_to(-2)learn.fit_one_cycle(1, slice(1e-2/(2.6**4),1e-2), moms=(0.8,0.7)) 94.7% is getting closer to the state of the art. All in less than 40mins. Also, the validation loss is less than the training loss, means we are not overfitting. You may have noticed the 2.6 to the fourth divided into the learning rate. Without boring you with details, all that has to do with discriminative learning rates. Essentially, as we progress layer by layer by how much do we decrease the learning rate. Jeremy Howard figured out that for NLP RNNs that’s the magical number. If you really want to dig deeper I suggest you take the Practical Deep Learning for Coders course FastAI offers. In our case, you can keep going if you want, unfreezing one layer at a time. My notebook started having some memory issues, so I’ll stop here. Save the model so you don’t have to retrain again and load back the tuned model to proceed. learn.save('second') learn.load('second') Prediction Time — Testing Our Model Our text_classifier_learner has a predict function that now allows us to pass in a review for classification. According to the documentation, the output generates a tuple. The first two elements of the tuple are, respectively, the predicted class and label. Label here is essentially an internal representation of each class, since class name is a string and cannot be used in computation. You’ll see what this looks like in a second. We can check what each label corresponds to by running learn.data.classes and as you can see there are two classes. So, at index zero is 1 which implies -ve polarity label. At index one is 2 which implies +ve polarity label. Now, let’s see if we can predict the outcome of a made up review. Let’s start with something really simple and obvious. Remember, an outcome of label 1 (index 0) is -ve polarity and 2 (index 1) is +ve polarity. The second element in the tuple is tensor(0). This is a reference to the class index which is 1, meaning it classified this review as having -ve polarity. The documentation clarified that The last element in the tuple is the predicted probabilities. So, there’s a 56.7% chance it’s -ve polarity and 43.3% it’s +ve. The former wins out. Let’s try something more upbeat. In this case, the second element in the tuple is tensor(1). This is a reference to the class index which is 2, meaning it classified this review as having +ve polarity. 99.8% probability feels pretty clear. Right on the money! What about a real Yelp review? tensor(0), negative polarity. Got it right with a 62.8% probability. Another negative polarity well in line with a rating of 1. Probability, in this case, is really high at 96.8%. That’s 2 for 2. Let’s look for something which should have a positive polarity. 3 for 3. 99.8% probability this review has a +ve polarity. Aligns well with a rating of 4 stars. Summary We covered a lot of ground in this post. I started off by describing what transfer learning is and how it helps tremendously especially around Natural Language Processing tasks. For our use case, WikiText gave us the boost we needed. You should walk away with a good understanding of how to fetch this data, build a language model, train a classifier and predict polarity on any given yelp review. You can take this further by - Trying this on a completely different corpus, beyond just restaurant reviews - Exploring how you can predict exact ratings and not just polarity - Even better deploying the model as an application to predict a set of reviews passed in as input Props to Wang Shuyi whose post on a similar topic got me inspired. There’s a lot to learn in this space and I hope this has similarly inspired you. If you want to learn more about how FastAI can help you solve real problems check out their Machine Learning courses. Best wishes!
https://medium.com/datadriveninvestor/using-fastai-to-analyze-yelp-reviews-and-predict-user-ratings-polarity-4e4e89df358e?source=rss-c4c714a5ce60------2
CC-MAIN-2019-22
refinedweb
2,760
66.64
Apache, and interceptors via both XML and Java annotations. You’ll get an introduction to most of the Struts 2.1 custom tags, and also learn how they can assist in rapid application prototyping and development. From there, you’ll make your way into Struts 2.1′s strong support for form validation and type conversion, which allows you to treat your form values as domain objects without cluttering your code. A look at Struts 2.1′s interceptors is the final piece of the Struts 2.1 puzzle, which allows. What Java Everybody knows the basics of documenting Java, so we won’t go into much detail. We’ll talk a bit about ways of writing code whose intention is clear, mention some Javadoc tricks we can use, and highlight some tools that can help keep our code clean. Clean code is one of the most important ways we can document our application. Anything we can do to increase readability will reduce confusion later (including our own). Self-documenting code We’ve all heard the myth of self-documenting code. In theory, code is always clear enough to be easily understood. In reality, this isn’t always the case. However, we should try to write code that is as self-documenting as possible. Keeping non-code artifacts in sync with the actual code is difficult. The only artifact that survives a project is the executable, which is created from code, not comments. This is one of the reasons for writing self-documenting code. (Well, annotations, XDoclet, and so on, make that somewhat less true. You know what I mean.) There are little things we can do throughout our code to make our code read as much like our intent as possible and make extraneous comments just that: extraneous. Document why, not what Over-commenting wastes everybody’s time. Time is wasted in writing a comment, reading it, keeping that comment in sync with the code, and, most importantly, a lot of time is wasted when a comment is not accurate. Ever seen this? a += 1; // increment a This is the most useless comment in the world. Firstly, it’s really obvious we’re incrementing something, regardless of what that something is. If the person reading our code doesn’t know what += is, then we have more serious problems than them not knowing that we’re incrementing, say, an array index. Secondly, if a is an array index, we should probably use either a more common array index or make it obvious that it’s an array index. Using i and j is common for array indices, while idx or index is less common. It may make sense to be very explicit in variable naming under some circumstances. Generally, it’s nice to avoid names such as indexOfOuterArrayOfFoobars. However, with a large loop body it might make sense to use something such as num or currentIndex, depending on the circumstances. With Java 1.5 and its support for collection iteration, it’s often possible to do away with the index altogether, but not always. Make your code read like the problem Buzzphrases like Domain Specific Languages (DSLs) and Fluent Interfaces are often heard when discussing how to make our code look like our problem. We don’t necessarily hear about them as much in the Java world because other languages support their creation in more “literate” ways. The recent interest in Ruby, Groovy, Scala, and other dynamic languages have brought the concept back into the mainstream. A DSL, in essence, is a computer language targeted at a very specific problem. Java is an example of a general-purpose language. YACC and regular expressions are examples of DSLs that are targeted at creating parsers and recognizing strings of interest respectively. DSLs may be external, where the implementing language processes the DSL appropriately, as well as internal, where the DSL is written in the implementing language itself. An internal DSL can also be thought of as an API or library, but one that reads more like a “little language”. Fluent interfaces are slightly more difficult to define, but can be thought of as an internal DSL that “fl ows” when read aloud. This is a very informal definition, but will work for our purposes. Java can actually be downright hostile to some common DSL and fl uent techniques for various reasons, including the expectations of the JavaBean specification. However, it’s still possible to use some of the techniques to good effect. One typical practice of fl uent API techniques is simply returning the object instance in object methods. For example, following the JavaBean specification, an object will have a setter for the object’s properties. For example, a User class might include the following: public class User { private String fname; private String lname; public void setFname(String fname) { this.fname = fname; } public void setLname(String lname) { this.lname = lname; } } Using the class is as simple as we’d expect it to be: User u = new User(); u.setFname("James"); u.setLname("Gosling"); Naturally, we might also supply a constructor that accepts the same parameters. However, it’s easy to think of a class that has many properties making a full constructor impractical. It also seems like the code is a bit wordy, but we’re used to this in Java. Another way of creating the same functionality is to include setter methods that return the current instance. If we want to maintain JavaBean compatibility, and there are reasons to do so, we would still need to include normal setters, but can still include “fl uent” setters as shown here: public User fname(String fname) { this.fname = fname; return this; } public User lname(String lname) { this.lname = lname; return this; } This creates (what some people believe is) more readable code. It’s certainly shorter: User u = new User().fname("James").lname("Gosling"); There is one potential “gotcha” with this technique. Moving initialization into methods has the potential to create an object in an invalid state. Depending on the object this may not always be a usable solution for object initialization. Users of Hibernate will recognize the “fl uent” style, where method chaining is used to create criteria. Joshua Flanagan wrote a fl uent regular expression interface, turning regular expressions (already a domain-specific language) into a series of chained method calls: Regex socialSecurityNumberCheck = new Regex(Pattern.With.AtBeginning .Digit.Repeat.Exactly(3) .Literal("-").Repeat.Optional .Digit.Repeat.Exactly(2) .Literal("-").Repeat.Optional .Digit.Repeat.Exactly(4) .AtEnd); Whether or not this particular usage is an improvement is debatable, but it’s certainly easier to read for the non-regex folks. Ultimately, the use of fl uent interfaces can increase readability (by quite a bit in most cases), may introduce some extra work (or completely duplicate work, like in the case of setters, but code generation and/or IDE support can help mitigate that), and may occasionally be more verbose (but with the benefit of enhanced clarity and IDE completion support). fl uent programming, rather than this specific example. Contract-oriented programming Aspect-oriented programming (AOP) is a way of encapsulating cross-cutting functionality outside of the mainline code. That’s a mouthful, but essentially it means is that we can remove common code that is found across our application and consolidate it in one place. The canonical examples are logging and transactions, but AOP can be used in other ways as well. Design by Contract (DbC) is a software methodology that states our interfaces should define and enforce precise specifications regarding operation. "Design by Contract" is a registered trademark of Interactive Software Engineering Inc. Other terms include Programming by Contract (PbC), or an object, whatever pushing means. What happens if we attempt to push a null? Let’s assume that for this implementation, we don’t want to allow pushing a null onto the stack. /** * Pushes non-null objects on to stack. */ public void push(final Object o) { if (o == null) return; stack.add(o); } Once again, this is simple enough. We’ll add the comment to the Javadocs stating that null objects will not be pushed (and that the call will fail/return silently). This will become the “contract” of the push method—captured in code and documented in Javadocs. The contract is specified twice—once in the code (the ultimate arbiter) and again in the documentation. However, the user of the class does not have proof that the underlying implementation actually honors that contract. There’s no guarantee that if we pass in a null, it will return silently without pushing anything. The implied contract can change. We might decide to allow pushing nulls. We might throw an IllegalArgumentException or a NullPointerException on a null argument. We’re not required to add a throws clause to the method declaration when throwing runtime exceptions. This means further information may be lost in both the code and the documentation. As hinted, Eiffel has language-level support for COP with the require/do/ensure/ end construct. It goes beyond the simple null check in the above code. It actively encourages detailed pre- and post-condition contracts. An implementation’s push() method might check the remaining stack capacity before pushing. It might throw exceptions for specific conditions. In pseudo-Eiffel, we’d represent the push() method in the following way: push (o: Object) require o /= null do -- push end A stack also has an implied contract. We assume (sometimes naively) that once we call the push method, the stack will contain whatever we pushed. The size of the stack will have increased by one, or whatever other conditions our stack implementation requires. One aim of COP is to formalize the nature of contracts. Languages such as Eiffel have one solution to that problem, and having it built-in at the language level provides a consistent means of expressing contracts. Java, of course, doesn’t have built-in contracts. However, it does contain a mechanism that can be used to get some of the benefits for a conceptually-simple price. The mechanism is not as complete, or as integrated, as Eiffel’s version. However, it removes contract enforcement from the mainline code, and provides a way for both sides of the software to specify, accept, and document the contracts themselves. Removing the contract information from the mainline code keeps the implementation clean and makes the implementation code easier to understand. Having programmatic access to the contract means that the contract could be documented automatically rather than having to maintain a disconnected chunk of Javadoc. SpringContracts SpringContracts is a beta-level Java COP implementation based on Spring’s AOP facilities, using annotations to state pre- and post-contract conditions. It formalizes the nature of a contract, which can ease development. Let’s consider our VowelDecider that was developed through TDD. We can also use COP to express its contract (particularly the entry condition). This is a method that doesn’t alter state, so post conditions don’t apply here. Our implementation of VowelDecider ended up looking (more or less) like this: public boolean decide(final Object o) throws Exception { if ((o == null) || (!(o instanceof String))) { throw new IllegalArgumentException( "Argument must be a non-null String."); } String s = (String) o; return s.matches(".*[aeiouy]+.*"); } Once we remove the original contract enforcement code, which was mixed with the mainline code, our SpringContracts @Precondition annotation looks like the following: @Precondition(condition="arg1 != null && arg1.class.name == 'java. lang.String'", message="Argument must be a non-null String") public boolean decide(Object o) throws Exception { String s = (String) o; return s.matches(".*[aeiouy]+.*"); } The pre-condition is that the argument must not be null and must be (precisely) a string. (Because of SpringContracts’ Expression Language, we can’t just say instanceof String in case we want to allow string subclasses.) We can unit-test this class in the same way we tested the TDD version. In fact, we can copy the tests directly. Running them should trigger test failures on the null and non-string argument tests, as we originally expected an IllegalArgumentException. We’ll now get a contract violation exception from SpringContracts. One difference here is that we need to initialize the Spring context in our test. One way to do this is with JUnit’s @BeforeClass annotation, along with a method that loads the Spring configuration file from the classpath and instantiates the decider as a Spring bean. Our class setup now looks like this: @BeforeClass public static void setup() { appContext = new ClassPathXmlApplicationContext( "/com/packt/s2wad/applicationContext.xml"); decider = (VowelDecider) appContext.getBean("vowelDecider"); } We also need to configure SpringContracts in our Spring configuration file. Those unfamiliar with Spring’s (or AspectJ’s) AOP will be a bit confused. However, in the end, it’s reasonably straightforward, with a potential “gotcha” regarding how Spring does proxying. <aop:aspectj-autoproxy <aop:config> <aop:aspect <aop:pointcut <aop:around </aop:aspect> </aop:config> <bean id="contractValidationAspect" class="org.springcontracts.dbc.interceptor. ContractValidationInterceptor"/> <bean id="vowelDecider" class="com.packt.s2wad.example.CopVowelDecider" /> If most of this seems like a mystery, that’s fine. The SpringContracts documentation goes into it a bit more and the Spring documentation contains a wealth of information regarding how AOP works in Spring. The main difference between this and the simplest AOP setup is that our autoproxy target must be a class, which requires CGLib. This could also potentially affect operation. The only other modification is to change the exception we’re expecting to SpringContract’s ContractViolationCollectionException, and our test starts passing. These pre- and post-condition annotations use the @Documented meta-annotation, so the SpringContracts COP annotations will appear in the Javadocs. It would also be possible to use various other means to extract and document contract information. Getting into details This mechanism, or its implementation, may not be a good fit for every situation. Runtime performance is a potential issue. As it’s just some Spring magic, it can be turned off by a simple configuration change. However, if we do, we’ll lose the value of the on-all-the-time contract management. On the other hand, under certain circumstances, it may be enough to say that once the contracts are consistently honored under all of the test conditions, the system is correct enough to run without them. This view holds the contracts more as an acceptance test, rather than as run-time checking. Indeed, there is an overlap between COP and unit testing as the way to keep code honest. As unit tests aren’t run all the time, it may be reasonable to use COP as a temporary runtime unit test or acceptance
http://www.javabeat.net/documenting-our-application/
CC-MAIN-2013-48
refinedweb
2,440
55.54
void str2et_c ( ConstSpiceChar * str, SpiceDouble * et ) Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. TIME TIME VARIABLE I/O DESCRIPTION -------- --- -------------------------------------------------- str I A string representing an epoch. et O The equivalent value in seconds past J2000, TDB. str is a string representing an epoch. Virtually all common calendar representations are allowed. You may specify a time string belonging to any of the systems TDB, TDT, UTC. Moreover, you may specify a time string relative to a specific UTC based time zone. The rules used in the parsing of `str' are spelled out in great detail in the CSPICE routine tpartv_. The basics are given in the Particulars section below. et is the double precision number of TDB seconds past the J2000 epoch that corresponds to the input `str'. None. 1) The error SPICE(UNPARSEDTIME) is signaled if the string cannot be recognized as a legitimate time string. 2) The error SPICE(TIMECONFLICT) is signaled if more than one time system is specified as part of the time string. 3) The error SPICE(BADTIMESTRING) is signaled if any component of the time string is outside the normal range of usage. For example, the day January 35 is outside the normal range of days in January. The checks applied are spelled out in the routine tcheck_. 4) The error SPICE(EMPTYSTRING) is signaled if the input string does not contain at least one character, since the input string cannot be converted to a Fortran-style string in this case. 5) The error SPICE(NULLPOINTER) is signaled if the input string pointer is null. This routine computes the ephemeris epoch corresponding to an input string. The ephemeris epoch is represented as seconds past the J2000 epoch in the time system known as Barycentric Dynamical Time (TDB). This time system is also referred to as Ephemeris Time (ET) throughout the SPICE Toolkit. The variety of ways people have developed for representing times is enormous. It is unlikely that any single subroutine can accommodate the wide variety of custom time formats that have arisen in various computing contexts. However, we believe that this routine will correctly interpret most time formats used throughout the planetary science community. For example this routine supports ISO time formats and UNIX `date` output formats. One obvious omission from the strings recognized by this routine are strings of the form 93234.1829 or 1993234.1829 Some readers may recognize this as the epoch that is 0.1829 days past the beginning of the 234'th day of 1993. However, many other readers may regard this interpretation as a bit obscure. Below we outline some of the rules used in the interpretation of strings. A more complete discussion of the interpretation of strings is given in the routine tpartv_. Default Behavior ---------------- Consider the string 1988 June 13, 3:29:48 There is nothing in this string to indicate what time system the date and time belong to. Moreover, there is nothing to indicate whether the time is based on a 24-hour clock or twelve hour clock.). Labels ------ If you add more information to the string, str2et_c can make a more informed interpretation of the time string. For example: 1988 June 13, 3:29:48 P.M. is still regarded as a UTC epoch. However, with the addition of the "P.M." label it is now interpreted as the same epoch as the unlabeled epoch 1988 June 13, 15:29:48. Similarly 1988 June 13, 12:29:48 A.M. is interpreted as 1988 June 13, 00:29:48 For the record: is interpreted as an epoch in the Pacific Standard Time system. This is equivalent to 1988 June 13, 07:29:48 UTC The following U.S. time zones are recognized. ) In addition any other time zone may be specified by representing its offset from UTC. This notation. For the Record: Leapseconds occur at the same time in all time zones. In other words, the seconds component of a time string is the same for any time zone as is the seconds component of UTC. Thus. Times in TDB are written as 1988 June 13, 12:29:48 TDB TDT times are written as: 1988 June 13, 12:29:48 TDT Finally, you may explicitly state that the time system is UTC 1988 June 13, 12:29:48 UTC. Abbreviating Years ------------------ Although it can lead to confusion, many people are in the habit of abbreviating years when they write them in dates. For example 99 Jan 13, 12:28:24 Upon seeing such a string, most of us would regard this as being 1999 January 13, 12:28:24 and not January 13 of the year 99. This routine interprets years that are less than 100 as belonging either to the 1900's or 2000's. Years greater than 49 ( 50 - 99 ) are regarded as being an abbreviation with the '19' suppressed (1950 - 1999). Years smaller than 50 ( 00 - 49 ) are regarded as being an abbreviation with the '20' suppressed (2000 - 2049). Note that in general it is usually a good idea to write out the year. Or if you'd like to save some typing abbreviate 1999 as '99. If you need to specify an epoch whose year is less than 1000, we recommend that you specify the era along with the year. For example if you want to specify the year 13 A.D. write it as 13 A.D. Jan 12 When specifying the era it should immediately follow the year. Both the A.D. and B.C. eras are supported. Changing Default Behavior ------------------------- As discussed above, if a string is unlabeled, it is regarded as representing a string in the UTC time system on the Gregorian calendar. In addition abbreviated years are regarded as abbreviations of the years from 1950 to 2049. You may modify these defaults through the routines timdef_c_ and tsetyr_c. You may: Set the calendar to be Gregorian, Julian or a mixture of two via the timdef_c; Set the time system to be UTC, TDB, TDT or any time zone via the routine timdef_c; Set the range of year abbreviations to be any 100 year interval via the routine tsetyr_c. See the routines texpyr_ and timdef_c for details on changing defaults. These alterations affect only the interpretation of unlabeled strings. If an input string is labeled the specification in the label is used. If any component of a date or time is out of range, str2et_c regards the string as erroneous. Below is a list of erroneous strings and why they are regarded as such. 1997 Jan 32 12:29:29 --- there are only 31 days in January '98 Jan 12 13:29:29 A.M. --- Hours must be between 1 and 12 inclusive when A.M. or P.M. is specified. 1997 Feb 29, 12:29:20.0 --- February has only 29 days in 1997. This would be ok if the year was 1996. 1992 Mar 12 12:62:20 --- Minutes must be between 0 and 59 inclusive. 1993 Mar 18 15:29:60.5 --- Seconds is out of range for this date. It would not be out of range for Dec 31 23:59:60.5 or Jun 30 23:59:60.5 because these can be leapseconds (UTC). Specifics On Interpretation of the Input String ----------------------------------------------- The process of examining the string to determine its meaning is called "parsing" the string. The string is parsed by first determining its recognizable substrings (integers, punctuation marks, names of months, names of weekdays, time systems, time zones, etc.) These recognizable substrings are called the tokens of the input string. The meaning of some tokens are immediately determined. For example named months, weekdays, time systems have clear meanings. However, the meanings of numeric components must be deciphered from their magnitudes and location in the string relative to the immediately recognized components of the input string. To determine the meaning of the numeric tokens in the input string, a set of "production rules" and transformations are applied to the full set of tokens in the string. These transformations are repeated until the meaning of every token has been determined, or until further transformations yield no new clues into the meaning of the numeric tokens. 1) Unless the substring "JD" or "jd" is present, the string is assumed to be a calendar format (day-month-year or year and day of year). If the substring JD or jd is present, the string is assumed to represent a Julian date. 2) If the Julian date specifier is not present, any integer greater than 999 is regarded as being a year specification. 3) A dash "-" can represent a minus sign only if it precedes the first digit in the string and the string contains the Julian date specifier (JD). (No negative years, months, days, etc. are allowed). 4) Numeric components of a time string must be separated by a character that is not a digit or decimal point. Only one decimal component is allowed. For example 1994219.12819 is sometimes interpreted as the 219th day of 1994 + 0.12819 days. str2et_c does not support such strings. No exponential components are allowed. For example you can't specify the Julian date of J2000 as 2.451545E6. 5) The single colon (:) when used to separate numeric components of a string is interpreted as separating Hours, Minutes, and Seconds of time. 6) If a double slash (//) or double colon (::) follows a pair of integers, those integers are assumed to represent the year and day of year. 7) A quote followed by an integer less than 100 is regarded as an abbreviated year. For example: '93 would be regarded as the 93rd year of the reference century. See texpyr_ for further discussion of abbreviated years. 8) An integer followed" by "B.C." or "A.D." is regarded as a year in the era associated with that abbreviation. 9) All dates are regarded as belonging to the extended Gregorian Calendar (the Gregorian calendar is the calendar currently used by western society). See the routine timedef_ to modify this behavior. 10) If the ISO date-time separator (T) is present in the string ISO allowed token patterns are examined for a match with the current token list. If no match is found the search is abandoned and appropriate diagnostic messages are generated. 11) If two delimiters are found in succession in the time string, the time string is diagnosed as an erroneous string. (Delimiters are comma, white space, dash, slash, period, or day of year mark. The day of year mark is a pair of forward slashes or a pair of colons.) Note the delimiters do not have to be the same. The pair of characters ",-" counts as two successive delimiters. 12) White space and commas serve only to delimit tokens in the input string. They do not affect the meaning of any of the tokens. 13) If an integer is greater than 1000 (and the "JD" label is not present, the integer is regarded as a year. 14) When the size of the integer components does not clearly specify a year the following patterns are assumed Calendar Format Year Month Day Month Day Year Year Day Month where Month is the name of a month, not its numeric value. When integer components are separated by slashes (/) as in 3/4/5. Month, Day, Year is assumed (2005 March 4) Day of Year Format If a day of year marker (// or ::) is present, the pattern I-I// or I-I:: (where I stands for an integer) is interpreted as Year Day-of-Year. However, I-I/ is regarded as ambiguous. Below is a sampling of some of the time formats that are acceptable as inputs to str2et_c. A complete discussion of permissible formats is given in the CSPICE routine tpartv_ as well as the reference document time.req located in the "doc" directory of the Toolkit. Calendar Formats. Day of Year Formatsulian Date Strings jd 28272.291 Julian Date 28272.291 2451515.2981 (JD) Julian Date 2451515.2981 2451515.2981 JD Julian Date 2451515.2981 Abbreviations Used in Tables na --- Not Applicable Mon --- Month DOY --- Day of Year DOM --- Day of Month Wkday --- Weekday Hr --- Hour Min --- Minutes Sec --- Seconds * The default interpretation of a year that has been abbreviated with a leading quote as in 'xy (such as '92) is to treat the year as 19xy if xy > 68 and to treat it is 20xy otherwise. Thus '69 is interpreted as 1969 and '68 is treated as 2068. However, you may change the "split point" and centuries through use of the CSPICE routine tsetyr_c. See that routine for a discussion of how you may reset the split point. ** All epochs are regarded as belonging to the Gregorian calendar. We formally extend the Gregorian calendar backward and forward in time for all epochs. + When a day of year format or calendar format string is input and neither of the integer components of the date is greater than 1000, the first integer is regarded as being the year. Suppose you would like to determine whether your favorite time representation is supported by str2et_c. The small program below gives you a simple way to experiment with str2et_c. (Note that erroneous inputs will be flagged by signaling an error.) To build and run this program you need to: 1. copy it to a file, 2. un-comment the obvious lines of code, and replace the default string with your test string 3. compile it, 4. link the resulting object file with CSPICE, 5. and place the leapseconds kernel in your current directory. #include <stdio.h> #include "SpiceUsr.h" char *date = "Thu Mar 20 12:53:29 PST 1997"; char *leap = "naif0007.tls"; main () { furnsh_c ( leap ); str2et_c ( date, &et ); printf ( "%f\n", et ); } C.H. Acton (JPL) N.J. Bachman (JPL) W.L. Taber (JPL) -CSPICE Version 1.1.5, 02-NOV-2009 (CHA) A few minor grammar fixes in the header. -CSPICE Version 1.1.4, 16-JAN-2008 (EDW) Corrected typos in header titles: Detailed Input to Detailed_Input Detailed Output to Detailed_Output -CSPICE Version 1.1.3, 12-NOV-2006 (EDW) Added Parameters section header. -CSPICE Version 1.1.2, 29-JUL-2003 (CHA) (NJB) Various minor header corrections were made. -CSPICE Version 1.1.1, 10-FEB-2002 (NJB) Corrected typo in header. -CSPICE Version 1.1.0, 08-FEB-1998 (NJB) Re-implemented routine without dynamically allocated, temporary strings. Exceptions section of header was updated. -CSPICE Version 1.0.0, 25-OCT-1997 (EDW) Convert a string to TDB seconds past the J2000 epoch Wed Apr 5 17:54:45 2017
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/str2et_c.html
CC-MAIN-2018-47
refinedweb
2,453
65.52
Search results Create the page "Editor Scripts" on this wiki! Page title matches - {{Scripts Tabbed Navigation}} == Editor Scripts ==16 KB (2,352 words) - 22:39, 5 November 2018 Page text matches - * [[Scripts]] - Everything from general purpose effects to debugging. * [[Wizards]] - Scripts to extend the Unity editor.6 KB (826 words) - 11:45, 18 July 2018 - == My scripts seem to be frame rate dependent! == == My Editor script won't compile! ==4 KB (592 words) - 20:52, 10 January 2012 - 1.) MonoDevelop/Visual Studio (or whatever text editor you are using) will crash, because auto-completion will try to load ''all'' ...ehaviour is what gives us access to pretty much everything you need to get scripts to work on objects in Unity. When you ''inherit'' from a class, you can see14 KB (2,338 words) - 20:12, 12 April 2016 - [[Category: Debugging Scripts]] [[Category: Heads Up Display Scripts]]13 KB (1,602 words) - 03:38, 1 December 2015 - When you're working in your text editor, it can be a nuisance to have to manually switch back to Unity to test your ...r supports (probably 'script'), and place it in a location where your text editor will be able to find it.1,009 B (158 words) - 20:57, 10 January 2012 - * [[Array Editing]] - Undocumented features that make editing arrays in the editor less painful. * [[Quick Editor - Generate Hashes]] - An example on how to create a quick editor script to generate MD5 Hashes on a list of game objects4 KB (603 words) - 17:24, 7 May 2019 - ''These scripts go in the Assets/Editor folder of your project.'' *[[Deselect]] - Sets the current selection in the editor to nothing. Deselects all.4 KB (623 words) - 22:54, 31 January 2014 - ...you if the performance is being slowed down by the objects in the scene or scripts attached to obejcts in the scene. If the Scene View is slugish, you might w ...phics memory. There is no need to edit the size of textures in your image editor. You can edit the size that Unity imports the image on in each image's Set11 KB (1,810 words) - 22:19, 12 April 2013 - If you need your editor scripts to have the same functionality as “Assets->Show In Explorer” check out ...ser closes the window, where as OnDisable is called after unity recompiles scripts. Think of the OnDestroy method as a close event for the window but the wind21 KB (2,794 words) - 05:23, 17 January 2016 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]2 KB (276 words) - 20:45, 10 January 2012 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]1 KB (184 words) - 14:17, 1 June 2012 - After you downloaded the script copy it to the 'scripts' folder of Blender. ...stem it is here: /Applications/Blender/blender.app/Contents/MacOS/.blender/scripts8 KB (1,344 words) - 19:26, 19 October 2009 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]8 KB (877 words) - 10:15, 28 April 2017 - This Editor script helps to delete a special type of components which are attached to t You must place the script in a folder named '''Editor''' in your projects Assets folder for it to work properly.1 KB (142 words) - 20:45, 10 January 2012 - ...he need to break the link to the original file due to cleanup in the Unity Editor. .../video/how-to-add-scripts-to-pie-menus-in-modo-301-252586/view/ How to add scripts to pie menus in modo 301] (which also works in modo 401 and has some nice t5 KB (787 words) - 11:23, 24 April 2013 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]2 KB (241 words) - 10:20, 6 July 2014 - * [[Event Execution Order]] - The order in which events in your scripts are called by Unity. ... Detailed Overview]] - Useful for people who want to write more complex in-editor tools.2 KB (232 words) - 18:15, 7 February 2019 - ...xplain all of the code yet, we just want to get familiar with Unity and C# scripts first. So go ahead and create a new Unity project named Tutorials or whatev ...ile and you should notice the icon disappears. This is Unity building your scripts in the background when you save a code file. It compiles and then any error21 KB (3,491 words) - 23:16, 1 December 2012 - OK, so you can only attach scripts in Unity that inherit from MonoBehaviour, got it? For now we'll leave it of ... don't need a constructor, as you'll want to set the initial values in the editor. But you can place a default value if none is supplied by initializing vari18 KB (2,805 words) - 20:45, 10 January 2012 - public age : int; // other scripts which have a reference to this object (e.g. if they're attached to the same private favoriteColor : Color; // private members are NOT visible to other scripts, even if they have a reference to this object19 KB (2,861 words) - 21:20, 21 November 2018 - [[Category: Debugging Scripts]] [[Category: Heads Up Display Scripts]]10 KB (971 words) - 21:34, 15 March 2014 - First, draw an enemy of some kind in your image editor of choice. The size of the graphic should be a power of two and reasonably ...k on the root of the enemy object, and go to the Component menu and select Scripts -> Raycast Check, or else find the RaycastCheck script and drag it onto the8 KB (1,381 words) - 19:30, 19 October 2009 - == Adding the object to the level editor == ...ents a collection of 8 different tiles that are automatically drawn by the editor, depending on the tile's neighbors. Change the Size element to 5, and drag3 KB (477 words) - 19:30, 19 October 2009 - ...tor. They won't actually do anything right now, since they don't have any scripts yet, but they do have colliders, so if you run into them, your ship will ex ...reated to Enemy. Double-click on the Enemy script to open it in your text editor.12 KB (1,967 words) - 20:52, 10 January 2012 - [[Category: Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. Also it must be14 KB (1,504 words) - 04:32, 17 August 2014 - Place the script in the Editor folder and run the wizard from GameObject/Lightmap Wizard. [[Category:Editor Scripts]]15 KB (1,747 words) - 20:45, 10 January 2012 - Place the script in the Editor folder and run the wizard from GameObject/Lightmap Wizard (Pixel). [[Category:Editor Scripts]]18 KB (2,120 words) - 20:45, 10 January 2012 - [[Category: Editor]] ...toggling between those cameras is a bit tedious. This is where this set of scripts come in handy. You can look at the rendered image of any selected camera th3 KB (285 words) - 20:52, 10 January 2012 - Place it inside the Editor folder. Then, you can click "Custom/Stats/Count Lines" public class CountLines: Editor{5 KB (502 words) - 19:28, 27 October 2012 - If you need to rename a behaviour (non-behaviour scripts don't matter), make sure to do it in Unity! If you rename it in VS, Unity w ...lorer, include the new renamed script, and finally rename the class in the editor (and enjoy some sweet refactoring :). It's a tad tedious, but once you get10 KB (1,678 words) - 20:47, 10 January 2012 - [[Category:Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly.3 KB (468 words) - 20:52, 10 January 2012 - ... is built, they are merged with the compiled Mono code from your project's scripts. This means that you can use them with a Unity Indie licence as well as wit *[ Behave] - Via an editor extension and a runtime library, this project implements behaviour trees in5 KB (802 words) - 13:50, 6 February 2015 - Here is a unityPackage that contains two Editor scripts, one that "merge" two OBJ meshes and transfers the UVs from one to the othe1,017 B (175 words) - 21:07, 5 October 2008 - [[Category:Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly.5 KB (680 words) - 22:29, 2 September 2013 - Grome: ...dan's excellent Unity Terrain toolkit, which plugs straight into the unity editor, and can quickly produce some very believable results.54 KB (8,866 words) - 23:14, 14 October 2012 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. // import settings of a single texture. Put this into Assets/Editor and once compiled by Unity you find17 KB (1,450 words) - 20:45, 10 January 2012 - [[Category: Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. When this is d5 KB (734 words) - 19:08, 24 June 2013 - ! UnityScript Editor ...res], [ UnityScript Editor Product Page]10 KB (1,352 words) - 17:05, 25 April 2014 - [[Category:Editor Scripts]] ...o this, you're basically stuck unless you export the heightmap to an image editor and brighten it. This will effectively raise the terrain, but can be probl5 KB (537 words) - 19:25, 15 January 2013 - * finding missing scripts in your scene (search the dump for "(null)") For a more full-featured version of this script, including a custom editor window for better IDE integration,3 KB (333 words) - 20:45, 10 January 2012 - ...e compiler for JavaScript, however, your scripts get compiled by the Unity editor as soon as you save them.6 KB (885 words) - 21:29, 21 November 2018 - 4) Get free PSPad Editor () or any other which can convert files to UTF-16 LE c 5) Open in PSPad Editor "\Assets\Cyr_test.js" and save it as UTF-16 LE. In PSPad you can type Forma2 KB (272 words) - 20:44, 21 October 2009 - [[Category: Scripts]] This editor script creates a plane with the specified orientation, pivot point, number16 KB (1,589 words) - 10:00, 21 June 2015 - [[Category: Editor]] This little helper scripts toggles the active status of all selected game objects to the opposite and1 KB (143 words) - 20:53, 10 January 2012 - [[Category: Editor]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly.19 KB (1,707 words) - 15:59, 20 February 2014 - ... means that the contents of a built-in array can be populated in the Unity editor, by dragging and dropping references. Generic Lists also have this ability ...pplied values are all ints. You can also use jagged arrays declared in C# scripts without any problems.29 KB (4,404 words) - 21:47, 2 February 2015 - Place the script inside the Editor folder. Select one or more GameObjects and choose ''GameObject > Move To Or [[Category:Editor Scripts]]1 KB (159 words) - 23:55, 18 January 2014 - [[Category: Editor]] Create a file "MakeFolders.cs" in the Assets\Editor directory (create it, it does not exist by default) and paste the code belo2 KB (235 words) - 20:45, 10 January 2012 - * In the editor, this change will persist across runs. However, the scripts still need to be attached to the correct objects in a build in order to wor3 KB (431 words) - 01:06, 26 March 2016 - - Specific details like scripts and cut scenes may not be in this document but be in the Story Bible. ===Editor===18 KB (2,841 words) - 09:04, 8 October 2010 - [[Category: Editor]] ...es creating 2 folders in your main Asset folder of your project, 1 called "Editor" and 1 called "environment" (the second can be changed in the script if nee2 KB (265 words) - 20:44, 10 January 2012 - == JavaScript - DrawLine.js - Editor version== // Draws a GUI line on the screen in an Editor window.14 KB (1,856 words) - 23:40, 20 August 2013 - There is currently no built-in way to manage the order in which scripts start up. To a certain extent you can get around this by putting more impo * 2. Derive your scripts (or at least the ones which you need to control the order they start in) fr4 KB (526 words) - 07:08, 14 November 2018 - [[Category: Editor]] Editor script that automatically selects and scrolls to a specific gameObject in U2 KB (212 words) - 20:52, 10 January 2012 - [[Category: Editor]] 1.Place the MassSetMaterials.js script in ''YourProject/Assets/Editor''.<br />1 KB (147 words) - 20:52, 10 January 2012 - [[Category:Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. The source obje9 KB (1,116 words) - 04:34, 17 August 2014 - [[Category: Editor Scripts]] Place this script in ''YourProject/Assets/Editor''.<br>5 KB (539 words) - 20:45, 10 January 2012 - CsBiped.cs and CsBiredEditor is Editor scripts for search simplification of parts of a biped body. Having changed these scripts according to your desire, you can strongly facilitate this work.4 KB (389 words) - 20:44, 10 January 2012 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]17 KB (1,480 words) - 20:47, 10 January 2012 - These scripts are designed for quickly setting up basic rigidbody-driven 2D orbital physi Optional component. Display the Orbiter component's properties in the editor. Does nothing in-game.12 KB (1,370 words) - 20:52, 10 January 2012 - In the editor, a script that has been assigned to an object, but subsequently deleted has ...tor/FindMissingScripts.cs". Note that it is important to save it into the editor directory.4 KB (433 words) - 00:00, 1 November 2013 - ...in Visual Studio integration, you'll want to drop the files in your "Unity\Editor\Data\lib" folder. If you had an existing Visual Studio project, you will ne ...t folder create a folder specifically for your C#-Unity-Scripts (I call it Scripts). Add a C# script there in Unity.8 KB (1,248 words) - 00:06, 21 November 2011 - ...documentation/ScriptReference/index.Writing_Scripts_in_Csharp.html Writing Scripts in C#]. It covers things like differences in coroutine syntax, etc. ...lly speeds up coding, and, so far anyway, I don't know of a similar (free) editor for Javascript.6 KB (948 words) - 21:33, 21 November 2018 - [[Category:Editor Scripts]] Like all Editor scripts, this has to be put into a folder named ''Editor'', somewhere in your Assets folder.9 KB (1,413 words) - 18:53, 18 October 2013 - This script creates a new window in the editor with a autosave function. It is saving your current scene with an interval Create a new script called '''AutoSave.cs''' in the folder: Assets/Editor. Activate autosave via window > autosave.2 KB (253 words) - 20:44, 10 January 2012 - [[Category:Editor Scripts]] You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work.2 KB (270 words) - 00:57, 19 March 2013 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]3 KB (322 words) - 20:45, 10 January 2012 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]1 KB (119 words) - 20:45, 10 January 2012 - ===Integrate with Unity3D Using the Scripts:=== #Write unit test scripts as classes derived from the TestCase class.3 KB (491 words) - 16:58, 15 April 2012 - '''Antares Project''' is an extensive package of tools and Editor classes for simplification of creation of large and average projects. As it Scripts Browser<br>6 KB (688 words) - 10:45, 17 October 2010 - Now create another script in the "Assets/Editor" folder named "ExposeProperties" and paste following code: ...hat the property is changing. Unfortunately, this exposes the field to the Editor (editing this value does not call the property getter/setter), so you have8 KB (895 words) - 19:18, 22 February 2016 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]5 KB (659 words) - 01:57, 24 May 2014 - You must place the script in a folder named "Editor" in your project's Assets folder for it to work properly. ...the Terrain menu as "CustomLightmap...". after you finish writing the scripts below11 KB (1,082 words) - 20:48, 10 January 2012 - ...[User:CorruptedHeart|Corrupted Heart]] : I thought I should put some of my scripts on here since it provides a more centralized area for them than on a blog w ....com/feedme/packages/FeedMe0.7.zip 0.7]) package offers the read and write scripts as prefabs for easy entry into a game.14 KB (1,903 words) - 20:45, 10 January 2012 - assigning data to the variable from within the editor. This script edits c# scripts (inserts the following)4 KB (539 words) - 19:18, 18 October 2018 - [[Category: Editor Scripts]] Place the script in a folder named '''Editor''' in your project's Assets folder. Call it '''TerrainImporter.js'''.13 KB (1,632 words) - 20:53, 10 January 2012 - Place the script inside the Editor folder. Select a GameObject and choose 'GameObject > Create Prefab From Sel [[Category:Editor Scripts]]5 KB (629 words) - 13:03, 27 April 2015 - ...vidual image from a massive tileset, and apply that image to a sprite. An editor script allows you to pick out an image of any rectangular size from a given ...Editor and TileSelectorEditor are Editor scripts and must be placed in the Editor folder of your project hierarchy. TileManager is the base script that kick10 KB (1,147 words) - 20:47, 10 January 2012 - ...backtrace again, until something (perhaps a backtrace to one of your Unity scripts) arises. *Review the scripts you have downloaded from the Internet. Most likely they were made for a des5 KB (743 words) - 21:25, 15 May 2012 - Allows execution of arbitrary code snippets in the editor. This makes use of the undocumented UnityEditor.Macros.MacroEvaluator class ...then click the Execute button. See [ this blog post] for examples.1 KB (147 words) - 20:45, 10 January 2012 - This script extends the Unity editor when editing a BoxCollider. Depending on the transformation mode it shows 6 You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly.10 KB (1,037 words) - 15:41, 22 February 2013 - Simple editor script that will copy the path to any selected project pane item to the cli Place this script in ''YourProject/Assets/Editor'' and the menu items will appear in Custom \ Selection \ Print Asset Locati895 B (111 words) - 20:44, 10 January 2012 - The Spline Controller scripts above allow users to create pre-defined spline paths for objects to follow, ...e set for each node in the Unity Editor. The package also includes editor scripts to override the default inspector for the Spline object (which contains the20 KB (3,232 words) - 07:59, 7 September 2013 - ...solved''' without a new release - e.g. if it turns out to be your drivers, scripts, etc - don't delete the bug from this list, just ''italicise'' it and add a ** When autoconnect profiler is enabled the Editor can become unresponsive after selecting Build and run for Android.3 KB (440 words) - 21:08, 8 December 2018 - ...nlock levels in our game as the player progressed..... so we made a simple editor script to make it much easier to delete them. [[Category:Editor Scripts]]696 B (86 words) - 00:41, 20 January 2013 - [[Category: Editor Scripts]] An in-editor version is now available and should be used instead of manual scripting: ht5 KB (731 words) - 12:29, 21 March 2014 - ... 'Standard Assets' folder of your project, and don't try to access them by scripts that are [ ... get a warning if you don't do this, and your project will run fine in the editor, however, it will fail to work when you actually build your project, and wi13 KB (1,683 words) - 01:21, 5 April 2014 - ...e in the Standard Assets folder; this way it can be called from C# and Boo scripts. Call it PlayerPrefsX, and then you can use the following functions: ...ArrayType' near the bottom). Save the file as EditorPrefsX.js and place in Editor folder.41 KB (4,926 words) - 08:55, 20 June 2014 - This editor window allows you to view and edit webplayer-PlayerPrefs files (*.upp) righ -editor. It's just a quick and dirty implementation. It has some error checks but i10 KB (967 words) - 20:47, 10 January 2012 - [[Category: Editor Scripts]][[Category: C Sharp]][[Category: ScriptableObject]] ...ith the name of your ScriptableObject-inheriting class, and place it in an Editor folder. You will now be able to create a uniquely named YourClass asset fil2 KB (273 words) - 12:55, 13 October 2014 - !align=left| Editor | Any scripts which alter the Unity editing environment itself must go in here2 KB (298 words) - 18:41, 23 May 2014 - ...from resources gives you the benefit of configuring the scripts inside the editor as well. You're allowed to put scripts that are not singleton types onto the prefab which do not need a public sin12 KB (1,458 words) - 20:47, 10 January 2012 - [[Category:Editor Scripts]]7 KB (803 words) - 23:32, 28 April 2014 - A simple tile editor script. ...he first one can be anywhere, you probably want to place it with your game scripts.13 KB (1,641 words) - 20:47, 10 January 2012 - {{Scripts Tabbed Navigation}} Example scripts using the new Unity UI system introduced in version 4.6. Designed for build8 KB (1,296 words) - 01:12, 8 November 2018 - {{Scripts Navigation}} ...ister scripts to receive and post notifications. Handles messaging across scripts without references to each other.8 KB (1,143 words) - 23:45, 14 November 2018 - {{Scripts Navigation}} *[[Scripts/StringFilter|StringFilter]] - A class to allow string filtering based on a11 KB (1,614 words) - 23:45, 14 November 2018 - {{Scripts Tabbed Navigation}} *[[FlyThrough]] - A basic fly through camera movement like the one within the editor.8 KB (1,174 words) - 22:39, 5 November 2018 - {{Scripts Tabbed Navigation}} == Editor Scripts ==16 KB (2,352 words) - 22:39, 5 November 2018 - [[Category: General Scripts]] This simple C# class is a timer component that times down from an editor set duration to 0.3 KB (374 words) - 20:45, 10 January 2012 - [[Category: Scripts]] ...ptReference/MonoBehaviour.Reset.html MonoBehaviour reserved method] for in-Editor component resetting. Feel free to suggest a better naming in the [[{{TALKPA13 KB (1,334 words) - 20:45, 10 January 2012 - Place this script in ''YourProject/Assets/Editor''. Go to File > AutoBuilder and select a platform. These methods can also b Place in an Editor folder.5 KB (555 words) - 20:44, 10 January 2012 - [[Category:Editor Scripts]] The purpose of this script is to load content of selected AssetBundle in Editor4 KB (424 words) - 21:56, 27 September 2012 - [[Category: Editor]] [[Category: Editor Scripts]]13 KB (1,572 words) - 20:51, 14 March 2012 - [[Category:Editor]] [[Category:Editor Scripts]]6 KB (738 words) - 05:43, 5 March 2012 - -Place the Math3d.cs script in the scripts folder. //Alternative for HandleUtility.DistanceToLine(). Works both in Editor mode and Play mode.46 KB (6,339 words) - 23:59, 21 August 2018 - Inspired by AddComponentRecursively and DeleteComponentsInChildren editor scripts, this version provides a more solid implementation. Copy it under /Assets/Editor folder and access from GameObject menu.2 KB (246 words) - 16:26, 11 December 2012 - This is a simple editor script. You must place this in the Editor folder of your project. public class AnimationShortcuts : Editor {3 KB (275 words) - 00:07, 25 April 2012 - You must place the script in a folder named "Editor" in your project's Assets folder. [[Category:Editor Scripts]]1 KB (122 words) - 11:51, 26 October 2013 - [[Category: Editor]] Adds a new editor window at menu '''Custom→ModelImportManager'''. The editor window allows selecting/creating/editing/saving model import settings prese20 KB (1,605 words) - 19:23, 11 July 2012 - [[Category: Editor]] Adds a new editor window at menu '''Custom→MaterialAnalyzer'''. The editor window allows analyzing and list all materials used by the current selectio14 KB (1,327 words) - 11:44, 23 July 2012 - [[Category: Editor]] ...ll materials currently used by a prefab or scene object in one window. The editor window expects the object to be dropped (or selected) in the appropriate ob15 KB (1,547 words) - 12:29, 30 September 2013 - Discussion page is [ here] We need 2 Scripts: Firstly a run-time script for holding the values:4 KB (483 words) - 09:41, 15 October 2012 - [[Category: Editor]] ...allows easy replacement of child objects by name by a selected prefab. The editor window expects the object to be dropped in the appropriate object field. A20 KB (1,991 words) - 22:40, 6 November 2012 - ...this script to a GameObject. The anchors are called on Start(). Remove the Editor section (line 146 ~157) if you don't need them updating in the SceneView. .../ This allow us to store the position in scene view after pressing "Play". Editor class is located in the lower section for reference;6 KB (804 words) - 15:04, 19 January 2013 - ... for use as a starting point for how to build a minimalistic 2D tile map & editor within unity.'' Provides two simple C# scripts that are fully commented. The TileMap.cs script is intended to be attached14 KB (1,598 words) - 07:47, 11 December 2012 - ...lder called "Editor" in the root of your project's Assets folder -> Assets/Editor/TransformContextMenu.cs. [[Category:Editor Scripts]]4 KB (421 words) - 00:09, 12 January 2013 - Use those scripts to procedurally create primitive meshes, with custom parameters. More to co PS : A lookat script might be usefull on those guys, with the editor's cam as target (Camera.current).25 KB (3,034 words) - 16:34, 26 October 2014 - [[Category: Scripts]] This editor script creates a baseboards for a selected terrain inside the editor.8 KB (837 words) - 17:34, 24 January 2013 - ...ghtforward. As with any Editor scripts, it must be put in a folder called Editor inside your Assets folder. It adds the menu option: Window -> MeshViewer.9 KB (1,109 words) - 07:48, 7 September 2013 - To start using this script just place it in de editor folder of your project. public class BlenderCameraControls : Editor5 KB (527 words) - 15:15, 27 January 2014 - ...svn/") are ignored by Unity. Any assets in there are not imported, and any scripts in there are not compiled. They will not show up in the Project view. Scripts in here are always compiled first. Scripts are output to either Assembly-CSharp-firstpass, Assembly-UnityScript-firstp9 KB (1,386 words) - 13:10, 2 September 2014 - ... window that allows to replace the presets list in Unity's animation curve editor. It was just written as a quick an dirty solution but is already quite poli ...ript''', so you have to place it in an Editor folder (any subfolder named "Editor"). The filename has to be "CurveEditorTools.cs".13 KB (1,312 words) - 01:39, 15 February 2013 - ...contains functionality that extends the unity editor include it under the "Editor Extensions" category etc. == Editor Extensions ==2 KB (296 words) - 20:21, 7 February 2019 - ...atically switching to and from the master scene when you press play in the editor, the scene auto-loader speeds up your workflow. ...57502-Executing-first-scene-in-build-settings-when-pressing-play-button-in-editor this forum thread].7 KB (818 words) - 19:31, 14 April 2018 - .... Can be useful for editor scripts but probably can be used for non-editor scripts for desktop builds also (for in-game mod editors perhaps?).3 KB (385 words) - 15:12, 9 April 2014 - ...uld be through the use of 'Manager' objects, empty game objects which have scripts attached that persist via calls to DontDestroyOnLoad(). If you imagine the ...ee 'what does what' in your codebase (because it is distributed across the editor)</li>9 KB (1,291 words) - 15:37, 11 July 2013 - A simple Editor window to quickly switch between build scenes. If you use a lot of differen Place SceneViewWindow.cs in your Assets/Editor folder.3 KB (282 words) - 23:00, 1 July 2013 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]13 KB (1,096 words) - 16:23, 1 February 2014 - You must place the script in a folder named '''Editor''' in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]15 KB (1,194 words) - 16:24, 1 February 2014 - ... you can see the results in the scene instantly! The tool comes with some scripts and instructions to integrate with TortoiseGit and Git on Windows (more VCS ...ormal Unity editor! You can take advantage of multi-edit and other editor scripts you’ve devised and the rest, once you’ve found the differences with thi25 KB (4,388 words) - 03:09, 21 January 2019 - [[Category:Editor Scripts]]4 KB (476 words) - 07:31, 9 September 2013 - [[Category:Editor Scripts]]9 KB (895 words) - 07:32, 9 September 2013 - ...g on this project as an open source project. you are still free to use the scripts on this wiki as a base for your own commercial projects. The latest (close Note that neither of these scripts (the original javascript and the translated C#) are up to date and contain15 KB (2,008 words) - 23:04, 8 January 2016 - == Editor Scripting == ...ipts can specialise the way that a components properties are presented and Editor windows can extend this functionality further by creating custom palettes t7 KB (1,111 words) - 12:45, 1 November 2013 - '''Notice: The Unity editor is [ now available on Linux] and can be downloaded through the [ ...s provided by the [ Wine] software. Stability of the editor depends on particular Linux distributions and the video/graphics cards.23 KB (3,658 words) - 21:43, 7 February 2019 - [[Category:Editor Scripts]]4 KB (374 words) - 08:46, 6 December 2013 - Place following scripts somewhere in your '''Assets''' folder under your '''Poroject''' This is editor class so place this code to any '''Editor''' folder inside your '''Assets''' folder<br />11 KB (1,178 words) - 17:20, 13 January 2014 - Place ''BatchActiveToggle.cs'' in the Editor folder of your project. public class BatchActiveToggle : Editor1 KB (184 words) - 10:51, 27 January 2014 - -Place the GameWindowSize.cs script in ''YourProject/Assets/Editor''. -Place the StoredEditorData.cs in ''YourProject/Assets/Scripts''.12 KB (1,404 words) - 09:29, 12 March 2014 - ...n scripts from Twinfox and bitbutter's Render Particle to Animated Texture Scripts from the Unity3D forums. ... will render out an animation that is played when "Play" is pressed in the editor to a series of PNG image files in a directory of your choosing.12 KB (1,664 words) - 04:33, 29 March 2014 - '''''Sublime Text''''' is a popular cross-platform text and source code editor. It is extendable and its community has contributed numerous packages (plug # In Unity, change your External Script Editor to Sublime Text:12 KB (1,754 words) - 09:51, 13 November 2018 - You can then create small scripts that load the values into your existing components. In the Editor project, put settings.txt into the same folder as Assets, Library, ProjectS7 KB (838 words) - 12:26, 4 December 2014 - Did you know your editor scripts can acquire a preview texture for an asset? Check out the members of the [h if you have MonoBehavior code that you want to run while in the unity editor you can use the [ KB (2,662 words) - 19:01, 26 May 2014 - [[Category:Editor Scripts]] Place the script in the ''Editor'' folder in your Assets directory.11 KB (1,235 words) - 20:25, 19 June 2014 - You must place the script in a folder named Editor in your project's Assets folder for it to work properly. [[Category:Editor Scripts]]7 KB (661 words) - 04:59, 16 August 2014 - [[Category: Scripts]] Place this script as "CreateIcoSphere.cs" in ''YourProject/Assets/Editor'' and a menu item will automatically appear in the "GameObject/Create Other8 KB (966 words) - 16:48, 26 October 2014 - [[Category: Editor Scripts]][[Category: C Sharp]][[Category: ScriptableObject]] 1. Copy the following editor script into the path "Assets\Editor\ScriptableObjectUtility2.cs".2 KB (272 words) - 14:25, 16 October 2014 - [[Category: Editor Scripts]][[Category: C Sharp]][[Category: Serialization]]3 KB (399 words) - 16:18, 20 November 2014 - [[Category: Editor Scripts]][[Category: C Sharp]][[Category: GenericMenu]] This editor script defines extension methods for Unity's GenericMenu class which aim to17 KB (1,729 words) - 18:14, 11 March 2015 - ...ipt package (which allows for exposing properties without dedicated editor scripts) can be found here: [[ExposePropertiesInInspector_Generic]] The scripts below make the properties (i.e. members having getters/setters) of a class8 KB (956 words) - 13:22, 21 May 2015 - This editor extension is for migrating code from UnityScript to C# while keeping your s [[Category:Editor Scripts]]7 KB (702 words) - 19:07, 19 November 2014 - Generates a new script, by default at "Assets/Editor/OpenSceneNames.cs" that generates MenuItems each loads a scene from the bui Place it inside the Editor folder. Then, you can click "Open Scene/Update Scene Names" and it will lis4 KB (386 words) - 15:26, 4 March 2015 - The scripts below make the properties (i.e. members having getters/setters) of a class ...e exposed properties in the inspector without the need for specific editor scripts for each, having only to inherit from the ExposableMonobehavior Class. Venr9 KB (1,053 words) - 13:18, 21 May 2015 - Windows Registry Editor Version 5.00 @="\"C:\\Program Files (x86)\\Unity\\Editor\\unity.exe\" -createProject \"%1\""37 KB (4,587 words) - 00:19, 3 April 2015 - ...s, but they can be added to each build type's player settings using editor scripts () to allow ...etion. This is because Unity runs all AssetPostProcessors THEN recompiles scripts, meaning that the manager will properly remove the defines that depend on i7 KB (832 words) - 20:43, 24 January 2016 - ...he prefab inspector (Allow designers a nice UI without custom scripting an editor extension) ...equires that gameobjects have a certain parent/child relationship or other scripts attached to the object.12 KB (1,541 words) - 16:46, 11 February 2016 - The example scripts are '''[[#MyAsset.cs|MyAsset.cs]]''' and '''[[#MyAssetFolderInspector.cs|My The example editor is based on the GUID ''8bf3d03...'',8 KB (774 words) - 09:15, 6 September 2016 - ...odeConfigLoader.cs''' in some editor folder (Assets/Scripts/Editor, Assets/Editor, etc.). - Use '''ConfigAsset.config''' from other scripts to access your config data :-)3 KB (288 words) - 12:23, 2 April 2017 View (previous 250 | next 250) (20 | 50 | 100 | 250 | 500)
http://wiki.unity3d.com/index.php?title=Special:Search&limit=250&offset=0&redirs=1&profile=default&search=Editor+Scripts
CC-MAIN-2019-30
refinedweb
5,952
61.16
Many in polynomial time, which means there’s a way to cheat. That being said, OptaPlanner solves the 1 000 000 queens problem in less than 3 seconds. Here’s a log to prove it (with time spent in milliseconds): INFO Opened: data/nqueens/unsolved/10000queens.xml INFO Solving ended: time spent (23), best score (0), ... INFO Opened: data/nqueens/unsolved/100000queens.xml INFO Solving ended: time spent (159), best score (0), ... INFO Opened: data/nqueens/unsolved/1000000queens.xml INFO Solving ended: time spent (2981), best score (0), ... How to cheat on the N Queens problem The N Queens problem is not NP-complete, nor NP-hard. That is math speak for stating that there’s a perfect algorithm to solve this problem: the Explicits Solutions algorithm. Implemented with a CustomSolverPhaseCommand in OptaPlanner it looks like this: public class CheatingNQueensPhaseCommand implements CustomSolverPhaseCommand { public void changeWorkingSolution(ScoreDirector scoreDirector) { NQueens nQueens = (NQueens) scoreDirector.getWorkingSolution(); int n = nQueens.getN(); List<Queen> queenList = nQueens.getQueenList(); List<Row> rowList = nQueens.getRowList(); if (n % 2 == 1) { Queen a = queenList.get(n - 1); scoreDirector.beforeVariableChanged(a, "row"); a.setRow(rowList.get(n - 1)); scoreDirector.afterVariableChanged(a, "row"); n--; } int halfN = n / 2; if (n % 6 != 2) { for (int i = 0; i < halfN; i++) { Queen a = queenList.get(i); scoreDirector.beforeVariableChanged(a, "row"); a.setRow(rowList.get((2 * i) + 1)); scoreDirector.afterVariableChanged(a, "row"); Queen b = queenList.get(halfN + i); scoreDirector.beforeVariableChanged(b, "row"); b.setRow(rowList.get(2 * i)); scoreDirector.afterVariableChanged(b, "row"); } } else { for (int i = 0; i < halfN; i++) { Queen a = queenList.get(i); scoreDirector.beforeVariableChanged(a, "row"); a.setRow(rowList.get((halfN + (2 * i) - 1) % n)); scoreDirector.afterVariableChanged(a, "row"); Queen b = queenList.get(n - i - 1); scoreDirector.beforeVariableChanged(b, "row"); b.setRow(rowList.get(n - 1 - ((halfN + (2 * i) - 1) % n))); scoreDirector.afterVariableChanged(b, "row"); } } } } Now, one could argue that this implementation doesn’t use any of OptaPlanner’s algorithms (such as the Construction Heuristics or Local Search). But it’s straightforward to mimic this approach in a Construction Heuristic (or even a Local Search). So, in a benchmark, any Solver which simulates that approach the most, is guaranteed to win when scaling out. Why doesn’t that work for other planning problems? This algorithm is perfect for N Queens, so why don’t we use a perfect algorithm on other planning problems? Well, simply because there are none! Most planning problems, such as vehicle routing, employee rostering, cloud optimization, bin packing, … are proven to be NP-complete (or NP-hard). This means that these problems are in essence the same: a perfect algorithm for one, would work for all of them. But no human has ever found such an algorithm (and most experts believe no such algorithm exists). Note: There are a few notable exceptions of planning problems that are not NP-complete, nor NP-hard. For example, finding the shortest distance between 2 points can be solved in polynomial time with A*-Search. But their scope is narrow: finding the shortest distance to visit n points (TSP), on the other hand, is not solvable in polynomial time. Because N Queens differs intrinsically from real planning problems, is a terrible use case to benchmark. Conclusion Benchmarks on the N Queens problem are meaningless. Instead, benchmark implementations of a realistic competition. OptaPlanner‘s examples implement several cases of realistic competitions.
http://www.javacodegeeks.com/2014/05/cheating-on-the-n-queens-benchmark.html
CC-MAIN-2016-07
refinedweb
557
53.27
When a member of my site logged out, click on link, dynamic page with his user id (it's only an example), of course he gets a 403 forbidden page. But I would like redirect him on my login page. I tried following code in router.js, but it doesn't work. How can I solve this ? thanks in advance Mauro [ router.js ] in Backend import {redirect} from 'wix-router'; export function Members_afterRouter(request, response) { if(response.status === 403) return redirect("", "301"); } or import wixLocation from 'wix-location'; export function Members_afterRouter(request, response) { if(response.status === 403) wixLocation.to(`/home/`); return response; } up Hi Mauro, You can write your own router to take care of "special" pages. Refer to the wix-router API for full details. Yisrael Hi Yisrael, believe me I read everything, but I wasn't able to get it, perhaps it's my fault. But could you suggest to me: 1) if my solutions are on the right way or not 2) what's the right way, also in general schema thx in advance Mauro Hi Mauro Did you find how to do this. I m need of the solution for this exact problem. kindly help me with your solution Hema Up
https://www.wix.com/corvid/forum/community-discussion/wix-experts-how-can-i-redirect-on-403
CC-MAIN-2020-05
refinedweb
205
67.25
What is Broccoli.js? Broccoli is a JavaScript build tool. A build tool is a piece of software that is responsible for assembling your applications assets (JavaScript, CSS, images, etc) into some distributable form, usually to run in a browser. All configuration is done in JavaScript (no confusing/messy config files) via a modular plugin architecture. What is a build tool? A build tool’s job is to take input files (your JavaScript, CSS, HTML, etc), to process them and output the result of those transformations, usually into some distributable form. Typically this will involve things like JavaScript transformations to allow you to write newer syntax that will work in a browser, to use a CSS pre-processor like Sass for your CSS, etc. Broccoli.js is different from other build tools. You may be used to tools like Grunt (a task runner), Gulp (streams and pipes) or Webpack (a module bundler), these all aim to solve different problems than what Broccoli was built for. Broccoli provides a modular plugin API to leverage other Node tools. Tools like Babel, Rollup, Node-Sass, Webpack, Browserify, and many more can easily be used with Broccoli. These tools perform the actual work by transforming files, Broccoli merely connects inputs to outputs. Thinking in Broccoli There are 3 main concepts to get your head around when using Broccoli: Directories Using the above tools in a standalone fashion is relatively straight forward, they read input files, and write to output files. The difficulty comes when connecting different tools together as you need to manage all the interim state yourself. The only common interface between them is the file system. Say we want to concatenate our JavaScript files, minify them, and copy the results to our build directory: import fs from 'fs'; import path from 'path'; import minify from 'minify'; import readDir from './readDir'; import readFiles from './readFiles'; function concatFiles(sourceDir, outputFile) { const output = readDir(sourceFiles).reduce((output, file) => output += `;${file.content}`, ''); fs.writeFileSync(outputFile, output) } function minifyFiles(sourceFiles, outputDir) { return readFiles(sourceFiles).map(file => { const minified = minify(file.path); const outputFile = `${outputDir}/${file.name}.min.${file.extension}`; fs.writeFileSync(outputFile, minified) return outputFile; }) } function copyFiles(sourceFiles, outputDir) { sourceFiles.forEach(filePath => { const file = path.basename(filePath); fs.createReadStream(path).pipe(fs.createWriteStream(`${outputDir}/${file}`)); }); } const concatted = concatFiles('app', '/tmp/concat-files') const minified = minifyFiles(concatted, '/tmp/minified-files') copyFiles(minified, './build'); The above is all well and good, but notice how we have to handle the state between each operation. Now imagine how this scales as our build pipeline grows, adding in Sass compilation, JavaScript transpilation (Babel), fingerprinting, etc. That’s lots of temp directories and file state that you have to handle. Broccoli works by managing a set of directories, connected together by plugins, which describe how files are moved or transformed at each step of the build process. Broccoli ensures plugins are called in the prescribed order, and writes the result to a target directory. Each plugin is responsible for processing files passed to it in input directories, and writing files to its output directory. This allows you to focus on the transformations and not how files are passed between each plugin. For example: app [target] ├─ src │ │ ├─ index.js --> ConcatPlugin() ┐ │ │ └─ other.js ├─ MergePlugin() --> ├─ prod.js └─ styles │ └─ site.css ├─ site.scss --> SassPlugin() ──┘ └─ layout.scss Broccoli itself doesn’t really care about files, it simply takes source directories and passes them as inputs to plugins, creates an output directory for the plugin to write to, and passes that output directory as an input to the next plugin. Broccoli is configured with a file in the root of your project called Brocfile.js. This file defines the build pipeline for your application, and is written in plain old JavaScript. The order in which operations happen is determined by this build file. All that is required is that export default returns a function that returns a plugin/string. You can think of broccoli-plugins much like a simple programming language, where the output of a function can be passed as the input(s) to another function. E.g.: export default options => { let js = babel('src'); js = uglify(js); let css = sass('src/styles', 'site.scss'); css = autoprefixer(css); return merge([js, css]); }; This could also be expressed as: export default options => { return merge([ uglify( babel('src') ), autoprefixer( sass('src/styles', 'site.scss') ) ]) }; In the above, a src directory is passed to the babel() plugin (which will convert our new ES6 syntax into ES5 that runs in the browser), the output of that is passed to the uglify() plugin which will minify our JS into a smaller format. The output of uglify() will in turn be passed as 1 input to merge(). Additionally, a src/styles directory and the input file site.scss is passed to sass() which will convert your .scss files into .css files, its output (your css) is passed as an input to autoprefixer() which will add vendor prefixes (like -ms or -webkit) to attributes, which is then in turn passed into the merge() plugin. The merge() plugin will copy the contents of each of its inputs into its output directory. Thus, it merges our uglified JavaScript and out vendor prefixed css. This then becomes our final output and is what is written to our target (destination) directory. Finally, the export default () => line exports a function that Broccoli will invoke with an options object, that contains an env property to indicate the environment. This is set from the --environment CLI argument and defaults to development. This should all be fairly familiar to you if you’ve ever written JavaScript (or any programming language for that matter) before; it’s just inputs and output. Note: ES Modules syntax is supported by Broccoli since version 2.1.0. Prior to this, standard CommonJs syntax with require and module.exports should be used. Plugins Plugins are what a build pipeline developer will interact with most. Plugins are what do the actual work of transforming files at each step of the build process. The API of a plugin is pretty simple, all that’s required is creating a class that extends the broccoli-plugin base class, and implementing a build() method, that performs some work or returns a promise. import Plugin from 'broccoli-plugin'; class MyPlugin extends Plugin { build() { // A plugin can receive single or multiple inputs nodes/directories // The files are available in this.inputPaths[0]/this.inputPaths[1]... // You can do anything with these files that you can do in Node // The output of your plugin must write to this.outputPath } } A broccoli-plugin has only one purpose, to transform the files from its this.inputPaths directories to its this.outputPath directory when its build() function is invoked. Anything you can do in Node, you can do in the build() method. A plugin can receive one or multiple inputs, and these are available in the this.inputPaths array in the order they are provided. this.inputPaths contains paths to directories, that are the outputPath of previous plugins. Each inputPath contains files that you can manipulate and write to this.outputPath. Broccoli will handle the state of these directories and take responsibility for passing them between plugins. There is a special case where a string is passed as an input to a plugin. When parsing your build pipeline, Broccoli will automatically convert a string input into a source plugin. This plugin basically connects its input directory to its output directory, and also allows Broccoli to watch and be notified when files within the input directory change and trigger a rebuild. You can also manually create an unwatched directory from a string by using UnwatchedDir, changes in this directory will not trigger a rebuild. Trees The build pipeline is a series of connected plugins, from one or more input directories to a single target directory. Working from the target directory (the final output) back up to the source directories resembles a tree. Think of a piece of Broccoli and you should have a mental model of what a build pipeline looks like. Broccoli parses the result of the export default from the Brocfile.js, and traverses up all of the connected nodes all the way to the source directories to produce this tree. As Broccoli does this, it sets up the filesystem state for each plugin, creating an outputPath for each to write to. Broccoli normalizes each plugin into what it calls nodes, that contain information about the inputs and output of each item in the build pipeline. You may often encounter the term “tree” when reading plugin READMEs or in tutorials, just remember a tree is a connected set of plugins. Building When Broccoli starts up, the build file Brocfile.js file in the root of the project is parsed, from last (target) plugin/node up to the source directories. As it does so, Broccoli handles wiring up all of the nodes’ inputs and outputs into a graph (from the end node up to the start nodes), creating temporary output directories for each as it goes, linking inputs to outputs. This graph of nodes is held in memory, and reused whenever a rebuild is triggered. When a build or rebuild is triggered, Broccoli will invoke the build() method on each plugin in the order they’re defined in the Brocfile.js, building one plugin at a time, and finally write the files from the final node into the destination build directory. Here’s an example: import mergeTrees from "broccoli-merge-trees"; // broccoli merge-trees plugin export default () => mergeTrees(["dir1", "dir2"]); This is a very simple Brocfile.js that merely merges the contents of dir1 and dir2 into the output directory. The node graph would be represented as follows: source plugin =====> merge plugin source plugin ------------------------ /dir1 => source node 1 /dir2 => source node 2 mergeTrees( 'dir1', => source node, implicitly created when using a string as an input 'dir2' => source node, implicitly created when using a string as an input ) export default () => broccoli-merge-trees node with source nodes dir1 and dir2 as inputs The two input nodes reference two source directories, dir1 and dir2. Thus export default contains a node that references the two input nodes, and an output path that will contain the contents of dir1 and dir2 when the build command is run. Serving One last thing. Broccoli comes with a built in development server that provides an HTTP server to host your assets in development, and perform rebuilds when source directories (nodes) change. The local HTTP server runs on Ok, that pretty much wraps up the basics, let’s continue on and learn how to setup a Broccoli build pipeline in the Getting Started guide.
https://broccoli.build/about.html
CC-MAIN-2019-13
refinedweb
1,777
54.32
0 comments Applying0 comments If0 comments Razor's ability to distinguish between code and HTML/text often looks like magic to me. However, like any good magic act, I'm sometimes surprised by the results I get. For example, this code in a View didn't give me the results I expected: @SalesOrder.CustomerName & " -- unknown" Instead of getting the customer's name followed by " -- unknown", I got this: Peter Vogel & " -- unknown" Razor had decided that my expression ended at the space before my ampersand. Fortunately, to tell Razor where the real end of my expression is, I just have to include the whole expression in parentheses. This code solved my problem: @(SalesOrder.CustomerName & " -- unknown") Now I get: Peter Vogel – unknown which is precisely what I want. Posted by Peter Vogel on 09/14/2015 at 2:19 PM0 comments If you do anything at all with file path, you need the Path class (in the System.IO namespace). The methods on the Path class that you're most likely to use include: These are the answers; any more questions? Posted by Peter Vogel on 08/24/2015 at 2:20 PM0 comments > More Webcasts
https://visualstudiomagazine.com/Blogs/Tool-Tracker/List/Blog-List.aspx?platform=410&Page=11
CC-MAIN-2021-39
refinedweb
194
61.77
Prevent BOBJ data loss when Business user leaves When a business user leaves the company the HR systems will trigger user deletion process which will eventually lock or remove the SAP user accounts in SAP ERP systems. Business Objects systems whose authentication is set to SAP will have only SAP aliases in BOBJ. This blog explains how to create Enterprise aliases to safeguard all SAP user accounts and their report objects in Business Objects systems. This is not applicable for those who Active Directory based login to their BOBJ systems. Refer to SAP notr#note#1804839 — How to add or remove an Enterprise alias through a script in SAP BI 4.0. Use this sample code from to adapt to your requirements. You can download the source code from GITHUB url: Follow the below screen print steps to create the needed Enterprise Aliases with complex random passwords. Create a JAVA Project in Eclipse and as show below. Add the appropriate JRE. In this case, remove the JRE 1.8 and add the sapjvm JRE which is similar to one used by BOBJ Server. Make Sure you have same sapjvm version in your machine as that of BOBJ server Select the newly configured SAPJVM and remove any other jvm from the screen above. Click Finish Here you will add BOBJ Library files. For this you need BOBJ Client tools installed on your machine or you can get the library files form BOBJ Windows server. Click Finish Create a new Class Copy and Past the Source Code Export the code to JAR format Import the JAR file to BOBJ as Program file object The BOBJ part starts from here. No need for any login credentials inside the source code as the Program can run in the logged-in user context of BOBJ system. Class name should match the namespace and class of the Source Code Schedule now Program running.
https://blogs.sap.com/2017/10/02/prevent-bobj-data-loss-when-business-user-leaves/
CC-MAIN-2018-17
refinedweb
317
69.72
I've setup python packaging to handle paths and this works fine at the python prompt but when I try to run Pycharm debug it seems to not respect the package import feature and unless I attach the other packages to the current project in pycharm I don't see how to get debug to import anything in the package directories. at python prompt: from utilities.utilities import get_ste If I attach the project/package utilities to the current project then in pycharm I must use: from utilities import get_ste The problem is we have different packages containing the same module names. Since the above import drops the top level package name, importing the next package overwrites get_ste. Is there a way to get pycharm debug to respect the existing import statements in the modules that work at the python prompt? PyCharm adds the roots of the project to PYTHONPATH. So if you have a directory "utilities" containing a file "utilities.py", and if you want it to be importable as "utilities.utilities", you need to add the parent directory of "utilities" as a content root to your PyCharm project. The current project is Development/PRTS The resources packages are Development/utilities Development/tools Development/JIRA I added the resource packages to the content list for PRTS but pc still listed the libraries as unresolved. So I removed all content directories and added Development This brings in all the other unrelated packages but is this the correct approach? There are a lot of directories I would need to exclude. Is there a performance issue or other reason I should exclude unused packages. For example: Development/JIRA Development/tools Development/utilities The project title shows "Development [JIRA] (/Users/eduvall/ALMA/Development)" so this looks like my project for JIRA. However the project directory does not appear in the project tab, none of the files in the JIRA project are displayed in the project tab and PC warns that JIRA project is already open in project so I cannot add it. The files belonging to the JIRA project that are still open in the editor have lost all perks such as tab completion, bracket highlighting, etc. I also lost my utilities project in PC. I now have two windows showing tools as the project. In the tools project the Content directory is Development and the tools directory and files appear in the project tab. In the JIRA project the Content directory is Development but I only see the files in Development. I don't see the JIRA project directory or files. If I invalidate the caches in one window/project of PC do I loose all of my editing history in all projects? <verbatim> Directory Content root Shows in JIRA project tool Development/JIRA Development No (It should) Development/tools Development Yes Pycharm returns message stating two projects in window cannot have same content root. If I exclude tools in JIRA project content then the library references to tools change to unresolved. If in JIRA project I change content root to Development/tools pycharm returns message about not having intersecting content. I created a project Development as you suggested. This seems to fix the inter-project library referencing and I see how to setup the servers to fit the various needs and I can open the one project in multiple windows though the window names are all the same except for the current file. So this is better than what I was dealing with. With this arrangement will there be a problem or limitations with distributing projects separately such as Development/JIRA and Development/ASDM? Thanks, Gene </verbatim>
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206595685-Trouble-with-debugging-and-importing
CC-MAIN-2020-05
refinedweb
606
51.78
madvise - provide advice to VM system #include <sys/types.h> #include <sys/mman.h> int madvise(void */ #define MADV_ACCESS_MANY_PSET 0x9 /* many processes in pset to access */ /* heavily */ This is. Tell.. MADV_DONTNEED and MADV_FREE perform related but distinct operations. MADV_DONTNEED tries to move any data from the specified address range out of memory, but it ensures that the contents of that range will be recovered when they are next referenced. MADV_FREE does not attempt to preserve the contents of the address range. As a result, subsequent references to an address range that received madvise (MADV_DONTNEED) are likely to be slower than references to a range that received madvise (MADV_FREE). Tell contain. Exclude the specified address range from the coredump of the process. This is alias of the memcntl MC_CORE_PRUNE_OUT command. Include the specified address range in a coredump of the process. This is an alias of the memcntl MC_CORE_PRUNE_IN command..(7) for descriptions of the following attributes:
https://docs.oracle.com/cd/E88353_01/html/E37843/madvise-3c.html
CC-MAIN-2021-43
refinedweb
156
58.79
Here is a list of core java interview questions. These are questions that touch the basics of Java language. And it is good to know them even if you are not attending an interview. Q) Describe the contract of equals() and hashCode(). Why is it important that if you implement one, then you must implement both? The general contract for the hashCode() and equals() method of the same object is that the hashCode() method should consistently return same value if an object is unchanged. If an object is changed then the hashCode() should return a different value and the changed object should not be equals() to the old object. And for two different objects the contract is that if an object equals() another object then the hashCode() of both the objects should also be same. So it is very important that if one of the methods is overridden then the other one should also be overridden. One important thing to consider.. Example Class that overrides both equals() and hashCode() package com.programtalk.learn.interview.questions; /** * * @author programtalk.com * */ public class Person { private String firstName; private String lastName; @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Person)) { return false; } Person otherPerson = (Person) obj; return areEqual(firstName, otherPerson.getFirstName()) && areEqual(lastName, otherPerson.getLastName()); } private boolean areEqual(String firstString, String secondString) { if (firstString == secondString) { return true; } return firstString != null ? firstString.equals(secondString) : false; } @Override public int hashCode() { int hashCode = 17; // start with a prime number hashCode = firstName != null ? firstName.hashCode(): 0; hashCode = lastName != null ? lastName.hashCode(): 0; return hashCode; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } Effective Java by Joshua Bloch is great book to read for core java related issues. Read the java docs of hashCode() here. You will find some interesting things as to how Object returns distinct integers for distinct objects Read the java docs of equals() here. Also look at the Note that refers to the contract defined above. Q) What is the contract between equals() and hashCode() and how it’s used in Java collections? We already defined the contract above. Now let’s discuss the importance of this contract in java Collections. equals() - equals is used in java collections to find an element in a collections. - remove() methods iterates the list to check if an element in a collection equalsthe object to be removed - Arrays.asList(“111”, “222”).remove(“111”) - contains() method checks if a method is in collections. It also iterates the list and checks using equalswhether an element in the list is equal to the object to be checked against. Arrays.asList("111", "222").contains("1111") hashCode() When an object is inserted into HashMap, HashTable or HashSet, a hashcode is generated and used to store the objects. To insert an entry to HashMap, a key and a value is needed. When a key is inserted to a HashMap, the hashCode() and equals() method of the key are used to store the key-value in a bucket( Bucket means each element of the HashMap). If a hashCode() generates the same hashcode for two keys that have equals as false, then both key-value pairs are stored in one bucket as a linked list. And when a search is done on such a key, the linkedlist has to be iterated to find the key that equals the searched one . Let’s take the worst case possible; if all the unequal keys have same hashcode, then they would be stored in one bucket as a linkedlist in the HashMap. And hence the HashMap would practically become a LinkedList and search would be very very slow. So it is very important that the keys of the HashMap should have different hashcode so that they are stored in different buckets in HashMap. HashMap performance is the best when there is approximately one key in one bucket. So it is very important to implement the hashCode() method properly and even effort should be made that unequal objects have not the same hashcode Q) List three Collections interfaces and the basic contract of each. List concrete implementations of each, how they differ, and performance characteristics in space and time. You can find the complete answer to this question at differences of List, Set and Map. Q) Describe Java collections, interfaces, implementations. What’s the difference between LinkedList and ArrayList? The difference between LinkedList and ArrayList is best explained here on stackoverflow. Q) What’s the difference between primitives and wrappers, where do they live, what’s autoboxing? Primitives types are the basic data types in java. And the wrapper classes are classes that encapsulates these primitive types. Here is the list of primitive types and the corresponding wrapper classes in Java. Differences between primitive and Wrapper classes - Declaration - for primitive types, variables are declared e.g. int i = 0; - for wrapper types, a wrapper class has to be instantiated e.g; Integer i = new Integer(1); - Assignment of nullvalue - primitives don’t have a nullvalue. (e,g. when declaring a variable, that usually cannot have a negative value is initialized with -1 as to know that the value comes from a declaration rather than computation) - wrapper classes can be initialized will nulle.g. Integer i = null;.But this makes the program vulnerable to NullPointerException(a billion dollar mistake) - Collections - primitives cannot be inserted into collections - only wrapper types can be inserted into collections. - Memory - primitives takes less memory - Wrapper classes have the primitive values and in addition have the other overheads that lead to more memory consumption Some other things that need to be considered here are autoboxing . We will discuss it in next question. Next thing that you should know is that BigDecimal and BigInteger are wrapper classes but are not primitive wrapper classes. These are immutable wrapper classes Q) What is autoboxing? In java a an int type can be assigned directly to the Integer wrapper class. int i = 1; Integer iWrapper = i; Behind this assignment Java creates an Integer object from the int type. That is called autoboxing. I have written and article about autoboxing and it also gives the various things that should be known to a developer, please read Autoboxing. Q) Where can you put keywords final and static and what do they do? final keyword is used to define a primitive variable as immutable. Once a variable has been declared final, it is not allowed to assign anything to that variable. The variable can no longer be changed. Why i did not say that it makes the variable immutable? Because the objects can be changed by the methods exposed by an object so the objects are still mutable. But the primitive variables cannot be changed except by assigning them to some value. So by defining them as final they become immutable. A final variable can be initialized on declaration or within a constructor. A final variable that is not initialized on declaration is called blank final. Anonymous inner classes declared within a method can only access the final variables available in the method scope. final keyword can be used with a method and a class. A final method can not be overriding by a subclass. A final class can’t be inherited by any class. java.lang.String is a final class. static keyword on a variable declares that variable belongs to a class rather than instance of that class. So only one instance of static field exists. static keyword on a method means that the methods belongs to a class. A static method is available without creating an instance of class and can be invoked by ClassName.staticMethod(). Static methods cannot access the fields of the class unless the fields are marked as static. Fields can be accessed via an instance of the class. static keyword can also be used with an import to import a static method or a static field of another class. Q) Access modifiers in Java. Access modifiers are used to determine who can access a class, method or a member of a class. There are two levels of access control. - Top Level class : A top level class can have either - public : accessible to anyone. - package private(no modifier): accessible only to the package level classes - Members of class : At member level there are four types of access modifiers. A class has access to all its members independent of the modifier. - public: accessible to everyone - protected : accessible to the package and the subclasses - package private(no modifier): only accessible within the same package as the class - private : only accessible within the class and noone else. Q) Difference between String and StringBuilder / StringBuffer. To represent a string literals like “Hello” in java a String class is used. The String class is a sequence of characters. The String class is immutable. I have disussed why string is immutable? The String class provides various method to concatenate, substring or creating a copy of the String. All these methods do not modify the String but they all return a new String. A String represents a string in UTF-16 format. StringBuilder is a mutable object and can be used for creating strings. A StringBuilder has append method to create a string and append any String to the existing String. To change a String object, you need to create a new one. StringBuilder can append to strings without creating new objects and hence has a better performance. See my post for String vs StringBuilder vs stringBuffer performance. StringBuffer has exactly the same properties as Stringbuilder but the only differnce between the two is that StringBuffer is safe to use in mutithreaded environment as StringBuffer is synchronized. So it is advised to use StringBuilder in a single threaded environment so to have a performance benefit over StringBuffer. Q) Difference between interface and abstract class. interface is a contract. Till java 8 no implementation was allowed in interfaces but with java 8 default methods interfaces can also have implementation in methods.In Interface all the methods take the same access modifier as declared for the interface. Any class implementing a interface has to implement all the methods from the interface except the default methods. A class can implement more than one interface. Abstract class is a class that can have abstract methods that have no implementation and can also have methods that have implementation. Only the method declared have to be implemented by the extending class. Since java doesn’t allow multiple inheritance of classes, a class can only extend one abstract class. Q) Difference between overriding and overloading. You can see a detailed answer here in java oops concept polymorphism Q) Types of exceptions and “handle or declare” rule. Java has three kinds of exception: 1. Checked Exceptions: Checked exceptions are the excpetions that need to be either handled with catch or throw. Checked Exceptions are checked at compile time. Even a checked Exception is not handled, the code will not compile. In the below example we will read a file and if the file is not found the readFile() method will throw IOException and in the main method we simply print the stacktrace. package com.programtalk.learn.java.beginner; import java.io.File; import java.io.FileReader; import java.io.IOException; public class ReadFile { public static void main(String[] args) { try { System.out.println(readFile()); } catch (IOException e) { e.printStackTrace(); } } private static String readFile() throws IOException { String content = null; File file2Read = new File("myfile.txt"); FileReader reader = null; try { reader = new FileReader(file2Read); char[] chars = new char[(int) file2Read.length()]; reader.read(chars); content = new String(chars); reader.close(); } finally { if (reader != null) { reader.close(); } } return content; } } 2. Error: Errors are exceptional conditions that are external to an application. Java does not enforce the handling of Errors. So if a method throws an Error, the calling method doesn’t need to handle it. The code will compile fine. An application cannot predict an error condition on compile time. Suppose if an application opens a file and cannot read a file due to some issue with the hardware, throwing java.io.IOError. 3. Runtime Exceptions: These exceptions are internal to an application. Usually these exceptions are because of some bugs with the application code. NullPointerException is a famous example of runtime exception. The below code has a bug that make the code throw a NullPointerException. public static void main(String[] args) { printIfHarry(null); } public static void printIfHarry(String firstName){ if(firstName.equals("Harri")){ System.out.println("I am Harray"); } } So there is a bug in the program and we need to fix it by either having a null check before invoking equals as below. So we don’t need to handle the exception but fix the bug. public static void printIfHarry(String firstName){ if(firstName != null && firstName.equals("Harri")){ System.out.println("I am Harray"); } } Handle or Declare: If you are calling a method that is throwing an exception, a decision needs to be made whether exception has to be caught or thrown to the caller and make the caller handle the exception. The rule is to bubble up the exception to the place where it can handled best. Like a Q) How does garbage collector work? Object data is stored in heap. Heap is managed by garbage collector. A garbage collector can be configured at startup. Automatic garbage collection is a process of managing the heap memory. The garbage collector looks for the objects that any not used anymore. It does so by looking at the references of the object. If an object is not referenced from anywhere in the application, the objects are garbage collected and the memory used by these objects are reclaimed. Here is a article that explains how garbage collector works for Oracle implementation of Java. One the nice book for performance you can read here. Q) How to make a class immutable and what’s the point? A class can be made immutable by declaring all the variables in the class as final. So that the state of the class cannot be changed. The immutability of any object makes that object safe for use as the user would be sure that the state of the object can’t change while the object is being used. The best example of immutability is the String class. An immutable object doesn’t need synchronized access on fields as the same value would be avaliable to all the threads and none of the threads can change the value of the object. Let’s make a Person class immutable. package com.programtalk.learn.java.beginner; /** * * @author programtalk.com * */ public class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } The state of a Person Object cannot be updated. It can only accept the firstName and lastName on creation and then nothing can be changed. Q) What’s JIT compilation? You can find the complete answer to this question at JIT compiler. Q) What’s new in Java 8 / Java 7? What’s coming in Java 9? In new features of Java 8 with examples I have discussed various new features. Here is the list of features: - Lambda expressions - Functional interfaces - Default and static methods in interfaces - forEach() in Iterable interface - Stream API - Java Date/Time API - Concurrency improvements In New Features in Java 9, I have discussed all the major features that are coming in Java 9. Here is the list of major changes: - Q) What is a default method? In Java 8, a major change was introduced in interfaces. The interfaces can now have implementation of methods if they are defined with keyword as default. I have written a detailed article about it at Default methods in Java 8. You may also be interested in: - One Comment Nice article, I was searching for something like this i was browsing the net since ours but din’t find exact question and answers which justifies the question your article is the best and have all the important questions include in it. Thanks for the post..
https://programtalk.com/java/top-corejava-interview-questions/
CC-MAIN-2021-04
refinedweb
2,702
65.62
.io; 29 30 import java.io.IOException; 31 import java.io.OutputStream; 32 33 import org.apache.http.annotation.NotThreadSafe; 34 import org.apache.http.io.SessionOutputBuffer; 35 import org.apache.http.util.Args; 36 37 /** 38 * Output stream that writes data without any transformation. The end of 39 * the content entity is demarcated by closing the underlying connection 40 * (EOF condition). Entities transferred using this input stream can be of 41 * unlimited length. 42 * <p> 43 * Note that this class NEVER closes the underlying stream, even when close 44 * gets called. Instead, the stream will be marked as closed and no further 45 * output will be permitted. 46 * 47 * @since 4.0 48 */ 49 @NotThreadSafe 50 public class IdentityOutputStream extends OutputStream { 51 52 /** 53 * Wrapped session output buffer. 54 */ 55 private final SessionOutputBuffer out; 56 57 /** True if the stream is closed. */ 58 private boolean closed = false; 59 60 public IdentityOutputStream(final SessionOutputBuffer out) { 61 super(); 62 this.out = Args.notNull(out, "Session output buffer"); 63 } 64 65 /** 66 * <p>Does not close the underlying socket output.</p> 67 * 68 * @throws IOException If an I/O problem occurs. 69 */ 70 @Override 71 public void close() throws IOException { 72 if (!this.closed) { 73 this.closed = true; 74 this.out.flush(); 75 } 76 } 77 78 @Override 79 public void flush() throws IOException { 80 this.out.flush(); 81 } 82 83 @Override 84 public void write(final byte[] b, final int off, final int len) throws IOException { 85 if (this.closed) { 86 throw new IOException("Attempted write to closed stream."); 87 } 88 this.out.write(b, off, len); 89 } 90 91 @Override 92 public void write(final byte[] b) throws IOException { 93 write(b, 0, b.length); 94 } 95 96 @Override 97 public void write(final int b) throws IOException { 98 if (this.closed) { 99 throw new IOException("Attempted write to closed stream."); 100 } 101 this.out.write(b); 102 } 103 104 }
http://hc.apache.org/httpcomponents-core-ga/httpcore/xref/org/apache/http/impl/io/IdentityOutputStream.html
CC-MAIN-2014-42
refinedweb
319
61.53
How to turbocharge your Rails API Building an API with Rails is super easy. Active Model makes managing your domain model relationships and querying your database headache-free. Namespacing your API routes only requires a few lines of code and mapping your controllers to namespaced routes only requires one line of code. Active Model Serializers make your JSON responses extremely customizable. On top of all that Rails generators will whip up the structure of your build with a single bash command. Oh ya, and they even have a flag to indicate that you’re generating an API. rails new my_api --api Yes, it’s that easy. Rails leaves a lot to ‘the man behind the curtain’ but it also gives developers easy-to-use tools to expand on whatever they drum up with generators. Let’s work up an example domain: we want to keep track of users that visit our business. - A Business has_many Visits - A User also has_many Visits - Visits belong_to both Businesses and Users - Visits act as a join table between Users and Businesses - Businesses/Users has_many of each other through Visits. We’re concerned with finding Visits that overlap with each other. So let’s put columns in the Visits table for :time_in and :time_out. Let’s also add a boolean :flagged column to the table and have it default to false (this will come in handy later). I won’t dive into how to set these resources and relationships up but you can read more about that here: Rails Generators, Rails Associations. How do we find overlapping visits you ask? Well let’s think about the conditions of an overlap: - userA and userB need to visit the same Business (duh) - AND userA doesn’t leave before userB arrives - AND userB doesn’t leave before userA arrives If all of those conditions are true then the visits in question will have some overlap time with each other. We can reflect these conditions in an instance method inside of the Visit model: Now that we’ve got that in our back pocket let’s talk about Active Model Serializers. First off: to use them you need to include gem ‘active_model_serializers’ in your GemFile then bundle install. We want to use them so that our JSON responses have overlap_visits nested in them. We’ll run rails g serializer visit to generate the serializer, then fill it with a few attributes: The beauty of this serializer is that if you call render json: visit in any controller action the JSON will automatically be formatted according to the attributes specified in the serializer. The response will have the :id, :business_id, :time_in, and :time_out attributes inside of the JSON object as well as all top-level attributes of :user. Pretty sweet. Now let’s get fancy and add :overlap_visits to the serializer. We define an instance method inside the serializer that calls the . overlap_visits instance method we defined in the Visits model. Before we do that, let’s take a look at an instance of VisitSerializer: Ok — main takeaway: if we want to interact with the instance of Visit while we’re inside of the VisitSerializer we will call object, not self. Now let’s move on to that VisitSerializer instance method — inside of it we’ll map over object.overlap_visits (because its an array of Visits), and serialize each Visit. Don’t forget to add :overlaps to the attributes list: Ok now lets seed some overlapping visits and send a get request to /visits/1 to test things out… Oh no! We’re making an infinitely nested JSON object. No worries. That’s why we gave Visit a :flagged attribute! We’re gonna do 2 things: temporarily flag a visit in our controller action, and we’ll make :overlaps a conditional attribute in our serializer like so: And BOOM! You’ve got custom conditional nested attributes in your JSON object. One thing worth noting is that we aren’t saving the Visit after we set :flagged to true — this is so it goes back to being nil after the response is sent (for future requests). This is only scratching the surface with Rails and serialization.
https://wickbushong.medium.com/how-to-turbocharge-your-rails-api-4cd920bf891e?source=post_page-----4cd920bf891e--------------------------------
CC-MAIN-2021-39
refinedweb
695
60.14
Pt-D-3 I still get the flicker as if the tr element is showing with the code suggestion below if I use grow as hinted. I think blind_down may be hiding the fact that the code is buggy. Hiding the tr element and using grows shows the same flicker that was fixed earlier in the chapter by hiding the div. I’m assuming the bug isn’t related to these js effects not working with block elements (why would the blind_down work with showing the cart the first time???) So, why is the flicker still occurring with the below code then? Seems like the code suggestion below is still buggy. I had trouble finding a canonical mapping of the effects as they are named in the effects.js => how to access them in RoR?. I tried “shake” and “grow” but gave up. Marcello:You should use a symbol with the name of the effect (as set in the Effect.VIsualEffect? js functions). Something like that: page[:current_item].visual_effect :grow Any thoughts on sharing the cart item partial between the AJAX & the initial page display? I came here looking for an answer to this problem, thought i’d find it here?! When I just add the line page[:current_item].visual_effect :grow to add_to_cart.rjs, the cart just blinks and winks at me, but its not pretty. - where does the page[:current_item].visual_effect :grow line go? - how do you hide the item initially if qty is 1? - whats the answer to the shared cart partial question? I’m not sure about the cart item question, but here’s my guess. If you want special effects based on the cart, you could have the cart items initially be hidden using CSS (such as using the hidden_div trick). However, only the Javascript from add_to_cart.rjs would be able to “unhide” the item by using “grow” or similar. This makes it tough to share the code because the initial page display doesn’t have the code to unhide the divs. If the user does a refresh, their cart is the same, but the store controller doesn’t know to unhide the items. I wanted to use the BlindDown? effect for this if a new item appeared and the Highlight if the item already exists. These two effects need these lines in my add_to_cart.rjs: For hiding the line I wrote a new helper, just like the one for divs, named hidden_tr_if… this goes to store_helper.rb:For hiding the line I wrote a new helper, just like the one for divs, named hidden_tr_if… this goes to store_helper.rb: page[:current_item].visual_effect :blind_down if @current_item.quantity == 1 page[:current_item].visual_effect :highlight, :startcolor => "#88ff88", :endcolor => "#114411" unless @current_item.quantity == 1 def hidden_tr_if(condition, attributes = {}) if condition attributes["style"] = "display: none" end attrs = tag_options(attributes.stringify_keys) "<tr #{attrs}>" end Now the _cart_item.rhtml has to use this helper. One question is: what happens if we don’t have JavaScript?? The CSS would still kick in and hide the tr element… but we can get around this by choosing the condition right. This is how I call the method in my _cart_item.rhtml: <% if cart_item == @current_item %> <%= hidden_tr_if(cart_item.quantity == 1 && request.xhr?, :id => "current_item") %> <% else %> <!-- ... --> Now I only hide the line using CSS if the view got invoked from a xhr request and this request can only happen if JavaScript? is active. There is only one problem I still have and right now I don’t have the solution: My BlindDown? is not beautiful. It is way too fast. I tried to change this line in add_to_cart.rjs page[:current_item].visual_effect :blind_down if @current_item.quantity == 1 to this page[:current_item].visual_effect :blind_down, :duration => 10 if @current_item.quantity == 1 but it has no effect on the speed at all. I tried all kinds of values without effect. I also tried the same duration parameter on the Highlight effect, there it works like a charm. Anybody knows what is wrong with my BlindDown?? I’m new to Wiki’s so sorry if this is in the wrong place but… In answer to the question above “Anybody knows what is wrong with my BlindDown??” I had a look at and it says: “Works safely with most Block Elements, except table rows, table bodies and table heads.” This could be the problem if you are using table rows? Just a note following the last comment to keep your code clean. Instead of adding a new method to the store_helper.rb file, replace the hidden_div_if method with: def hidden_element_if(element, condition, attributes = {}) if condition attributes["style"] = "display:none" end attrs = tag_options(attributes.stringify_keys) "<#{element} #{attrs}>" end Then in _cart_item.rhtml, call the method with: <% if cart_item == @current_item %> <%= hidden_element_if("tr", cart_item.quantity == 1 && request.xhr?, :id => "current_item") %> <% else %> ... Just make sure you change the method call accordingly for the div tag in store.rhtml.I don’t know if it’s a good idea, but I’ve done the following And I use the following on the templates.And I use the following on the templates. module StoreHelper def method_missing(name, *params, &block) if match = name.to_s.match('hidden_(\w+)_if') hidden_if(match[1], *params, &block) end end def hidden_if(tag, condition, attributes = {}, &block) if condition attributes['style'] = 'display: none;' end attrs = tag_options(attributes.stringify_keys) if block concat("<#{tag}#{attrs}>", block.binding) yield concat("</#{tag}>", block.binding) else "<#{tag}#{attrs}>" end end end <%= hidden_tr_if(@current_item.quantity == 1, :id => 'current-item') %> ... </tr> <% hidden_div_if(@cart.items.empty?, :id => 'cart') do -%> <%= render :partial => 'cart', :object => @cart %> <% end -%> This way I can use both idioms and for any tag. Nathan Manzi says: I modified the hidden_div_if function to help accomplish hiding/revealing individual cart items. I renamed the function to hidden_element_if, adding in an extra parameter for specifying an element to be hidden (as the cart items are wrapped in td tags) and introduced block-handling into it which makes the code a bit cleaner by automatically ending the tag (removing the obscure s): def hidden_element_if(condition, element, attributes = {}, &block) if condition attributes["style"] = "display:none" end attrs = tag_options(attributes.stringify_keys) content = capture(&block) concat("<#{element} #{attrs}>") concat(content) concat("</#{element}>") end Anthony Ettinger says: I tried effects too, but also saw that they only work on block elements. Since the shopping cart is a table (as it should be), there’s no point in working around the clock to get a shake/grow pair working. I originally thought a slide_right/left would be cool for cart items, but alas, they only work on blocks as well. Its more important to have the data show in a table (qty | title | price) then it is to convert to a pseudo-table using nested unordered lists…although that would be the route I would take should it be a requirement. Jinyoung says: My conclusion: 1. The blind/slid down effect doesn’t work well with a table row. However the grow effect works with a table row. Of course, it’s not prefect. the effects works well with firefox 3.0.3 in xUbuntu 8.10(beta), nvidia graphic card machine. And the grow effect works well but table row expanding effect still flickers with IE 6.0.2 in Windows XP, nvidia graphic card machine(a different machine). 2. To tell the truth, I can’t understand the intent not meaning of a question that “Does this make it problematic to share the cart item partial between the AJAX code and the initial page display?” 3. Anyway.. below is my code.In _cart_item.html.erb In add_to_cart.js.rjsIn add_to_cart.js.rjs <% if cart_item == @current_item %> <tr id="current_item" style="display:hidden"> <% else %> <tr> <% end %> <td><%= cart_item.quantity %>×</td> <td><%=h cart_item.title %></td> <td class="item-price"><%= number_to_currency(cart_item.price) %></td> </tr> page.replace_html("cart" , :partial => "cart" , :object => @cart) page[:cart].visual_effect :blind_down if @cart.total_items == 1 page[:current_item].visual_effect :grow if @current_item.quantity == 1 page[:current_item].show if @current_item.quantity > 1 page[:current_item].visual_effect :highlight, :startcolor => "#88ff88" , :endcolor => "#114411" Johnnysocko says: What the guide asks for leaves a little to be desired. I’m had some interpretation issues with what he was asking for. I suppose using the author’s lead for creating the cart as being hidden initially and then using the blinddown effect to expose it was somehow applicable to the problem he’s encouraging you to solve. Getting the thing to just grow by adding a visual_effect = grow for quantity 1 was simple enough. It’s originally hidden by definition since it doesn’t exist for quantity = 0, is it not? I didn’t really get the whole hidden thing. Grow by itself for me renderred pretty strange in IE, bleeding in from the main page till it was in final position. In the end I settled on trying the “parallel_effect” since that sounded pretty cool. But, after several attempts, I couldn’t figure out how to integrate that into the add_to_cart.js.rjs file. So, I left the highlight visual effect intact, then went this route, as ugly as it may be for current_item.quantity = 1. First, I hid the cart_item display for quantity 1. <% if cart_item == @current_item && @current_item.quantity == 1 %> <tr id="current_item" style="display:none"> <% elsif cart_item == @current_item %> <tr id="current_item"> After the rendering of the cart_item partial in _cart.html.erb, I added this gem: <% if !@current_item.nil? && @current_item.quantity == 1 %> <%= render(:partial => 'parallel') %> <%end %> Then, I brute forced the parallel effect in a new partial, _parallel.html.erb: Then, I could easily play around with combinations of Appear, Blinddown, Grow. Behavior was inconsistent between IE and Firefox3. How about the author stop by and give his answer? Groxx says: My changes are as follows (I have no non-ajax degradation, I may add it later). I like the combination they create, and the slide-down effect has a neat bug/feature when tables are involved. Very short video of effects: Note how the “Your Cart” rolls down a moment after the table is revealed :)To store_controller.rb: To add_to_cart.js.rjs: (specifically, :slide_down)To add_to_cart.js.rjs: (specifically, :slide_down) def add_to_cart product = Product.find(params[:id]) @cart = find_cart @current_item = @cart.add_product(product) respond_to {|format| format.js} rescue ActiveRecord::RecordNotFound logger.error("Attempt to access invalid product #{params[:id]}") flash[:notice] = "Invalid product" redirect_to :action => 'index' end def empty_cart session[:cart] = nil respond_to {|format| format.js} end Added empty_cart.js.rjs:Added empty_cart.js.rjs: page.replace_html("cart", :partial => "cart", :object => @cart) page[:cart].visual_effect :slide_down if @cart.total_items == 1 page[:current_item].visual_effect :highlight, :startcolor => "#88ff88", :endcolor => "#114411" And finally to layouts/store.html.erb:And finally to layouts/store.html.erb: page[:cart].visual_effect :drop_out Which nicely solves the entire display problem, though effectively requires AJAX to replace the display properties / content.Which nicely solves the entire display problem, though effectively requires AJAX to replace the display properties / content. <div id="cart" style="display: none"><!-- AJAX fills here --></div> As to the people getting nil errors, it’s likely because you’re trying to check ‘cart.items.empty’ or something similar. The problem is coming from the fact that ‘cart’ itself is nil, so it has no ’.items’ method (it’s actually a nil-class object at this point, not a cart object). Check with ‘cart.nil? or cart.items.empty’ to handle both cases. Leandro says: I didn’t understand the question about sharing code between partial and index, but my code seens to work just fine and it’s fairly simple. Added two lines to handle the insertion of a new product at the cart and inserted a condition to the “yellow fade” effect so it affects only existing product at the cart.add_to_cart.js.rjs page[:current_item].hide if @current_item.quantity == 1 page[:current_item].visual_effect :grow if @current_item.quantity == 1 page[:current_item].visual_effect :highlight, :startcolor => "#88ff88", :endcolor => "#114411" if @current_item.quantity > 1 Alexey says: Here is what I did. First of all, looks like :blind_down effect isn’t working well when it comes to table rows. We can apply :grow effect instead:add_to_cart.js.rjs page[:current_item].visual_effect :highlight, :startcolor => "#88ff88" , :endcolor => "#114411" unless @current_item.quantity == 1 page[:current_item].visual_effect :grow if @current_item.quantity == 1 But now we’ve got a little nuisance: “current_item” renders first, and after that our AJAX redraws it. Therefore we see slight blinking. I’ve come with this bit of an ugly coding to avoid this:_cart_item.html.erb <% if cart_item == @current_item && @current_item.quantity == 1 %> <tr id="current_item" style="display: none"> <% else %> <% if cart_item == @current_item %> <tr id="current_item"> <% else %> <tr> <% end %> <% end %> Any suggestions? Page History - V18: Mark Young [over 4 years ago] - V17: Paweł Damasiewicz [over 5 years ago] - V16: Paweł Damasiewicz [over 5 years ago] - V15: Andrew de Andrade [over 6 years ago] - V14: Andrew de Andrade [over 6 years ago] - V13: Wesley Tarle [about 7 years ago] - V12: Wesley Tarle [about 7 years ago] - V11: Alexey Efremov [over 7 years ago] - V10: Alexey Efremov [over 7 years ago] - V9: Alexey Efremov [over 7 years ago]
https://pragprog.com/wikis/wiki/Pt-D-3/version/10
CC-MAIN-2017-17
refinedweb
2,166
59.8
Log Message: ----------- Replace the random IP ID generation code from OpenBSD with an improved algorithm by Amit Klein. The previous implementation had known flaws (see Klein's paper). We modified a patch from Robert Watson (FreeBSD) to implement the changes. Modified Files: -------------- src/sys/netinet: ip_id.c (r1.1.1.1 -> r1.2) -------------- next part -------------- Index: ip_id.c =================================================================== RCS file: /home/cvs/src/sys/netinet/ip_id.c,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -L sys/netinet/ip_id.c -L sys/netinet/ip_id.c -u -r1.1.1.1 -r1.2 --- sys/netinet/ip_id.c +++ sys/netinet/ip_id.c @@ -1,27 +1,17 @@ -/* $OpenBSD: ip_id.c,v 1.2 1999/08/26 13:37:01 provos Exp $ */ /*- - * Copyright 1998 Niels Provos <provos at citi.umich.edu> + * Copyright (c) 2008 Michael J. Silbersack. * All rights reserved. * - * Theo de Raadt <deraadt at openbsd.org> came up with the idea of using - * such a mathematical system to generate more random (yet non-repeating) - * ids to solve the resolver/named problem. But Niels designed the - * actual system based on the constraints. - * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. + * notice unmodified, @@ -37,173 +27,185 @@ * $FreeBSD: src/sys/netinet/ip_id.c,v 1.7 2005/01/07 01:45:44 imp Exp $ */ +#include <sys/cdefs.h> +__MBSDID("$MidnightBSD$"); + /* - * seed = random 15bit - * n = prime, g0 = generator to n, - * j = random so that gcd(j,n-1) == 1 - * g = g0^j mod n will be a generator again. - * - * X[0] = random seed. - * X[n] = a*X[n-1]+b mod m is a Linear Congruential Generator - * with a = 7^(even random) mod m, - * b = random with gcd(b,m) == 1 - * m = 31104 and a maximal period of m-1. - * - * The transaction id is determined by: - * id[n] = seed xor (g^X[n] mod n) - * - * Effectivly the id is restricted to the lower 15 bits, thus - * yielding two different cycles by toggling the msb on and off. - * This avoids reuse issues caused by reseeding. + * IP ID generation is a fascinating topic. + * + * In order to avoid ID collisions during packet reassembly, common sense + * dictates that the period between reuse of IDs be as large as possible. + * This leads to the classic implementation of a system-wide counter, thereby + * ensuring that IDs repeat only once every 2^16 packets. + * + * Subsequent security researchers have pointed out that using a global + * counter makes ID values predictable. This predictability allows traffic + * analysis, idle scanning, and even packet injection in specific cases. + * These results suggest that IP IDs should be as random as possible. + * + * The "searchable queues" algorithm used in this IP ID implementation was + * proposed by Amit Klein. It is a compromise between the above two + * viewpoints that has provable behavior that can be tuned to the user's + * requirements. + * + * The basic concept is that we supplement a standard random number generator + * with a queue of the last L IDs that we have handed out to ensure that all + * IDs have a period of at least L. + * + * To efficiently implement this idea, we keep two data structures: a + * circular array of IDs of size L and a bitstring of 65536 bits. + * + * To start, we ask the RNG for a new ID. A quick index into the bitstring + * is used to determine if this is a recently used value. The process is + * repeated until a value is returned that is not in the bitstring. + * + * Having found a usable ID, we remove the ID stored at the current position + * in the queue from the bitstring and replace it with our new ID. Our new + * ID is then added to the bitstring and the queue pointer is incremented. + * + * The lower limit of 512 was chosen because there doesn't seem to be much + * point to having a smaller value. The upper limit of 32768 was chosen for + * two reasons. First, every step above 32768 decreases the entropy. Taken + * to an extreme, 65533 would offer 1 bit of entropy. Second, the number of + * attempts it takes the algorithm to find an unused ID drastically + * increases, killing performance. The default value of 8192 was chosen + * because it provides a good tradeoff between randomness and non-repetition. + * + * With L=8192, the queue will use 16K of memory. The bitstring always + * uses 8K of memory. No memory is allocated until the use of random ids is + * enabled. */ -#include "opt_pf.h" +#include <sys/types.h> +#include <sys/malloc.h> #include <sys/param.h> #include <sys/time.h> #include <sys/kernel.h> +#include <sys/libkern.h> +#include <sys/lock.h> +#include <sys/mutex.h> #include <sys/random.h> +#include <sys/systm.h> +#include <sys/sysctl.h> +#include <netinet/in.h> +#include <netinet/ip_var.h> +#include <sys/bitstring.h> + +static MALLOC_DEFINE(M_IPID, "ipid", "randomized ip id state"); + +static u_int16_t *id_array = NULL; +static bitstr_t *id_bits = NULL; +static int array_ptr = 0; +static int array_size = 8192; +static int random_id_collisions = 0; +static int random_id_total = 0; +static struct mtx ip_id_mtx; + +static void ip_initid(void); +static int sysctl_ip_id_change(SYSCTL_HANDLER_ARGS); + +MTX_SYSINIT(ip_id_mtx, &ip_id_mtx, "ip_id_mtx", MTX_DEF); + +SYSCTL_DECL(_net_inet_ip); +SYSCTL_PROC(_net_inet_ip, OID_AUTO, random_id_period, CTLTYPE_INT|CTLFLAG_RW, + &array_size, 0, sysctl_ip_id_change, "IU", "IP ID Array size"); +SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id_collisions, CTLFLAG_RD, + &random_id_collisions, 0, "Count of IP ID collisions"); +SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id_total, CTLFLAG_RD, + &random_id_total, 0, "Count of IP IDs created"); -#define RU_OUT 180 /* Time after wich will be reseeded */ -#define RU_MAX 30000 /* Uniq cycle, avoid blackjack prediction */ -#define RU_GEN 2 /* Starting generator */ -#define RU_N 32749 /* RU_N-1 = 2*2*3*2729 */ -#define RU_AGEN 7 /* determine ru_a as RU_AGEN^(2*rand) */ -#define RU_M 31104 /* RU_M = 2^7*3^5 - don't change */ - -#define PFAC_N 3 -const static u_int16_t pfacts[PFAC_N] = { - 2, - 3, - 2729 -}; - -static u_int16_t ru_x; -static u_int16_t ru_seed, ru_seed2; -static u_int16_t ru_a, ru_b; -static u_int16_t ru_g; -static u_int16_t ru_counter = 0; -static u_int16_t ru_msb = 0; -static long ru_reseed; -static u_int32_t tmp; /* Storage for unused random */ - -static u_int16_t pmod(u_int16_t, u_int16_t, u_int16_t); -static void ip_initid(void); -u_int16_t ip_randomid(void); - -/* - * Do a fast modular exponation, returned value will be in the range - * of 0 - (mod-1) - */ - -#ifdef __STDC__ -static u_int16_t -pmod(u_int16_t gen, u_int16_t exp, u_int16_t mod) -#else -static u_int16_t -pmod(gen, exp, mod) - u_int16_t gen, exp, mod; -#endif +static int +sysctl_ip_id_change(SYSCTL_HANDLER_ARGS) { - u_int16_t s, t, u; + int error, new; - s = 1; - t = gen; - u = exp; - - while (u) { - if (u & 1) - s = (s*t) % mod; - u >>= 1; - t = (t*t) % mod; - } - return (s); + new = array_size; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error == 0 && req->newptr) { + if (new >= 512 && new <= 32768) { + mtx_lock(&ip_id_mtx); + array_size = new; + ip_initid(); + mtx_unlock(&ip_id_mtx); + } else + error = EINVAL; + } + return (error); } /* - * Initalizes the seed and chooses a suitable generator. Also toggles - * the msb flag. The msb flag is used to generate two distinct - * cycles of random numbers and thus avoiding reuse of ids. - * - * This function is called from id_randomid() when needed, an - * application does not have to worry about it. + * ip_initid() runs with a mutex held and may execute in a network context. + * As a result, it uses M_NOWAIT. Ideally, we would always do this + * allocation from the sysctl contact and have it be an invariant that if + * this random ID allocation mode is selected, the buffers are present. This + * would also avoid potential network context failures of IP ID generation. */ static void ip_initid(void) { - u_int16_t j, i; - int noprime = 1; - struct timeval time; - - getmicrotime(&time); - read_random((void *) &tmp, sizeof(tmp)); - ru_x = (tmp & 0xFFFF) % RU_M; - - /* 15 bits of random seed */ - ru_seed = (tmp >> 16) & 0x7FFF; - read_random((void *) &tmp, sizeof(tmp)); - ru_seed2 = tmp & 0x7FFF; - - read_random((void *) &tmp, sizeof(tmp)); - - /* Determine the LCG we use */ - ru_b = (tmp & 0xfffe) | 1; - ru_a = pmod(RU_AGEN, (tmp >> 16) & 0xfffe, RU_M); - while (ru_b % 3 == 0) - ru_b += 2; - - read_random((void *) &tmp, sizeof(tmp)); - j = tmp % RU_N; - tmp = tmp >> 16; - - /* - * Do a fast gcd(j,RU_N-1), so we can find a j with - * gcd(j, RU_N-1) == 1, giving a new generator for - * RU_GEN^j mod RU_N - */ + mtx_assert(&ip_id_mtx, MA_OWNED); - while (noprime) { - for (i=0; i<PFAC_N; i++) - if (j%pfacts[i] == 0) - break; - - if (i>=PFAC_N) - noprime = 0; - else - j = (j+1) % RU_N; + if (id_array != NULL) { + free(id_array, M_IPID); + free(id_bits, M_IPID); + } + random_id_collisions = 0; + random_id_total = 0; + array_ptr = 0; + id_array = (u_int16_t *) malloc(array_size * sizeof(u_int16_t), + M_IPID, M_NOWAIT | M_ZERO); + id_bits = (bitstr_t *) malloc(bitstr_size(65536), M_IPID, + M_NOWAIT | M_ZERO); + if (id_array == NULL || id_bits == NULL) { + /* Neither or both. */ + if (id_array != NULL) { + free(id_array, M_IPID); + id_array = NULL; + } + if (id_bits != NULL) { + free(id_bits, M_IPID); + id_bits = NULL; + } } - - ru_g = pmod(RU_GEN,j,RU_N); - ru_counter = 0; - - ru_reseed = time.tv_sec + RU_OUT; - ru_msb = ru_msb == 0x8000 ? 0 : 0x8000; } u_int16_t ip_randomid(void) { - int i, n; - struct timeval time; - - /* XXX not reentrant */ - getmicrotime(&time); - if (ru_counter >= RU_MAX || time.tv_sec > ru_reseed) - ip_initid(); - - if (!tmp) - read_random((void *) &tmp, sizeof(tmp)); - - /* Skip a random number of ids */ - n = tmp & 0x3; tmp = tmp >> 2; - if (ru_counter + n >= RU_MAX) - ip_initid(); + u_int16_t new_id; - for (i = 0; i <= n; i++) - /* Linear Congruential Generator */ - ru_x = (ru_a*ru_x + ru_b) % RU_M; + mtx_lock(&ip_id_mtx); + if (id_array == NULL) + ip_initid(); - ru_counter += i; + /* + * Fail gracefully; return a fixed id if memory allocation failed; + * ideally we wouldn't do allocation in this context in order to + * avoid the possibility of this failure mode. + */ + if (id_array == NULL) { + mtx_unlock(&ip_id_mtx); + return (1); + } - return (ru_seed ^ pmod(ru_g,ru_seed2 ^ ru_x,RU_N)) | ru_msb; + /* + * To avoid a conflict with the zeros that the array is initially + * filled with, we never hand out an id of zero. + */ + new_id = 0; + do { + if (new_id != 0) + random_id_collisions++; + arc4rand(&new_id, sizeof(new_id), 0); + } while (bit_test(id_bits, new_id) || new_id == 0); + bit_clear(id_bits, id_array[array_ptr]); + bit_set(id_bits, new_id); + id_array[array_ptr] = new_id; + array_ptr++; + if (array_ptr == array_size) + array_ptr = 0; + random_id_total++; + mtx_unlock(&ip_id_mtx); + return (new_id); }
http://www.midnightbsd.org/pipermail/midnightbsd-cvs/2008-February/003028.html
CC-MAIN-2014-52
refinedweb
1,603
54.63
$ cnpm install @cotype/core Cotype manages structured content that can accessed via APIs. The system itself is not concerned with the actual rendering of the data - this is left completely to the consumer which could be a server that generates HTML, a client-rendered web app or a native app that reads the data via HTTP. Cotype is not free software. In order to run cotype on a public server you must purchase a valid license. Please contact info@cellular.de for inquiries. npm install @cotype/core // server.ts import { init, Opts /* ... */ } from "@cotype/core"; const port = 1337; const opts: Opts = { /* ...see */ }; /* Init cotype and receive express app */ init(opts).then(({ app }) => { /* Make the app listen on a specific port * see */ app.listen(port, () => console.log(`Cotype listening on{port}!`) ); }, console.error); models?: ModelOpts[] Describes what content types exist, which fields they have and how they are edited. persistenceAdapter: Promise<PersistenceAdapter> Adapter providing the database connection of the server. Cotype provides a Knex.js adapter that can be configured with a Knex configuration object. import { init, knexAdapter } from "@cotype/core"; init({ /* ... */ persistenceAdapter: knexAdapter({ /* see */ }) }); storage: Storage When files are uploaded, the meta data is stored in the database while the binary data is stored using this adapter. Cotype comes with an adapter that stores all data on the local file system. import { init, FsStorage } from "@cotype/core"; init({ /* ... */ storage: new FsStorage("./uploads") }); thumbnailProvider: ThumbnailProvider Thumbnail creator for uploaded image files. Cotype does not come with a default provider for size-reasons. Please see @cotype/local-thumbnail-provider for a straight-forward implementation. basePath?: string Default: / Can be used to mount the app on a sub-path. For example. import { init } from "@cotype/core"; init({ /* ... */ basePath: "/cms" }); sessionOpts?: SessionOpts The server uses a cookie-session that holds nothing but the user's id. See cookie-session#options for details. The cookie is signed to prevent any sort of tampering. Therefore a secret must be provided using sessionOpts.secret or via the SESSION_SECRET env var. If omitted, a random string will be generated, which means that sessions will become invalid once the server is restarted. migrationDir?: string Absolute path to a directory containing content migration scripts. The scripts are read in alphabetic order and executed only once. Each script must export a function that takes exactly one argument: a MigrationContext. The data can be accessed via REST. The server provides an interactive API explorer that developers can use to browse the content model. NOTE: THe content API is read-only. Modifying content is only possible via the management API that is used by the UI. The content model is defined using only primitives, so it can be serialized into JSON. It describes what content types exist, which fields they have and how they are edited. For a list of available content models check out the typings file. Currently the content model is part of the server and changes require a re-deployment/restart in order to take effect. But since the model is plain JSON it would be pretty easy to manage content types directly in the CMS and store is alongside the data. The data is stored in a Database. Built-In entities (like users, roles, etc.) live in a traditional relational model, whereas all content is stored as JSON in a common table. Content is immutable and each change creates a new revision. If the publish/draft system is enabled for a given content type, API clients won't see the changes until they are published (or a preview is requested). There are two materialized views (one for all published, one for the latest versions) that have indexes on the JSON data as well as a full-text index for searching. Pull-Requests, Issues, Feedback, Coffee and positive thoughts are very welcome! If you want to work on this project locally using the development environment or want to know more about what we consider "internal stuff", please refer to the contribution guidelines
https://npm.taobao.org/package/@cotype/core
CC-MAIN-2020-05
refinedweb
662
59.6
In my last post I walked through the steps you need to take to establish a simple connection with the three sensors on SparkFun’s 9DoF Sensor Stick. If you took those code snippets, dumped them into one file, and ran it on your Arduino… you’d have a big mess. It would work, but it would be awful to read, maintain, or upgrade. And what if you wanted to put some real logic in it? Maybe something that does more than dump raw readings to Serial? And what happens when we get other sensors? We will usually be doing the same things: - Define device-specific constants, likely lifted from the datasheet. - Initialize. - Read data. - Calibrate. - Maybe tweak some device specific parameters, listen for interrupts, etc. Everything but item 5 can be pretty well abstracted away, and we can encapsulate all of the device specific mess in classes that won’t clutter our code or namespaces. Doing this will leave us with code that is more robust, easier to use correctly, and easier to maintain. That’s why I am writing muCSense. muCSense Overview The purpose of muCSense is to provide a framework that abstracts basic operations of initializing, accessing, and calibrating sensors while allowing enough flexibility to allow clients full control over the specific features of each sensor. Along with the framework, the library provides implementation classes for a variety of common sensors. That’s the goal, anyway. I’m still working on the calibration part of the library, and I will write about that — and about some of the cool algorithms behind it — once I get the code online. As of today, I have checked in a basic sensor access framework along with implementation classes for all of the sensors on the 9DoF Sensor Stick. Example Code Let me give you a quick taste of how this library changes your code. If you haven’t looked at the code I already posted for the 9DoF Sensor Stick, open a new tab and have a look now. Now let’s look at a sketch that will produce the same output (modulo startup messages) using muCSense. Start with a few needed #includes. #include <wire.h> #include <adxl345.h> #include <hmc5843.h> #include <ITG3200.h> Next we’ll declare a few pointers for implemented sensors that we’ll construct on the heap. We’ll also keep an array of Sensor objects and an array of names that helps us print things later. //Pointers to implemented sensors that we'll create on the heap. ADXL345* pAccel; HMC5843* pMag; ITG3200* pGyro; Sensor* sensors[3]; char* names[] = {"ACCEL: ", "MAG: ", "GYRO: "}; The setup routine is simple: we use factory methods to fetch the single instances of each of our sensors. It is possible that we have more than one of these sensors connected. In that case, you just need to pass the I2C bus address of the sensor you want as an argument to the ::instance() method. Once they are created, we put the Sensor objects into an array and loop through to initialize them. void setup() { Serial.begin(115200); //Default for BlueSMiRF Wire.begin(); //Call factory methods to get single instances of each sensor. // To get a sensor at a specific I2C bus address, pass the // address in to the factory method. pAccel = ADXL345::instance(); pMag = HMC5843::instance(); pGyro = ITG3200::instance(); //Put the sensors into the array. We could have //constructed them here from the start, but sometimes //it is nice to have access to the derived class pointers. sensors[0] = pAccel; sensors[1] = pMag; sensors[2] = pGyro; //All of our objects implement the Sensor interface, //so we can work with them uniformly. Here we initialize. Serial.println("Initializing sensors"); for(size_t i=0; i < 3 ; ++i) { sensors[i]->init(); } Serial.println("Sensors ready"); } While running, we can loop through the sensors and tell each one to fetch a new reading, then loop through them again to see what the reading was. Why separate the steps like that? There are many times I want to have many clients listening to one sensor, and I want to them to all get the same data. In the calibration part of the library (not checked in yet!) I do this with an Observer pattern, where a DataCollector object tells the sensor to read(), then notifies all of the listeners to come get their data. void loop() { //Now we read the sensors. This call actually triggers // I2C communication (or whatever other communication is needed) // with the device and stores the readings internally. for(size_t i=0; i < 3 ; ++i) { sensors[i]->read(); } //Now that the sensors have been read, we can ask the sensors what // the readings were. This DOES NOT trigger communication with the // sensor and the rawReading method is const. This allows multiple // clients to request the rawReading and they will all get the // same result -- a feature that can be very important. const int16_t* buf = 0; for(size_t i=0; i < 3 ; ++i) { buf = sensors[i]->rawReading(); Serial.print(names[i]); printInt16Array(buf,sensors[i]->dim()); } Serial.println(); delay(100); } Finally, here is a little helper function I used above (that really should be a template). void printInt16Array(const int16_t* buf, size_t len) { size_t i; for(i=0;i Yes, it is still a bit long but notice that most of it is whitespace and comments. There are no device-specific #defines. You can create, initialize, and start reading data from a sensor in four lines of code. If you have a bunch of sensors — like we do on the Sensor Stick — then you can put them in an array and loop through them using a standard interface. Getting Started: Installing and Using muCSense To make the sketch above work, you need to download and install muCSense. To do that: - Download and install Arduino 1.0.1. I don’t know if it works on earlier versions, I’ll try to keep it working on later versions. - In your Arduino directory, create a directory called “libraries” if it isn’t already there. - Download the code as a zipfile from the GitHub repository and extract the files into the “libraries” directory you created in Step 2. It will extract into a folder called something like “rolfeschmidt-muCSense-9b13d30” in your libraries directory. Feel free to change the name. - Now you can either put a sketch together from the snippets above, or grab one I already put together here. You should be up and running in no time. Enjoy! Warning: This is Version 0.0 I’ve been using this for my own projects for a week or two, but it is far from complete and needs thorough testing. So caveat downloador. Some particular issues that currently need to be addressed: - Need a unit testing framework and a set of tests. - Could use an implementation class for ADXL335 (connects through analog pins). - Could use implementation class for simple potentiometers — I particularly want to use flex sensors. - A “keywords” file would be nice. - There is no wiki or documentation. - There is nothing in there for calibration. - EEPROM storage doesn’t work. Right now (August 2012), I’m working hard on item 6, making a calibration library, and hope to have something online within a week. If anyone wants to join in and help me get the other parts done, that would be great! .) Pingback: Connecting to Sparkfun’s 9DOF “Sensor Stick”: I2C access to ADXL345, ITG-3200, and HMC5843 | Chionotech Pingback: SensorLib: Using Calibration | Chionotech I highly admire your work Rolfe! Google searches keep leading me to your posts, along with Aaron Berk’s ( ). Both are absolutely fantastic resources. Thanks, Lee. I’m glad you found it useful. Thanks for pointing out Aaron Berk’s posts — I think I will get a lot out of those. It keeps printing 0 0 0 0 0 0 0 0 0 . I didn’t use soldering. Would that be the issue? That is the only thing I am doing different than you. Any suggestions?
https://chionophilous.wordpress.com/2012/08/24/sensorlib-introduction-and-example/
CC-MAIN-2019-26
refinedweb
1,333
65.12
Ok, so this is not quite a suggestion to DreamHost, but rather a suggestion to the DH users! Recently I’ve been playing with the Go programming language (also known as golang since there are so many things named ‘Go’, starting with the traditional Chinese/Japanese game). If you don’t know what it is, then probably this short guide will be pointless for you. I’m no Go evangelist — so I’ll stick to the basic principles: it’s a programming language developed at Google by a group lead by Ken Thompson and Rob Pike; Thompson is most famous for having developed the C programming language almost half a century ago. Go was designed to be a systems programming language, but even Google was surprised at how it quickly became used by general-purpose programmers as well. It shares some of the syntax of the C/C++/C#/Java/JS/PHP family, although the compiler provides almost all semicolons (so you don’t need to type them). It’s a strongly typed language (think about TypeScript, minus the semicolons) and therefore, unlike JS, you’re not constantly needing to figure out what type a variable is. Nevertheless, you can assign (typed) variables on demand, just as in JS and PHP, and the compiler will figure out what type the variable is — so it sort of combines the best of both worlds, while still avoiding the mess of dynamically typed languages. It’s not strictly an object-oriented language — Thompson et al. never liked the way object-oriented programming has been implemented on ‘their’ family of languages and think that, while the concept is great, the implementation sucks — on all of them. So they came up with an alternative to ‘pure’ object-oriented languages, which retains the best ideas but makes everything conceptually so much simpler. And last but not least, this was a language designed from scratch to deal with distributed computing — as opposed to ‘hacks’ on existing languages (including C!) to deal with that. Sure, semaphores and mutexes are part of the standard libraries, for those loving the traditional approach, but Go goes so much further, into uncharted regions, making distributed computing part of the language itself, and so easy to use that beginners (including yours truly) tend to abuse it — but that’s ok, Go deals with it nicely. Go does not run on virtual machines; it is not an interpreted language and never meant to be one. Instead, it goes back to the source of systems programming: efficient native compiling, doing it ‘fast and furious’, and pretty much having compilers for all platforms (yes, including Android and iOS!). You can also do cross-compiling for multiple platforms from the same source. And the designers wanted that the resulting code is at least as fast as C. After all, one of the purposes of Go was to allow Google to pretty much replace everything they have as web services and replace it with Go. A tremendous task — there must be billions of lines of code! — but I have been assured by people quite high on the hierarchy that this is exactly what is happening. Go has a lot of intriguing design concepts, and one of them is that everything is statically linked (no need to worry about if you have the ‘right’ dynamic libraries — DLLs under Windows — installed correctly), and that you can embed a full web server inside the programming language. That’s right: no need for Apache/Nginx, no need for mod_php or php-fpm, or Passenger, or whatever you use to run your favourite application. No need to install ‘frameworks’ either: Go is its own ‘framework’ (even though obviously there are frameworks on top of Go as well). You get everything out of the box. In that specific scenario, Go is a bit like Node.js, Python, or Ruby. There is a difference, though: no ‘emulated’, ‘interpreted’, or ‘compiled-just-in-time’ code. It’s pure, raw, natively compiled machine code. Anyway, enough of talking about the merits of Go; if it’s the first time ever you heard about it, nothing like visiting one of the many Go tutorials — this one uses the Go Playground, an easy way of learning each lesson while trying out the code associated with it on the same web page, and being allowed to tweak it and see what happens. You’ll be up and running in a jiffy; there is no better way to learn a programming language than by example, i.e. actually writing code instead of looking at code. So — I wondered, is this something that DreamHost supports? Well, searching through the many DH search tools failed to get any results. Go is certainly not installed in the shared environment. And there is one key issue which is fundamental here: DreamHost is about Web hosting. So anything stored in your account should be for the purpose of sharing content online. On the other hand, while Go has its own stand-alone, built-in Web server, deploying it goes against DH’s terms of service, since you’re not supposed to have an application running all the time, consuming memory and resources. Do that too often, and DreamHost will take action — even if it’s an application that is serving Web content. There is a solution, of course. While a Go application can be deployed on its own, in real time, there are usually some front-ends in front of it. It may simply be an nginx configured as reverse proxy, serving static resources directly while passing the rest to Go itself (Go is very efficient at serving static content as well, but some people nevertheless want something ‘in front’ of Go, fearing that it might not be able to handle the load). It might be several nginxes, concurrently sharing the load; or several Varnish front-end reverse-proxy caches… or CloudFlare… whatever. Go ‘plays nice’ with whatever is placed in front of it, and one particular configuration is, of course, running as a FastCGI application. Now you may be thinking that having Apache using FastCGI to connect to an application means a lot of resources being wasted, namely, speed (as opposed to, say, running something as a module inside Apache, such as mod_php). But this is not necessarily the case. While the original CGI specs (which were actually developed in Apache’s immediate predecessor in the earlier 1990s) might have some performance issues, FastCGI is another beast altogether. In particular, when handling applications that fully implement FastCGI as they should, when an application is launched by Apache (which is what DH runs on the shared servers) via FastCGI, then there is a part of it that remains ‘resident’, and the rest of the code is the dispatcher/handler which actually handles the request. What this means is that you can do some setup, keep some structures in memory, and handle requests as they come in. If such requests are frequent (i.e. one per second or so), then the Go application will remain as an active running process — using Go’s thread-like goroutines to handle each request concurrently — for as long as traffic justifies it. When eventually the traffic subsides, and no requests come in for a while, then Apache and the FastCGI interface will just safely and cleanly kill the process. This is a very reasonable approach to resource allocation, not unlike what actually happens with, say, PHP. Also, the Go package that implements FastCGI does it in a way that is totally compatible with a standalone Web application (for which you get zillions of examples when googling on the Web) — basically, you don’t need to worry much if your Go application is being called by FastCGI or directly, the handling actually happens in precisely the same way. Why would you use Go instead of much more popular solutions, such as PHP? Well, learning a new language obviously has a learning curve to overcome; writing code in Go is substantially different from PHP (I use PHP as a reference because it’s highly likely most people around here are familiar with PHP). To give you a personal example, while learning Go, I ported one application I was doing in PHP, which took me about a year to develop until I got ‘stuck’ with handling websockets and a certain degree of parallelism that the application required and that it was extremely difficult to achieve with PHP (it wasn’t impossible, just hard to do). Porting everything to Go took me about four months. The result? An application that is 3x smaller in terms of lines of code (Go is more compact in several different ways, even if at first — being a strongly typed language! — it doesn’t look like it), does some intensely CPU-bound code a thousand times faster (no joking — it’s the difference about an efficiently compiled language versus a good interpreter/compiler, but which nevertheless is nothing more than that), and, although the port was just intended to replicate the same functionality, due to the way Go works, it was so easy to extend it in so many different ways that I ended up with three times the functionality as well — things that had not been part of the specifications at all, but it was just a matter of adding a few bells and whistles as tiny snippets of code, since all the rest was supported by default anyway — it just required activating it. The logic is therefore different. Go started as a systems programming language which got a few packages so that it became a powerful language to provide Web services quickly and efficiently — Google’s answer to interpreted languages such as Ruby on Rails, for instance. One might argue that Java, Python, etc. would all be appropriate to do the same thing. But Google was reluctant about deploying those for their core business. Facebook, as you know, had to develop their own version of PHP (known as HHVM), a compiled one, to get enough performance to deal with one billion users. Twitter had to abandon Ruby. These are the best-known examples, but there are many more: such environments are great when you start developing simple services and need to extend them quickly without much work. But at some point you’ll be dealing with the reality: millions of users pounding at your Web services, and your server(s) need to handle that amount of load. So sometimes simplifying things is the way to go (pun intended): instead of complex stacks with virtual machines, just-in-time compilers, all sorts of ‘performance enhancement’ tools and libraries, and finally your code on top (in an abstract, high-level, interpreted language), Google decided to strip down those layers and just have efficiently compiled machine code to run stuff. A stand-alone Go application serves content as fast as nginx — and that is no mean feat. Of course, nginx is a general-purpose server which can do a zillion things depending on the configuration (and still do it efficiently at all levels); while a Go application will usually implement some kind of Web service, and just stick to do that well. It works like a charm, and it’s hard to imagine anything faster (until you wish to develop your own web server in machine code!). But it’s way easier to do it in Go than in, say, C (which would certainly give you the same amount of performance) — Go’s compiler is supposed to be as good and as efficient as any modern C compiler, and to prove it, yes, Go is also working with the EFF’s famous and ubiquitous GCC compiler, so that it also compiles Go source code — for those die-hard GCC fans who only trust GCC to generate perfect machine code, the good news is that it can compile Go as well, although, honestly, I haven’t seen yet a benchmark comparing an application compiled with Go’s own compiler vs. one compiled with GCC. I would say that the differences would be tiny. One thing that might interest DreamHost fans (just like me!) is the handling of databases. You see, in my own experience, the biggest performance hit that I get on my PHP-based things (namely WordPress, but not only that is) comes from having MySQL as a bottleneck. Of course I’m aware of all the tricks that you can do to limit the amount of MySQL calls made by a PHP application. W3 Total Cache, for instance, already includes a lot of such tricks (caching frequent MySQL requests for specific areas of the site that will not change much over time). Among other caching plugins I’ve tried out, WP Fastest Cache (which has a free and a cheap ‘premium’ option) also uses MySQL query caching on WordPress to achieve better results. Note that I’m not blaming DreamHost for their MySQL solution — it’s probably the best one they can offer considering their shared server setup. But what is the alternative? Sure, you can use sqlite3 — it does its job well enough, and at least it won’t require hitting the main DH MySQL database servers. But Go is so much more flexible in that regard — people have developed all sorts of embedded databases, some running in memory, some running from disk (this is important, since DH limits the amount of memory each process consumes). And these days there is a new trend, the concept of ‘no database’ content-management systems, where basically everything is done with static files on disk — which the user can manage directly by writing Markdown, or access through a backend. There are zillions of applications doing that — Grav, for instance, is a very popular one that runs on top of PHP. Go has its own templating system (similar to the powerful Smarty templating system for PHP), so lots of people have developed solutions on top of Go to accomplish that (Hugo is perhaps Go’s most famous zero-database CMS, or static website generators as they are known, but there are many, many more). Anyway, enough ‘proselytising’ from someone who claimed at the beginning not to be a Go evangelist Installing Go on your DreamHost account is actually quite simple. Go to and copy the link to the latest Linux version (as I type this, it’s). Now login to your DH account. The first thing to do is to download Go: wget This should leave you with a directory called go, but we’re going to change its name: mv go go1.X (where X is the current version, e.g. go1.9; this allows you to have several Go versions side-by-side and quickly fall back to an earlier version if something doesn’t work for you on a newer one, although Go’s maintainers promise to keep backwards compatibility) The reason for this is that Go assumes a lot of things, one of which is that your own applications will be developed under ~/go/src/my-wonderful-project-name. This directory layout for actual development would conflict with the place where the Go compiler and tools are installed, so we rename the directory with those (and in case you’re wondering: yes, Go will check that the development directories are separate from the directories where the Go compiler resides, and it will complain and refuse to run if you merge them together). We can also prepare our first project by creating the necessary directories, e.g.: mkdir -p ~/go/src/my-wonderful-project-name Now we just need to make sure that our $PATH is correctly set up on the shell, as well as some environmental variables for Go to find what it needs. Open your favourite editor and add to the end of your ~/.bashrc file: export GOROOT=$HOME/go1.9 export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin Do a . ~/.bashrc (or log out and log in again) and you should be set up. You should be able now to run the go compiler with go version And that ought to output something like go version go1.9 linux/amd64 if you have everything set up properly. Now let’s start with our first project, just to see if we have set up everything properly. Move to ~/go/src/my-wonderful-project-name and create a file called hello.go. As expected, you’ll do your first Hello, World! project here. package main import ( "fmt" ) func main() { fmt.Println("Hello, world!") } Save it, and remain in that directory. Now run go install If all goes well, you should now have an executable binary in ~/go/bin/ named hello. Running it should obviously write Hello, world! on the screen (as expected). To actually do something useful you will need to write some code that handles the FastCGI API. Here is a very simple example: import ( "fmt" "net/http" "net/http/fcgi" ) func handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-type", "text/plain; charset=utf-8") fmt.Fprintln(w, "This was generated by Go running as a FastCGI app") } func main() { /* * * Everything that is done here should be setup code etc. which is retained between calls * */ http.HandleFunc("/", handler) // This is what actually concurrently handles requests if err := fcgi.Serve(nil, nil); err != nil { panic(err) } } Save it as before, and do a go install. This time, however, we’ll add an additional step afterwards, which is to copy the application binary to one of your actually existing domains that is being served by DreamHost: cp ~/go/bin/hello ~/your.real.webserver.tld/hello.fcgi DreamHost has nicely configured Apache on their shared webservers so that all directories to which the domain name points to are able to run FastCGI applications (I made a few tests and it seems that if they end with .fcgi by default, the webserver will complain the least). So there is no further configuration necessary, just try it out by pointing your web browser to: And you should get (as expected): This was generated by Go running as a FastCGI app That’s it! Note that it is not unusual for the first time you run the Go compiler for it to take some time until it finishes the compilation (it’s a very silent compiler, by the way; it almost never says anything except when it stops with an error). This is normal and the behaviour is consistent among all platforms I tried (Mac OS X, FreeBSD, Ubuntu Linux, and, of course, DreamHost). As you compile more and more times the actual compiling gets faster — there must be some hidden logic behind it (so much happens ‘behind doors’…) which, for the time, still eludes me. But do not evaluate the first time it takes to compile as a baseline for using Go! It’s actually much faster on subsequent runs of the compiler; so fast, in fact, that it doesn’t ‘feel’ like compilation at all. Of course, the next step would be to extract data passed via GET variables or POST data, which is beyond the scope of this article, but you’re quite welcome to take a look at some of my slightly more complex code at for instance. This is a ‘full’ example, intended for a more complex tutorial I’m currently writing for my own blog, and it includes a lot of bells & whistles, namely, key/value database access, complex logging (FastCGI applications cannot write errors to the console — there is no console! — so they will always need to log errors and warnings to file), parsing command-line arguments, setting things up so that the same code works either as a self-contained web app or as a FastCGI app (and even has a console mode for debugging purposes), extracting headers and parameters from a GET/POST, etc. So it does a lot of stuff… with not that many lines of code. Setting it up properly also requires understanding how to use the command go get to get packages from GitHub or elsewhere to use with your own code. All of that is really beyond this post which is already way too long, and in case you’re wondering, yes, that Git repository interface on the link above is fully written in Go (and yes, it can also interface with GitHub, mirror things from there and vice-versa) but no, it does not run on DreamHost, because it was not designed to run as a FastCGI application and I couldn’t bother to change the code (it’s open source). In fact, the major handicap in using applications that others have developed in Go is that almost all, with very few exceptions, were designed to run as self-contained, standalone apps. This is not possible under DreamHost, as explained, unless the application also supports FastCGI. A few do, most don’t. Anyway, I just wanted to add this topic mostly because there might be people googling for friendly hosting providers that allow people to run their own Go applications, and DreamHost is certainly one of them, even though it doesn’t advertise the fact (most likely because they have never heard of Go before or were not even aware that it was so simple to install and get it running in their own servers). Happy Go-ing
https://discussion.dreamhost.com/t/how-to-run-go-language-programs-on-dreamhost-servers-using-fastcgi/64844/?source_topic_id=65734
CC-MAIN-2018-13
refinedweb
3,579
55.17
in reply to Difference between use Module::Name and use Module::Name qw /method1 method2/ Formally, the syntax of the use statement is such that... use Foo::Bar; # is equivalent to: BEGIN { require Foo::Bar; Foo::Bar->import(); }; # and with parameters: use Foo::Bar ...; # is equivalent to: BEGIN { require Foo::Bar; Foo::Bar->import(...); }; [download] The only slightly surprising case is an explicit empty list: use Foo::Bar (); # is equivalent to: BEGIN { require Foo::Bar; }; [download] ... and the import method is not called at all! So the question comes down to; what is the difference between these: Algorithm::LUHN->import(); Algorithm::LUHN->import(qw/is_valid/); [download] import is just a regular old class method; nothing special about it. So the difference between those is whatever the author of Algorithm::LUHN wants it to be. Nonetheless, there are some conventions for the parameters to the import method. While they're just conventions, they're quite widely followed... If you supply a list of words (like "is_valid") to the import method, it indicates that you want to import the listed functions into your own namespace. So, given: Algorithm::LUHN->import(qw/is_valid/); [download] You're saying you want to copy Algorithm::LUHN::is_valid to Your::Package::is_valid. This is really an alias rather than a copy, so uses negligible memory, and negligible CPU (unless you're aliasing dozens and dozens of functions). A bigger concern is often namespace pollution - it means you no longer have the freedom to define your own is_valid function in your package. If the list of words includes some prefixed with ":" or "-", these often refer to "bundles" of functions. So for example, Algorithm::LUHN could define a :validity bundle which included "is_valid" and also "get_validation_errors". So calling: Algorithm::LUHN->import(qw/ :validity /); [download] ... would import both functions. If you don't pass any import parameters at all, the convention is that the module will choose some "default" list of things to export to your namespace - which may be nothing; or may be everything; or may be somewhere in between. Of course, just because you request some function to be exported; there's no guarantee that it actually will - the module may not offer the function you requested. In these cases it is convention for the import method to croak Those are the conventions; there's no rule that says anybody must follow them, but if one does deviate from them, then it's polite to document ones deviation! Deep frier Frying pan on the stove Oven Microwave Halogen oven Solar cooker Campfire Air fryer Other None Results (323 votes). Check out past polls.
http://www.perlmonks.org/index.pl?node_id=1015853
CC-MAIN-2016-26
refinedweb
435
53.21
20906/does-python-know-whether-variable-the-class-method-variable print(hasattr(int, '__call__')) print(hasattr(lambda x: x, '__call__')) print('') class A(object): a = int b = lambda x : x print(A.a) print(A.b) Gives an output of: True True <type 'int'> <unbound method A.<lambda>> How does Python decide what is going to be a method (as A.b is here) and what is just going to be itself (as A.a is here)? In python objects/variables are wrapped into methods if they are function (i.e type( xxx ) gives FunctionType) This is because the FunctionType defines a __get__ method, implementing the descriptor protocol, which changes what happens when A.b is looked up. int and most other non-function callables do not define this method: >>> (lambda x: x).__get__ <method-wrapper '__get__' of function object at 0x0000000003710198> >>> int.__get__ Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> int.__get__ AttributeError: type object 'int' has no attribute '__get__' You could make your own method-wrapper-like behavior by defining some other sort of descriptor. An example of this is the property. property is a type that is not a function, but also defines a __get__ (and __set__) to change what happens when a property is looked up Suppose you have a variable defined in ...READ MORE For Python 3, try doing this: import urllib.request, ...READ MORE Hi. Good question! Well, just like what ...READ MORE Class Method class method is the method which is ...READ MORE You can also use the random library's ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE can you give an example using a ...READ MORE You can simply the built-in function in ...READ MORE If you are talking about the length ...READ MORE The ActiveState solution that Pynt references makes instances of ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/20906/does-python-know-whether-variable-the-class-method-variable
CC-MAIN-2020-40
refinedweb
321
77.23
0 I wrote the following code for a homework problem, but it's stuck in an infinate loop. I'm not sure how to correct that problem. The other issue is I want the answer to be given in two decimal places and not rounded in any way and it appears that my answers are being rounded. Any help would be greatful! // this program will calculate the salary after a set number of days // the user will input the number of days to obtain the salary #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { // declare variables float n = 0; float total = 0; float dollaramount = 0; // prompt user for the number of days cout << "Please enter the number of days to obtain the sum of $0.01 per\n" "day that doubles for the amount of days that you input:"; cin >> n; while (n >= 1 || n <= 30) { total = pow(2, n) - 1; dollaramount = total/100; cout << "The total dollar amount will be:" << setprecision (2) << fixed << dollaramount << " on the " << n << " day."; } cout << " You entered a number outside of 1 through 30, please\n" "start over."; system ("pause"); return 0; }
https://www.daniweb.com/programming/software-development/threads/264062/while-loop-stuck-in-an-infiniate-loop
CC-MAIN-2016-50
refinedweb
190
73.61
Introduction in large amounts of data generated from images and video. For example, one house with 12 cameras taking 180,000 images per day can easily generate 5 GB of data. These large amounts of data make manual analysis impractical. Some cameras have built-in motion sensors to only take images when change is detected, and while this helps to reduce the data, light changes and other insignificant movement will still be picked up and have to be sorted through. To monitor the home for what is wanted, OpenCV* presents a promising solution. For the purposes of this paper it is people and faces. OpenCV* already has a number of pre-defined algorithms to search images for faces, people, and objects, and can also be trained to recognize new ones. This article is a proof of concept to explore quickly prototyping an analytics solution at the edge using Intel® IoT Gateway computing power to create a smarter security camera. Figure 1. Analyzed image from webcam with OpenCV* detection markers Set-up It starts with 'sensor'*. Figure 2. Intel® Edison board and Webcam Setup Figure 3. Intel® IoT Gateway Device Capturing the image The webcam must be USB video class (UVC) compliant to ensure that it is compatible with the Intel® Edison USB drivers. In this case a Logitech* C270 webcam is used. For a list of UVC compliant devices, go here:. To use the USB slot, the micro switch on Intel® Edison development board must be toggled up towards the USB slot. Note that this will disable the micro-USB below to it and disable Ethernet, power (the external power supply must be plugged in now instead of using the micro-USB slot as a power source), and Arduino* sketch uploads. Connect the Intel® Edison development board to the Gateway’s Wi-Fi hotspot to ensure it can see the webcam. To check that the USB webcam is working, type the following into a serial connection. ls -l /dev/video0 A line similar to this one should appear: crw-rw---- 1 root video 81, 0 May 6 22:36 /dev/video0 Otherwise, this line will appear indicating the camera is not found. ls: cannot access /dev/video0: No such file or directory In the early stages of the project, the Intel® Edison development board was using the FFMEG library to capture an image and then send it over MQTT to the Gateway. This method has drawbacks as each image takes a few seconds to be saved which is too slow for practical application. To resolve this problem and make images ready to the Gateway on-demand, the setup switched to have the Intel® Edison development board continuously stream a feed that the Gateway could capture from at any time. This was accomplished using the mjpeg-streamer library. To install it on the Intel® Edison development board, add the following lines to base-feeds.conf with the following command: echo "src/gz all src/gz edison src/gz core2-32" >> /etc/opkg/base-feeds.conf Update the repository index: opkg update And install: opkg install mjpg-streamer To the start the stream: mjpg_streamer -i "input_uvc.so -n -f 30 -r 800x600" -o "output_http.so -p 8080 -w ./www" MJEG compressed format is used to keep the frame rate high for this project. However, YUV format is uncompressed which leaves more detail for OpenCV. Experiment with the tradeoffs to see which one fits best. To view the stream while on the same Wi-Fi network, visit:, a still image of the feed can also be viewed by going to:. Change localhost to the IP address of Intel® Edison development board that should be connected to the Gateway’s Wi-Fi. The Intel® IoT Gateway sends an http request to the snapshot address and then saves the image to disk. Gateway The brains of the whole security camera is on the Gateway. OpenCV was installed into a virtual Python* environment to create a clean and segmented environment for OpenCV and not interfere with the Gateway’s Python version and packages. Basic install instructions for OpenCV Linux* can be found here:. These instructions need to be modified in order to install OpenCV and its dependencies on the Intel® Wind River* Gateway. GCC, Git, and python2.7-dev are already installed. Install CMake 2.6 or higher: wget tar xf cmake-3.2.2.tar.gz cd cmake-3.2.2 ./configure make make install As the Wind River Linux* environment has no apt-get command, it can be a challenge to install the needed development packages. A workaround for this is to first install them on another 64-bit Linux* machine (running Ubuntu* in this case) and then manually copy the files to the Gateway. The full file list can be found on the Ubuntu* site here:. For example, for the libtiff4-dev package, files in /usr/include/<file> should go to the same location on the Gateway and files in /usr/lib/x86_64-linux-gnu/<file> should got into /usr/lib/<file>. The full list of files can be found here:. Install and copy the files over for packages listed below. sudo apt-get install libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev sudo apt-get install libjpeg8-dev libpng12-dev libtiff4-dev libjasper-dev Libv4l-dev Install pip, this will help install a number of other dependencies. wget python get-pip.py Install the virutalenv, this will create a separate environment for OpenCV*. pip install virtualenv virtualenvwrapper Once the virtualenv has been installed, create one called “cv.” export WORKON_HOME=$HOME/.virtualenvs mkvirtualenv cv Note that all the following steps are done while the “cv” environment is activated. Once “cv” has been created, it will activate the environment automatically in the current session. This can be seen in the command prompt at the beginning eg. (cv) root@WR-IDP-NAME. For future sessions it can be activated with the following command: . ~/.virtualenvs/cv/bin/activate And similarly be deactivated using this command (do not deactivate it yet): deactivate Install numpy: pip install numpy Get the OpenCV* Source Code: cd ~ git clone cd opencv git checkout 3.0.0 And make it: mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=ON \ -D PYTHON_INCLUDE_DIR=/usr/include/python2.7/ \ -D PYTHON_INCLUDE_DIR2=/usr/include/python2.7 \ -D PYTHON_LIBRARY=/usr/lib64/libpython2.7.so \ -D PYTHON_PACKAGES_PATH=/usr/lib64/python2.7/site-packages/ \ -D BUILD_NEW_PYTHON_SUPPORT=ON \ -D PYTHON2_LIBRARY=/usr/lib64/libpython2.7.so \ -D BUILD_opencv_python3=OFF \ -D BUILD_opencv_python2=ON .. If the cv2.so file is not created, make OpenCV* on the host Linux* machine as well and copy the file over to /usr/lib64/python2.7/site-packages. Figure 4. Webcam capture of people outside with OpenCV detection markers_4<< Figure 5. Node-RED Flow Once a message is injected in at the “Start” node (by clicking on it), the script will loop continuously after processing the image or encountering an error. A few nodes of note for the setup are the http request, the python script, and the function message for the tweet. The “Repeat” node is to visually simplify the repeat flow into one node instead of pointing all three flows back to the beginning. The “http request” node sends a GET message to the IP webcam’s snapshot URL. If it is successful, the flow saves the image. Otherwise, it tweets an error message about the webcam. Figure 6: Node-RED http GET request node details To run the Python* script, create an “exec” node from the advanced section with the command “/root/.virtualenvs/cv/bin/python2.7 /root/PeopleDetection.py”. This allows the script to run in the virtual Python* environment where OpenCV is installed. Figure 7: Node-RED exec node details The Python* script itself is fairly simple. It checks the image for people using the HOG algorithm and then looks for faces using the haarcasade frontal face alt algorithm that comes installed with OpenCV. It also saves an image with boxes drawn around found people and faces. The code provided below is not optimized for our proof of concept beyond the optional scaling the image down before analyzing it and tweaking some of the algorithm inputs to suit our purposes. It takes the Gateway approximately 0.33 seconds to process an image. In comparison, the Intel Edison module takes around 10 seconds to process the same image. Depending on where the camera is located, and how far or close people are expected to be to it, the OpenCV algorithm parameters may need to change to better fit the situation. import numpy as np import cv2 import sys import datetime def draw_detections(img, rects, rects2, thickness = 2): for x, y, w, h in rects: pad_w, pad_h = int(0.15*w), int(0.05*h) cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness) print("Person Detected") for (x,y,w,h) in rects2: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),thickness) print("Face Detected") total = datetime.datetime.now() img = cv2.imread('/root/incoming.jpg') #optional resize of image to make processing faster #img = cv2.resize(img, (0,0), fx=0.5, fy=0.5) hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) peopleFound,a=hog.detectMultiScale(img, winStride=(8,8), padding=(16,16), scale=1.3) faceCascade = cv2.CascadeClassifier('/root/haarcascade_frontalface_alt.xml') facesFound =faceCascade.detectMultiScale(img,scaleFactor=1.1,minNeighbors=5,minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE) draw_detections(img,peopleFound,facesFound) cv2.imwrite('/root/out_faceandpeople.jpg',img) print("[INFO] total took: {}s".format( (datetime.datetime.now() - total).total_seconds())) To send an image to Twitter, the tweet is constructed in a function node using the msg.media as the image variable and the msg.payload as the tweet string. Figure 8: Node-RED function message node details The system can take pictures on demand as well. Node-RED monitors the same twitter feed for posts that contain “spy” or “Spy” and will post a current picture to Twitter. Posting a tweet with the word “spy” in it will trigger the Gateway to take a picture. Figure 8: Node-RED flow for taking pictures on demand Summary This concludes the proof of concept to create a smarter security camera using Intel® IoT Gateway computing. The Wind River Linux Gateway comes with a number of tools pre-installed and ready to prototype quickly. From here the project can be further optimized, made more robust with security features, and even expanded to create smart lighting for rooms when a person is detected.
http://www.digit.in/apps/smarter-security-camera-a-proof-of-concept-poc-using-the-intel-iot-gateway-33793.html
CC-MAIN-2017-34
refinedweb
1,774
56.55
Is this a bug? <pre>from scene import * import sys class Test(Scene): def setup(self): print self.size def draw(self): sys.exit() run(Test())</pre> The screen size of the iPad 2 in pixels is 768x1024, in portrait mode. But when running this script it looks like the height looses 20 pixels, both in landscape and in portrait, while the width stays like it is supposed to. Output in landscape: Size(w=1024.0, <b>h=748.0</b>) Output in portrait: Size(w=768.0, <b>h=1004.0</b>) Is this supposed to happen? And if so, why doesn't it happen on my iPhone 4S as well? Can anyone else replicate this? - Tony550234 The title bar does not seem to go away on the iPad, but it does on the iPhone. Yes, the size of the scene doesn't include the status bar, which is 20 points high. On the iPhone, the status bar is hidden when a scene is run. Oh, I see. Thanks guys ;)
https://forum.omz-software.com/topic/226/is-this-a-bug
CC-MAIN-2018-13
refinedweb
171
94.66
Object Integrity & Security: Error & Exceptions In this case, anything that is thrown will be caught in this try/catch block. There is no granularity when it comes to Errors, Exceptions, RunTimeErrors, and so forth. As far as information reporting goes, note that in this example, you are using the following line inside the catch block itself. System.out.println(e); This technique is powerful when your code is in development and/or testing. You can start out by casting a wide net and reporting exceptions and errors at a very high level. However, as the development progresses and testing uncovers various issues, you then can use this information to drill down and handle the various situations that arise. In Figure 6, the printed output actually indicates the specific exception that was encountered—in this case, an ArithmeticException. Figure 6: Catching all things Thrown. You also can use a 'compound' catch block to catch more than one specific exception, as seen below. try { .... } catch (java.lang.ArithmeticException e) { System.out.println(e); } catch (java.io.IOException e) { System.out.println(e); } Listing 7 shows an application that combines the two exceptions that I have used in your illustrations, ArithmeticException and FileNotFoundException. import java.io.*; public class Anomaly { public static void main(String args[]){ int a = 0; int b = 1; int c = 0; System.out.println("Begin Application"); try { System.out.println("Divide by Zero"); c = a/0; FileInputStream fileStream= new FileInputStream("Test.txt"); DataInputStream fileIn = new DataInputStream(fileStream); while (fileIn .available() !=0) { System.out.println (fileIn .readLine()); } fileIn .close(); } catch (java.lang.ArithmeticException e) { System.out.println(e); } catch (java.io.IOException e) { System.out.println(e); } System.out.println("Exit"); } } Listing 7: Catching more than one individual exception. The main issue to understand here is that the exceptions will be handled in the order that they are encountered in the catch block. This is important because, if you do something like this, some of the code is considered redundant. For example, in the following code stub, because Exception is listed first, all other exceptions listed in the block (in this case java.io.IOException) are, in fact, redundant. In short, if an IOException is encountered, it will actually be caught by the Exception catch block (because it is indeed an exception) and not even find its way to the IOException catch block. try { .... } catch (Exception e) { System.out.println(e); } catch (java.io.IOException e) { System.out.println(e); } Page 5 of 6 This article was originally published on September 6, 2007
https://www.developer.com/design/article.php/10925_3698026_5/Object-Integrity-amp-Security-iError-amp-Exceptionsi.htm
CC-MAIN-2021-10
refinedweb
422
50.94
#include <sys/types.h> #include <sys/spu.h> int spu_create(const char *pathname, int flags, mode_t mode); int spu_create(const char *pathname, int flags, mode_t mode, int neighbor_fd);: A new directory will be created at the location specified by the pathname argument. This gang may be used to hold other SPU contexts, by providing a pathname that is within the gang directory to further calls to spu_create().. Creating SPU_CREATE_ISOLATE contexts also requires the SPU_CREATE_NOSCHED flag. The mode argument (minus any bits set in the process's umask(2)) specifies the permissions used for creating the new directory in spufs. See stat(2) for a full list of the possible mode values.
http://www.makelinux.net/man/2/S/spu_create
CC-MAIN-2015-48
refinedweb
111
54.22
What's in a Clojure Namespace? What's in a Clojure Namespace? Namespacing is a fundamental part of Clojure, but what actually is it under the hood? A great under the covers article on the innards of Clojure's namespace functionality. Join the DZone community and get the full member experience.Join For Free Every well-behaved clojure source file starts with a namespace declaration. The ns macro, as we all know, is responsible for declaring the namespace to which the definitions in the rest of the file belong, and generally also includes some requirements and imports and whatnot. But today (at Clojure/West, shoutout!) Stuart Sierra made a passing reference to the internals of nsduring his talk that got me interested. But what is a namespace really? Some things in Clojure are implemented as Java classes of terrifying scope and, for reasons known and important only to the Man himself, using a perplexing and obscure formatting style. But, namespace is not one of those things, which is nice because otherwise the rest of this post would be Java source code and nobody wants to see that. (I’m perfectly comfortable with normal Java code, by the way, it’s just that clojure’s, for probably reasonable reasons, is not that). No, you came to see some down and dirty Clojure internals, and that’s what you’re going to get. It turns out that ns is just a regular old macro that expends to a bunch of regular old functions that just happen to be how Clojure happens to load code. In other words, we can use our good friend macroexpand to peer (partway) down this particular rabbit hole, which as you might have guessed is what is about to happen. Luckily, clojure.core’s code is about as transparent as the underlying Java is opaque, so everything went better than expected for the purposes of this post. The result of (macroexpand '(ns namespaces.test)) is the following: (do (clojure.core/in-ns (quote namespaces.test)) (clojure.core/with-loading-context (clojure.core/refer (quote clojure.core))) (if (.equals (quote namespaces.test) (quote clojure.core)) nil (do (clojure.core/dosync (clojure.core/commute (clojure.core/deref (var clojure.core/*loaded-libs*)) clojure.core/conj (quote namespaces.test))) nil))) Hey, that’s not so bad! Inside that do, there are 3 things happening: in-nsis called, setting the current value of the ns var in the clojure.corenamespace. Stateful! Shame! But, there’s a rich tradition of lisps in general working this way behind it, and it saves adding an extra indentation level to every source file by including it in some with-nsmacro, so I think we can let this slide. (Also, judging by the Java code, someone has a vendetta against excess indentation). - Inside the with-loading-contextmacro, we referthe clojure.core namespace. This is good, because we always want the functions in clojure.coreto be handy. Also, referturns out to be the root of all code-loading in clojure; more on this later. - Finally, if the namespace in question is not clojure.core, we append its name (as a symbol) to the *loaded-libs*ref, using commutein a dosynctransaction as one does when working with refs. “I hope he’s not about to go into excruciating detail about each of those steps,” I hear you psychically mutter. Too bad for you! From the Top: in-ns The in-ns is one of those things that Clojure defines in Java. If I wasn’t clear before, I have no intention of delving beyond that barrier, but from context it’s clear that in-ns does what ns would do if ns wasn’t dedicated to encapsulating the half-dozen different things involved in initializing said namespace. In other words, in-ns is what you would be using if you were also using the require and use functions in your code, instead of the :require and :use (p.s. don’t use use or :use) in ns. In code form, this… (in-ns 'namespaces.test) (require 'clojure.string) … is about equivalent to: (ns namespaces.test (:require clojure.string)) Well, except for all the other stuff that ns does. Incidentally, while sternly recommending against it, the clojure.core internals use in-ns extensively, sometimes spreading a namespace across files. But who are we to judge? refer Madness The next thing that happens is that the clojure.core namespace is refer’d into the context of the namespace that was just declared the current namespace in in-ns above. This is important because we probably want access to the functions in clojure.core. Ultimately, refer ends up calling the referencemethod on the *ns* (current namespace) var, which is an instance of clojure.lang.Namespace, which does a voodoo dance that results in the relevant symbols being made available to us. I didn’t explore too deeply into what the undocumented with-loading-contextmacro does, accomplishes, because Java, but perhaps it has something to do with how we’re able to use functions defined in clojure.core to load clojure.core. Or perhaps not? Getting loaded Finally, the rigamarole surrounding the *loaded-libs* refs is just there so that load-lib doesn’t reload a loaded lib (er, namespace) unless specifically asked to. More about load-lib right now: What About require and use? Popping a :require (or :use or :import) into your ns declaration just adds a matching call to require (or use or import) to the with-loading-context part of the namespace macro expansion. Require and use turn out to be different flavors of the same thing: (defn require "...docs..." [& args] (apply load-libs :require args)) (defn use "...docs..." [& args] (apply load-libs :require :use args)) load-libs is a collection of checks and whatnot wrapping a bunch of calls to load-lib, which we met above. In turn, load-lib translates the namespace into a path and does some other stuff and then calls load on the path, while loadinvokes the Java methd clojure.lang.RT/load on it. The eldritch magic contained therein in turn grabs the file, compiles it, and puts all the top-level symbols it found into the current namespace. The import macro is a bit different, deferring to import*, another magic clojure symbol that’s only defined in Java. The details aren’t clear to me, but I think it’s safe to assume that ultimately this just uses Java reflection to load the class. Conclusion So what can we take away from this mutually enlightening experience? - The nscall is actually not so special, until you get to the special parts. - We could manually implement just about everything with in-nsand requiredirectly, but we shouldn’t. - I should talk to someone about my underlying Java phobia. That’s all for tonight! Published at DZone with permission of Adam Bard . 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/whats-in-a-clojure-namespace
CC-MAIN-2019-26
refinedweb
1,171
65.93
This program should allow you to enter the percentage desired at the end of a course, the total number of points in the course, the points earned to date, and the total points to date. The program should then calculate and display: 1) the number of the remaining points in the class needed to earn the desired percentage 2) the percentage of the remaining points needed to earn the desired percentage in the course. Read the input in the order below: (Don't read anything else.) 1) Percentage desired 2) Total points in the course 3) Points earned to date 4) Total points to date Heres is what I have got so far. I am not sure how to convert the formula over to C code #include <stdio.h> int main () { float percent; int totalpoints; int earnedpoints; int totaltodate; printf("Enter Percentage Desired:"); scanf (" %d", & percent); printf("Enter Total points in the course:"); scanf ("%d",& totalpoints); printf("Enter Total points earned to date:"); scanf("%d ", &earnedpoints); printf("Enter Total points to date:"); scanf("%d",&totaltodate);
http://cboard.cprogramming.com/c-programming/62583-problem-calculations.html
CC-MAIN-2015-40
refinedweb
175
60.28
In general a PCI device does not need to have _HID or _UID, because _ADR is used for that purpose. If a PCI device happens to be on a root PCI bus, it has _HID and _UID as well. So the bus number is avaialble from _BBN on the bus, assuming that the OS does not change the PCI bus number. So as long as you are interested in _HID and _UID of a PCI device, you should be able to assume _BBN, thus, PCI bus number. Jun -----Original Message----- From: Lee, Jung-Ik Sent: Wednesday, May 02, 2001 2:02 PM To: Nakajima, Jun; 'Matt_Domsch@Dell.com'; acpi@phobos.fachschaften.tu-muenchen.de Cc: linux-ia64@linuxia64.org Subject: RE: [Linux-ia64] translating ACPI _HID & _UID to PCI bus number Even with ACPI namespace, {_HID, _UID} pair does not tell the path of a device in a given topology, and can not produce a PCI bus number(vice versa). _ADR of PCI device does not provide bus number either. It's just dev +func. So to get PCI bus number of a given PCI bus: 1. you can use _BBN of the device, but this works only on root pci bridges. I personally want to see all PCI bridges have _BBN method for OSPM's convenience, but ACPI spec does not require it for non-roots. 2. you can enumerate pci bus from root pci bridges, following PCI std df enum scheme, and access pci config space of pci bridges to get BIOS set bus numbers. (But note that bus numbers set by BIOS do not necessarily match to what OSes assign. For reasons OSes can assign bus numbers different from BIOS's. So, PCI numbers from pci config space at EFI boot manager time, it's not always the same as OSes enumerates) Afaik, linux does not alter bus numbers set by BIOS yet, but someday...) Thus, there seems to be no perfect solutions here... to get pci bus number from acpi name space alone. J.I. -----Original Message----- From: Nakajima, Jun [mailto:jun.nakajima@intel.com] Sent: Wednesday, May 02, 2001 1:26 PM To: 'Matt_Domsch@Dell.com'; acpi@phobos.fachschaften.tu-muenchen.de Cc: linux-ia64@linuxia64.org Subject: RE: [Linux-ia64] translating ACPI _HID & _UID to PCI bus number Not all PCI devices appear in the ACPI namespace. If a PCI device shows up in the ACPI namespace, it should have _ADR, which basically is its PCI bus, device, and function number. Then you can tell the _HID and _UID associated with that device. Hope this helps. Jun -----Original Message----- From: Matt_Domsch@Dell.com [mailto:Matt_Domsch@Dell.com] Sent: Wednesday, May 02, 2001 12:34 PM To: acpi@phobos.fachschaften.tu-muenchen.de Cc: linux-ia64@linuxia64.org Subject: [Linux-ia64] translating ACPI _HID & _UID to PCI bus number I'm working on a user-space application to add a Linux entry to the IA-64 EFI Boot Manager. One component of this entry is the ACPI _HID and _UID fields, which correspond to a PCI bus number (in Linux kernel terms). I know the PCI bus number, device, and function, for a given controller. What I don't have is the ACPI _HID and _UID fields that match the PCI bus number. Any thoughts on how I can get them? Thanks, Matt -- Matt Domsch Sr. Software Engineer Dell Linux Systems Group Linux OS Development _______________________________________________ Linux-IA64 mailing list Linux-IA64@linuxia64.org on Wed May 02 16:25:31 2001 This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:03 EST
http://www.gelato.unsw.edu.au/archives/linux-ia64/0105/1503.html
CC-MAIN-2020-24
refinedweb
603
73.68
This lesson was originally publish on React Native School. If you're interested in accessing 110+ React Native articles then be sure to visit! Once you've configured deep linking in your app, which you can learn how to do here (Expo, React Native CLI), what happens once the app opens? In this lesson we'll configure an app to automatically navigate to the right screen based on the deep linking url. The app we're starting with grabs a list of people from the Star Wars API and displays their details on a details screen. You can clone this starter project on Github. We want to set up our app so that it will automatically open up to a detail screen and get the relevant data. To accomplish that we'll need to do a few things - Enable deep linking in the app (Done) - Configure deep linking in React Navigation - Request person information from data passed in our deep link Configuring Deep Linking in React Navigation First, we need to define a path for each of the navigators in the tree. By that I mean that, since we want to set up deep linking to the Details screen we'll also need to set up a path for its parent navigator listing MainApp. App/index.js // ... const MainApp = createStackNavigator({ List: { screen: List, navigationOptions: { headerTitle: 'People', }, path: 'list', }, Details: { screen: Details, navigationOptions: { headerTitle: 'Details', }, path: 'details', }, }); const App = createSwitchNavigator({ Initializing, MainApp: { screen: MainApp, path: '', }, }); // ... We're also going to need to be able to pass variables to /details. We can designate that by adding a parameter prefixed by :. // ... const MainApp = createStackNavigator({ List: { screen: List, navigationOptions: { headerTitle: 'People', }, path: 'list', }, Details: { screen: Details, navigationOptions: { headerTitle: 'Details', }, path: 'details/:personId', }, }); This will allow us to pass a dynamic value such as /details/3. Next, we need to tell React Navigation what our uriPrefix. This is whatever you configured within Xcode or AndroidManifest.xml. If you're using Expo then the prefix is going to be different between development and a published app. Fortunately. Expo makes it easy to build the right uriPrefix. import { Linking } from 'expo'; // ... const AppContainer = createAppContainer(App); export default () => { const prefix = Linking.makeUrl('/'); console.log(prefix); // if not using expo then prefix would simply be `swapi://` return <AppContainer uriPrefix={prefix} />; }; // ... I'm logging prefix so we know what to use when opening the url. The app should now be configured to accept and handle deep linking. To test it run the following command: Terminal # iOS xcrun simctl openurl booted exp://127.0.0.1:19000/--/details/3 # Android adb shell am start -W -a android.intent.action.VIEW -d "exp://127.0.0.1:19004/--/details/3" com.deeplinking If you're not using expo, or it's a live app, it would look like: Terminal # iOS xcrun simctl openurl booted swapi://details/3 # Android adb shell am start -W -a android.intent.action.VIEW -d "swapi://details/3" com.deeplinking Request Person Information from Data Passed in Deep Link Obviously we don't have any data yet. To fix this we need to grab the person id and make a request. To access the personId we just need to use this.props.navigation.getParam('personId') like we would grab any other param. First we'll check if a full item is passed. If a full item is not passed then we'll try to grab the personId and make a request. App/screens/Details // ... class DetailsScreen extends React.Component { // ... componentDidMount() { const item = this.props.navigation.getParam('item', {}); if (Object.keys(item).length === 0) { const personId = this.props.navigation.getParam('personId', 1); fetch(`{personId}`) .then(res => res.json()) .then(res => { const data = []; Object.keys(res).forEach(key => { data.push({ key, value: `${res[key]}` }); }); this.setState({ data }); }); } else { const data = []; Object.keys(item).forEach(key => { data.push({ key, value: `${item[key]}` }); }); this.setState({ data }); } } // ... } // ... And there you have it! That's how you configure and interact with deep links in your React Native app. You can find the final code on Github. Have a React Native question? Let me know! Discussion (0)
https://dev.to/spencercarli/handling-deep-links-with-react-navigation-nk0
CC-MAIN-2021-21
refinedweb
682
50.12
A few days ago I wrote about bifurcation for a discrete system. This post looks at a continuous example taken from the book Exploring ODEs. We’ll consider solutions to the differential equation for two different initial conditions: y(0) = 0.02, y‘(0) = 0 and y(0) = 0.05, y‘(0) = 0. We’ll solve the ODE with both initial conditions for 0 ≤ t ≤ 600 with the following Python code. from scipy import linspace from scipy.integrate import solve_ivp import matplotlib.pyplot as plt def ode(t, z): y, yp = z return [yp, 2*(-2 + t/150)*y - 4*y**3] a, b = 0, 600 t = linspace(a, b, 900) sol1 = solve_ivp(ode, [a, b], [0.02, 0], t_eval=t) sol2 = solve_ivp(ode, [a, b], [0.05, 0], t_eval=t) First let’s look at the solutions for 0 ≤ t ≤ 200. Here’s the code that produced the plots. plt.subplot(211) plt.plot(sol1.t[:300], sol1.y[0][:300]) plt.subplot(212) plt.plot(sol2.t[:300], sol2.y[0][:300]) plt.show() Note that the vertical scales of the two plots are different in order to show both solutions relative to their initial value for y. The latter solution starts out 2.5x larger, and essentially stays 2.5x larger. The two solutions are qualitatively very similar. Something unexpected happens if we continue the solutions for larger values of t. Here’s the code that produced the plots. plt.subplot(211) plt.plot(sol1.t, sol1.y[0]) plt.ylim([-1,1]) plt.subplot(212) plt.plot(sol2.t, sol2.y[0]) plt.ylim([-1,1]) plt.show() Now the vertical scales of the two plots are the same. The solutions hit a bifurcation point around t = 300.
https://www.johndcook.com/blog/2020/01/22/ode-bifurcation-example/
CC-MAIN-2021-21
refinedweb
292
68.57
An Introduction to Compiler Design - Part II - Parsing A. Introduction Welcome to part II of the compiler design tutorial! (See part I) Parsing is a pretty complex subject, so the examples I will present are basic but good enough for you to see how you can extend them to support a progamming language. We'll parse a conditional statement (if/then), arithmetic statements, and a few others. After the source code has been tokenized, the parsing phase commences. At the end of this stage, if the source code is syntactically valid, the compiler has generated either (1) an abstract syntax tree (AST) or (2) a syntax-directed translation (SDT) of the source code. These are known as immediate representations (IR). They are forms that can be optimized easily and later translated into assembler code. An AST is a simpler form of the source code that represents the syntactical structure of the code, and SDT is an assembler-like language that closely represents the actual layout of runtime instructions. SDT sort of skips the syntax tree all together. I'll cover SDT in part III. B. Grammar and Language Grammar provides a precise way to specify the syntax (structure or arrangement of composing units) of a language. In grade school we take grammar lessons that teach us to speak and write proper English. They teach us the correct way to form sentences with subjects, predicates, noun phrases, verb phrases, etc. Subjects, predicates, and phrases are some of the composing units of a sentence in English; similarly, if/else statements, assignment statements, and function definitions are some of the composing units of source code, which itself is a single sentence of a particular programming language. There are a very large number of valid English sentences one could compose; likewise, there are a large (probably infinite) number of valid source code programs one could create. If someone says "on the computer she is," we immediately recognize that the sentence is ill-formed. It's structure is invalid, because the noun phrase should proceed the verb phrase. It should be: "She is on the computer." Diagramming is used to validate the sentence, or rather to specify the syntax of it. If you take a look at that diagramming article, you'll see that the model is exactly like an AST. So it goes without saying that parsing, or more formally, “syntactical analysis," has its roots in Linguistics. Moreover, just as in English, programming languages need to be specified in a way that allows us to verify whether a sentence of the language is valid. That's where context-free grammars (CFG) come to into play; they allow us to specify the syntax of a programming language's source code. C. Context-Free Grammars A context-free grammar is a set of rules that specify how sentences can be structured; this set of rules can be defined recursively. All CFGs have (1) a start symbol, (2) a set of non-terminal symbols, (3) a set of terminal symbols, and (4) a set of productions or "re-write rules." The following is a CFG that describes simple mathematical expressions that aren't aware of precedence or associativity rules. expr → expr op expr expr → (expr) expr → -expr expr → id op → * | / | + | - id → a | b | c Note: The division and addition symbols should be bold. Each line is a production (or "rule"). expr, op, id, *, /, +, -, a, b, c are all symbols. The pipe (|) indicates that each symbol can serve as the replacement for the left side of the production, but you can only choose one. When I say “left side of the production" I mean to the left of the arrow. You can see that some of the productions are recursively defined. The start symbol is the symbol for which all sentences in the language can be derived from. It's also where we begin. Usually, the symbol on the left side of the first production is the designated start symbol, but sometimes it's specified explicitly if it's not in the first production. So expr is the start symbol. Non-terminals are symbols that can be replaced by the right side of their productions. They are symbols that represent a set of strings that may contain other non-terminals and terminals. They are a syntactical "variable" or "category" because there are many strings they can be replaced with. Each symbol on the left side is a non-terminal. Terminals are the symbols that can't be re-written. They are the tokens, or basic units, of which strings in the language are composed of. The terminals correspond to the set of tokens returned by the lexer. The bold face symbols are terminals. Here's another simple CFG that describes a few common programming constructs. stmt → if equality_expr then stmt else stmt stmt → do stmtList while equality_expr stmtList → stmt | stmt; stmtList Here's a set of productions that describe the Integer class in part I. This CFG partially describes our notion of a Java class, not just a class named Integer. Spoiler D. Derivations When we apply the productions starting from the start symbol we try to derive a sentence in the language, that is, a string of terminals. a + b * c is a sentence of the language defined by our first CFG above. Similarly, the source code we write is a sentence of some language defined by some CFG. Let's walk through a derivation of the mathematical expression a + c using the first CFG above. - Expand or "reduce" the start symbol, expr. This means replace the non-terminal in question with the appropriate string on the right side of its production. There are several to choose from: expr op expr, (expr), -expr, and id. Pick the one that you think will derive a + c in the least amount of steps. expr op expr seems like the right one, but why? If we look at the expression we can see it that matches up (or will match up in a few steps) with the production exactly. The terminal a is an id, which is an expr; + is an op and c 's case is the same as a's. As you can see a little intuition has to be exercised here. Note that we just did a recursive expansion. The current derivation is as follows: expr → expr op expr I will use the term "expansion" many times throughout this part of the tutorial; what I call an "expansion" is commonly referred to as a "reduction." - We are now working on expr op expr. Expand the first non-terminal from the left. Replace expr with the most appropriate production. Like we said above, since a is an id, we ought to use the production: expr → id. The current derivation becomes: expr → expr op expr → id op expr - We are now working on id op expr. Since id is a non-terminal we expand that instead of moving on to op. id only has one production: id → a | b | c. We can choose between the three. We choose a. The current derivation becomes: expr → expr op expr → id op expr → a op expr Because we keeping expanding the leftmost non-terminal first, we call this a leftmost derivation. - op is now the leftmost non-terminal, so we expand it to *, /, +, or -. We choose op → + . The current derivation becomes: expr → expr op expr → id op expr → a op expr → a + expr By now, you probably understand what's happening. - expr is now the leftmost non-terminal, so expand it to id. expr → expr op expr → id op expr → a op expr → a + expr → a + id - And lastly, we expand id to c. Our full derivation becomes: expr → expr op expr → id op expr → a op expr → a + expr → a + id → a + c And that's it folks! We've ensured the expression is syntactically valid and is therefore a sentence of the language described by our CFG. The final string is all terminals. This must be true for all derivations of any string in the language. If you had any trouble following along, this example should help to clarify the procedure. Suppose the expression was a + d. At step 6, when we try to expand id to d, we fail, because there's no production for that. If the expression was d + a, we would have failed at step 3. If the expression was b % a, we would have failed at step 4. Here's the derivation for ( ( ( -a * b ) - ( c + b ) ) / c ) using the CFG above: expr → ( expr ) → ( expr / expr ) → ( ( expr ) / expr ) → ( ( expr – expr ) / expr ) → ( ( ( expr ) – ( expr ) ) / expr ) → ( ( ( expr * expr ) – ( expr ) ) / expr ) → ( ( ( expr * expr ) – ( expr + expr ) ) / expr ) → ( ( ( -expr * expr ) – ( expr + expr ) ) / expr ) → ( ( ( -id * expr ) – ( expr + expr ) ) / expr ) → . . . . . . → ( ( ( -id * id ) – ( id + id ) ) / id ) → ( ( ( -a * b ) – ( c + b ) ) / c ) And, here's the derivation for our Integer class using the CFG defined in the spoiler above: program → PUBLIC CLASS id LCURLY classBody RCURLY → PUBLIC CLASS ID LCURLY classBody RCURLY → PUBLIC CLASS ID LCURLY declaration RCURLY → PUBLIC CLASS ID LCURLY fieldDeclaration RCURLY → PUBLIC CLASS ID LCURLY type id SEMICOLON RCURLY → PUBLIC CLASS ID LCURLY INT id SEMICOLON RCURLY → PUBLIC CLASS ID LCURLY INT ID SEMICOLON RCURLY The first ID terminal would be associated with the string Integer and second with the string value, which are returned together by the lexer. Let's extend upon our source code CFG (see spoiler) to support simple methods with variable initialization statements. We won't support the notion of an instance variable. program → PUBLIC CLASS id LCURLY classBody RCURLY classBody → declarationList declarationList → declaration declarationList | epsilon declaration → methodDeclaration methodDeclaration → PUBLIC STATIC VOID id LPAREN RPAREN LCURLY methodBody RCURLY methodBody → variableInitializationList variableInitializationList → variableIntializationStatement variableInitializationList | epsilon variableIntializationStatement → type id ASSIGN literal SEMICOLON literal → intLiteral | strLiteral | true | false type → INT | BOOLEAN | STRING intLiteral → INTLITERAL strLiteral → STRLITERAL id → ID Note that epsilon means "nothing" or that there's no match available. So in the sixth production a variableInitializationList can be reduced to nothing, meaning the method didn't have any initialization statements or that we've matched several initializations and there aren't any left. INTLITERAL is a terminal that corresponds to a lexer token returned when an integer literal is matched. Examples of integer literals are -123, 0, 432434, etc. The regular expression is: INTLITERAL = [-0-9][0-9]* STRLITERAL is a terminal that corresponds to a lexer token returned when a string literal is matched. String literals are strings in double quotes: "one", "_two?", "\n\t three". Its regular expression is similar to the one for ID, which I talked about earlier. Now, let's create our new source code: public class IntegerTest { public static void main() { int num = 20; boolean isNegative = false; } public static void toString() { String formattedString = “%1$-7d"; } } Let's derive it! If you pay attention to the non-bold face non-terminals you can capture the essence of the derivation quickly. Spoiler My point in doing this incredibly long leftmost derivation is to show you that the derivation proceeds in the same order as the execution of the program instructions. This is the first important point! We derived the first integer assignment first, not second or third. Then, we derived the boolean assignment second, and so on. As you can see CFG is very powerful, having the ability to describe sentences of a potentially infinite size (as long as your system memory can accommodate it). I could have added 100,000 methods to IntegerTest and still validated its syntax. E. Abstract Syntax Trees An AST is a type of parse tree that's used in source code compilation. It's abstract because minor details in the code like semicolons and braces are omitted. Parse trees that include those details are called concrete syntax trees. Enough information is stored to preserve the meaning of the program. Each tree node represents a grammar symbol. Every node that represents a non-terminal in the tree has a collection of child nodes that are either non-terminals or terminals. The child nodes represent the symbols that were produced from expanding the non-terminal. The leaves in the tree are always terminals and the interior nodes are always non-terminals. Terminal nodes are usually variable identifiers or literals.. This is the second important point. Here's a partial AST for IntegerTest: It just so happens that a preorder tree traversal on our AST visits nodes in the same order as the derivation, so logically it follows that the traversal follows the order in which instructions are executed. This is the third and final important point. And that my friends is the way we generate assembler that preserves the exact order in which high-level instructions are written! We recurse through the AST, generating the corresponding assembler for the node type. Beautiful isn't it? Translating assembler instructions line for line isn't difficult. No parsing is needed. This is essentially what an assembler does. It translates assembly statements to their binary counterparts. The nice thing is that the instructions execute in sequence. 0x1 li $v0, 1 0x2 syscall It's guaranteed that the system call instruction will be executed directly after the load immediate instruction for this program. So an assembler doesn't have to worry about maintaining the order of executing instructions. An assembler literally goes through each line and translates it to machine code. What makes compilation more difficult is that you have to translate a program where high-level instructions jump from one method to another. Line 0: void bar() { Line 1: System.out.println(1); Line 2: } Line 3: void foo() { Line 4: System.out.println(2); Line 5: } I can't just go from line 0 to 5 and translate each statement into a runtime instruction. foo() may never even be called in the program. In short, there isn't a direct translation like with assembler. In assembler, when you see a load immediate instruction you just translate it to 010101011010101010 or whatever the ISA calls for. When you generate assembler from a node in the AST for a method call, there's a lot more to do. You have to save the state of your registers (save the local variables), plop arguments onto the stack (send the method parameters), set stack and frame pointers (don't destroy another method's state!), check the symbol table (how much stack space do I need?), etc. The other nice thing about ASTs is that they can be represented in computer programs. It's just a regular ol' node-based tree. As the parser runs through its parse algorithm, it builds a tree with nodes that are specialized. The visitor pattern is very useful when working with ASTs because it allows the compiler to be extensible (supporting more CPU architectures). An example of AST nodes: class ProgramNode { ClassBodyNode classBody; ProgramNode(ClassBodyNode classBody) { this.classBody = classBody; } void generateMIPSAssembler(FileWriter wtr) { wtr.append(".text\n"); classBody.generateMIPSAssembler(wtr); } } class ClassBodyNode { DeclarationListNode declList; ClassBodyNode(DeclarationListNode declList) { this.declList = declList; } void generateMIPSAssembler(FileWriter wtr) { declList.generateMIPSAssembler(wtr); } } F. Regular Expressions vs. Context-Free Grammars CFG can describe all regular sets, but it's overkill for regular expressions. Regex is a concise and powerful notation for describing patterns. Here's an example of Regex vs. CFG. Our regular set: S = {"ab-", "ab-dd", "ac-", "ac-ddd", . . .} Regex pattern: a(b|c)-d* CFG S → aA A → ( b-B ) | ( c-B ) B → dB | e e – is the empty string Do the derivation if you want, it works. The process involved in creating a parse table is quite complex; it's inefficient to use CFG when an easier array-based regex solution exists. Regex implementations are much, much easier to construct than parsers, as we're about to see. I'm totally disregarding advanced regex features like lookahead, reluctant quantifiers, capturing groups, etc.; but even with those added, parsers are still more complex. Allowing regex to handle lexing allows the compiler to be modular, where front-ends are interchangeable. G. Parsing Methods and Implementations We saw how lexers were built programmatically in the last section, and in the future parts of this tutorial we'll see how to programmatically generate assembler. In this part we saw how to define a CFG for the beginnings of a programming language and how to derive a given sentence while building an AST for it. However, all of what we've learned about parsing is useless if we can't do it programmatically. There are many parsing methods, each of which require a fair bit of detailed explanation, so we're only going to hit the tip of the iceberg, mainly focusing on top-down parsing. There are two types of parsing methods: top-down and bottom-up. Everything I've showed you up to this point is an example of top-down parsing. "Top-down" is pretty much self-explanatory. From left to right, we drill down through each non-terminal until we get to a terminal. We also build our tree from the root node down to the leaves in a top-down fashion. It's important to note that we drill down from left to right replacing the leftmost non-terminal first. The definitive meaning of top-down parsing is “an attempt to find a leftmost derivation." In bottom-up parsing we are doing a rightmost derivation, where we replace the rightmost non-terminal first. Ambiguity Ambiguous grammars are those in which a string of the language has more than one parse tree. This is problematic because it may be hard to interpret the intended meaning of the string. Here's an example from Wikipedia's entry on ambiguous grammars. x * y; That C statement can be interpreted as the multiplication of two variables, x and y, or as the declaration of a variable y whose type is a pointer to x. To resolve the conflict the compiler must locate y's type information in the symbol table. If it's a numerical type the statement is interpreted as an expression. Generally speaking, ambiguity is an unwanted feature of any grammar and may pose a threat to the correctness of both top-down and bottom-up parsers. Different parsers handle it with varying efficacy. In spite of all this, ambiguity isn't always a problem. It's possible to generate a non-ambiguous language from an ambiguous grammar. Even if there are two parse trees that generate a string, as long as it has one intended meaning there's no problem. Some parser generators allow specifying precedence and associativity rules to remove any ambiguity. Bottom-Up Parsing In bottom-up parsing the derivation starts from the string of terminals (our sentence) . We try to derive the start symbol of our CFG. It's essentially a top-down derivation backwards. Initially, instead of replacing a non-terminal with another non-terminal or terminal (drilling down), we replace a terminal with non-terminal (drilling up). At certain points we may even replace several non-terminals with one non-terminal. Since the derivation is the exact reverse of a leftmost derivation, we are then replacing non-terminals from right to left (a rightmost derivation). When we make a replacement we create a node that becomes the parent of some other node instead of its child. Top-Down Parsing There are several problems with top-down parsing. (1) Left-recursion can lead to infinite parsing loops, so it must be eliminated. Left recursion in a CFG production occurs when the non-terminal on the left side appears first on the right side of the arrow. For some bad input, we might find ourself continuously expanding the same non-terminal. At the beginning of this tutorial we had expr → expr op expr expr → (expr) That's left recursion. There are simple algorithms to remove it, but the CFG becomes twice as long in many cases. (2) Top-down parsing may involve backtracking. Backtracking is the act of climbing back up the derivation (the parse), reversing everything you've done to try another derivation path. We end up re-scanning the input as well. If you're inserting information into a symbol table (explained later) as the parse proceeds, everything has to be removed. That's pretty costly in a 10 million line application. The need for backtracking can be eliminated by parsing with lookahead. Note that backtracking isn't restricted to top-down parsers. There are backtracking LR parsers as well. Finally, (3) the order in which we choose non-terminal expansions can cause valid inputs to be rejected without information as to why. Types of Top-Down Parsers There are two types of top-down parsers: recursive-descent parsers and predictive parsers. A recursive-descent parser consists of a set of functions that construct a leftmost derivation of the input. The functions don't actually have to be recursive, but they can be. Each function implements a grammar rule. RD parsers may need to implement backtracking. Below is an example of a grammar that requires backtracking. S → cAd A → ab | a The input is cad. After matching c, when we go to expand A and we have a as the next character in the input. We don't know exactly whether the alternative ab or a will be chosen without looking at the next character in the input after a, which is d. We have to look ahead two characters in the input to know the right alternative to choose, but we only have access to a. We choose the first alternative expansion, ab. We match a in the alternative and go the next input token, d. We then try to match b in the alternative, but the next token is d, so we have to back track and choose a as the alternative. To implement backtracking in the code we have to save a pointer to a previous place in the input before we try an expansion and possibly remove information we have saved. It's costly when your deep into a parse of many lines of source code. A predictive parser is a recursive-descent parser that needs no backtracking. It can predict the derivation path it'll take by specifying a certain amount of lookahead. Lookahead is the number of tokens in the input the parser needs to examine to decide which non-terminal expansion to take. This type of parser only works for LL(k) grammars, where k is the amount of lookahead the parser needs to make its decision. Lookahead is looking at a few more input items to determine the correct path to take. An LL(k) grammar must not be ambiguous or contain left recursion. This is a major restriction for compiler designers, so LR parsers are preferred. An LL parser is a predictive parser that reads the input from left to right and constructs a leftmost derivation on LL(k) grammars. Lets go back to one of the CFGs from before. program → PUBLIC CLASS id LCURLY classBody RCURLY classBody → declaration declaration → fieldDeclaration | methodDeclaration fieldDeclaration → type id SEMICOLON methodDeclaration → PUBLIC VOID id LPAREN RPAREN SEMICOLON type → INT | BOOLEAN | STRING id → ID This grammar only allows for one class declaration, so you can either have a member field or a member function signature, but not both. Below is a code snippet for a recursive-descent LL parser for the above grammar. It directly mimics the CFG. The code is an LL(1) parser since we only use the next token in the input to make our expansion decisions. As you can see we don't need to save a pointer to a place in the input or logic to backtrack and try another path through the derivation. I've left out code to build the tree, but I've commented where you'd insert the tree-building statements. The input is formatted for easy tokenization to keep things simple. Spoiler Easy enough. In parts IV and VI I will add in the tree building statements, so that we have an AST to experiment with. You'll be able to implement your own semantic analysis and code generation from the tree. It's impractical to think this is an effective way to parse sentences for all grammars. The parsing logic is hard coded. We need something dynamic that we can load with parsing logic. We need a table-based parser. Table-Based Parsing A more flexible way of implementing a parser is to make it table-based, where we introduce a parsing table (a 2d array) and a stack. Each entry in the parse table represents a reduce action, and each entry on the stack is a symbol. Here's a simple run-down of a table-based LL(1) parsing algorithm: The bottom of the stack starts with $ and the grammar's start symbol is on top of that. Look at the symbol on the top of stack, we'll call that X, and then look at the current token of the input, we'll call that a. If X is a terminal and it equals a, pop X off the stack and remove a from the input. If it doesn't equal a, an occur has occurred. If X is a non-terminal, retrieve the reduction from the table and swap it with X. Table(X, a) returns the string that X is reduced to when a is the next token in the input. That string is one of the alternatives on the right side of the production. The string of symbols are actually thrown on the stack backwards since we're doing a leftmost derivation. If there's no entry in the table for X and a , an error has occurred. Repeat the steps until X equals $, where there are no more stack symbols to be processed. That's literally the entire algorithm. If that example was difficult to understand, here's another example showing how the algorithm works. So how do we compute the parse table? You have to construct the first and follow sets. The input to these algorithms are a CFG. You can find the algorithms here. They aren't too complicated. The important thing to know is that the parsing algorithm utilizes a table that's dynamically generated from the output of the first and follow sets, which can be programmatically generated from a grammar specification. No more hard-coding your grammar rules! And no more having to write code to support more language syntax! This gives rise to what we call the parser generator. This is the sane way to create a complex parser. Types of Bottom-Up Parsers One form of bottom-up parsing is called shift-reduce parsing. This method of parsing uses a table of actions and a stack of symbols. The Wikipedia entry has an easy-to-understand example. It's a relatively simple algorithm that only supports a small class of grammars. The major disadvantage with shift-reduce parsers is that they don't support associativity or precedence rules, nor do they handle ambiguous grammars well. They are used to describe operator grammars and are commonly used to parse mathematical expressions.Operator-precedence parsing is a bottom-up shift-reduce parser that supports defining precedence rules for grammars. Perl 6 and GCC parsers use some form operator-precedence parsing for optimization purposes. LR Parsing LR parsers are a class of parsers that scan the input from left to right, but constructs a rightmost derivation. It's a bottom-up parser because it constructs a rightmost derivation instead of a leftmost derivation like the top-down parsers. LR(k) parsers require k lookahead. They are deterministic. LR parsers have some advantages over their counterparts: - They can handle virtually all CFG grammars (including left recursive ones), giving them the ability to handle many more languages than LL parsers. - They have better error reporting than backtracking parsers. LR parsers consist of a stack of symbols, an input buffer, and a parser driver but also have a few more components. The parse table for an LR parser is filled with states. There is also an action and a goto table. I said I wouldn't go to deeply into the details of bottom-up parsers, because it would be very time consuming, so I'll just give a high-level overview. There are three general types of LR parsers: SLR parsers, Canonical LR parsers, and LALR parsers. SLR parsers are the simplest to implement, but fail to produce tables for certain grammars. Canonical LR parsers are the most powerful of the three but are also the hardest to implement. They cover the widest range of grammars. Lastly, LALR parsers cover the middle ground: they are between SLR and Canonical parsers in complexity and coverage but can handle grammars for most programming languages. GLR parsers are an extension of LR parsers that use a form of backtracking to handle ambiguous grammars. They work by forking sub-parsers at any point in the parse where they can't decide which transition to take. If any match in the sub-path fails, that sub-parse is thrown away and the next sub-parse is tried. If several sub-parses pass, the parser accepts both. In this sense, backtracking takes on a more general meaning: building up candidates as possible solutions and discarding them as soon as they fail. It's worth mentioning that there are backtracking LR parsers as well. Backtracking parsers go through greater troubles to give the exact location of a syntax error, because they have to try many candidates before they're absolutely sure that the string isn't valid. The parser may have to record each possible syntax error and include logic to figure out the correct one upon failure. When deterministic parsers fail to match a token, the process as a whole fails at that point and the location of the failure is known at that point. Unlike the table-based top-down parser, an LR parser uses a table of states rather than productions. The LR parsing algorithm jumps from state to state. It's essentially a deterministic finite automaton. The algorithm is fairly simple, but constructing the parse tables is not. To construct an LR parse table you have to turn the grammar into a DFA. From the DFA, you construct the parse table. The DFA is able to recognize prefixes in the grammar, and that allows the parser to determine what actions it needs to take without having to scan down the stack to make decisions. This is the “power" of LR parsers. To create the DFA you must perform the canonical sets-of-items algorithm, which depends on 3 other algorithms: augmenting grammars, closure, and goto. The inputs to these algorithms are a CFG. The algorithms are somewhat complicated. They are certainly harder to understand than those of a table-based predicative parser. Here's a overview of LR parse tables. LR parsers are hard to implement by hand because the sets-of-items construction will result in LR tables with several thousand states. The parse table for a typical programming language will have 20,000 entries; that's 20 KB! It gets messy quickly, even for very small grammars, so parser generators are normally used to create the parse tables. Generators are implementations of the aforementioned table-construction algorithms, which of course can do things much more efficiently than humans. Saving space is particularly important in constructing parse tables because many table entries (array elements) will be empty. One might use linked lists instead. There are also many duplicate rows that can be eliminated with the use of pointers, where you could compress many rows into one long row whose elements contain the index of the duplicate row. Parser Generators Parser generators are fantastic, and they're easy to use! You just feed them a specification file with a bunch of CFG rules, and it spits out a parser in your language of choice. Usually you can embed code into the specification to specify how you want the parser to build your AST. There are also ways to specify the precedence and associativity rules. And furthermore, they can usually handle ambiguous grammars. Yacc was one of the earlier parser generators developed and was the default generator on UNIX systems. Two popular generators based off Yacc are GNU Bison and CUP. Both produce LALR parsers. GNU Bison is probably the most popular generator today. It can produce parsers in C, C++, and Java code. It's been used to create YARV (Ruby interpreter), Zend parser (PHP scripting engine), Bash Shell, and GCC (initially). ANTLR is another generator and probably is the most popular of them all. The ANTLR package has some really nice tools that make easing into compiler construction a lot more comfortable. CUP, formerly known as JCUP, is a parser generator for Java. I found it particularly easy to use and I would recommend it to anyone looking to build a Java parser or compiler. I had planned on showing a few examples of CFG for a simple language, but I ended up writing a post that goes somewhat in depth on how to do so using CUP. All the CFGs I wrote above can be translated into a CUP spec with minimal effort. Bison and CUP require a lexer to produce a parser, usually Flex and JFlex, respectively. I covered how to use lexer generators in part I. The JFlex distribution has a few really good examples for generating lexers and parsers. H. Conclusion Luckily, we don't have to concern ourselves at all with how parsers are built. We focus only on specifying the CFG for our language and using a generator to create our parser. Creating an AST is an elegant way to represent the structure of source code that leaves the compiler open to optimization and code generation. To recap, we've covered the following important points: - A derivation proceeds in the same order as the execution of the program instructions. -. - A preorder tree traversal on our AST visits nodes in the same order as the derivation, so logically it follows that the traversal follows the order in which instructions are executed. - A table-based parsing algorithm utilizes a table that's dynamically generated from the output of the first and follow sets, which can be programmatically generated from a grammar specification. - Parser generators are implementations of the table-construction algorithms. If your interested, I found this awesome set of lecture notes for the dragon book. In part III, we will take a short look at the wonderful world of syntax directed translation. Sources Alfred V. Aho, Jeffrey D. Ullman. Principles of Compiler Design. Reading: Addison-Wesley, 1977. Wikipedia: The Free Encyclopedia. Wikimedia Foundation, Inc. 22 July 2004. Web. 10 Aug. 2004. This post has been edited by blackcompe: 25 September 2014 - 03:32 AM
https://www.dreamincode.net/forums/topic/268945-an-introduction-to-compiler-design-part-ii-parsing/
CC-MAIN-2020-05
refinedweb
5,821
64
Richard Lewis wrote: > On Tuesday 14 November 2006 14:17, Jorey Bump wrote: >> Richard Lewis wrote: >>>? >>? I don't think so. Directives in the Location context should override the directives higher up in the VirtualHost context. Try something like this: <Location /edit> PythonDebug On AuthType Basic AuthName "Restricted" Require valid-user PythonAuthenHandler foo.bar </Location> foo/bar.py looks something like this: from mod_python import apache def authenhandler(req): pw = req.get_basic_auth_pw() user = req.user if user == "spam" and pw == "eggs": return apache.OK else: return apache.HTTP_UNAUTHORIZED As you are working in an earlier Apache processing phase, this will work to protect all resources under /edit, even if they are not handled by mod_python. It's a powerful thing. Jim
http://modpython.org/pipermail/mod_python/2006-November/022604.html
CC-MAIN-2017-51
refinedweb
121
61.43
?xml:namespace> According to Robert Simmons, head of rubber and tyre research at LMC International, the replacement ratio dropped to 0.90 in 2009 in the wake of the global recession. There was a slight uptick in 2010-11, but today it has fallen again to about 0.92. "That doesn't sound like much," Simmons told the second annual ICIS Butadiene & Derivatives Conference on Wednesday, "but it's a big drop." And it is a drop that the tyre industry -- and petrochemical makers that trade in butadiene (BD) and styrene-butadiene-rubber (SBR) -- should get used to for a variety of reasons, he said. First off, people are driving less. This is especially true in the EU and the "From 2001 to 2009, the average annual number of vehicle-miles travelled by young people (16 to 34 years old) decreased from 10,300 miles to 7,900 miles per capita – a drop of 23%," the group said in its study. "The trend away from steady growth in driving is likely to be long-lasting – even once the economy recovers," said Benjamin Davis and Tony Dutzik, authors of the study. As economies have slowed around the world, so too has commercial freight, Simmons said during his presentation. For instance, commercial tyres sales, which account for about 60% of total tyre sales, declined by 20% in the EU in 2012. The same is true for the Another ominous sign for US and European tyre makers, Simmons said, is the fact that by 2016, replacement-tyre sales in emerging markets will surpass sales in developed markets. Again, it is expected that drivers will, on average, drive fewer miles per year than Americans and Europeans did over the past half century. "It's a huge shift in driving habits that the tyre makers must factor into future demand," Simmons said. "Can that trend continue?" Simmons asked. "For replacement vehicles, yes. For [automakers], no. They want tyre suppliers close to the factories." Simmons expects about 3% annual growth in worldwide tyre sales, but much of it will be in developing markets where it is expected that consumers will drive less, thus replacing tyres less often. "That is what the industry has to get its head around," he said.
http://www.icis.com/resources/news/2013/09/11/9705162/tyre-makers-need-to-adjust-to-new-driving-habits-consultant/
CC-MAIN-2014-49
refinedweb
374
69.21
Can anyone please explain to me how to change the insertion point of the text ("Hello, World!") to wherever the cursor happens to be whenever the plugin is activated? import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!") You will use view.sel() to get the cursors. This returns a list of regions, since multiple cursors are supported . Anyways, if you want to assume the first cursor, and the beginning of the region you can do the following. import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, self.view.sel()[0].begin(), "Hello, World!") Probably worthwhile to take a look at the api if you haven't already. ST2: sublimetext.com/docs/2/api_reference.htmlST3: sublimetext.com/docs/3/api_reference.html Thank you -- here are my lessons learned so far: Variables are set AFTER self.view.insert, not in the middle of. Python is sensitive to indentations in the form of white space, with incremental white space indentations. Saving a file with the Python console open helps to debug. To try out the plugin in the Python console, I need to be aware that this syntax is no longer supported in ST2 [view.runCommand('example')] -- instead, I should use: view.run_command('example') To utilize dir() in the Python console, there are many variables that could be inserted in between the parenthesis -- I will need to read more documentation regarding the various usages. Examples of code that will work in the Sublime Text plugins can be found in unrelated Python scripts, because the language is the same.docs.python.org/2/library/os.path.html You must be looking at old versions of the api documentation. You want view.run_command. Not view.runCommand. Check the links I provided. Also, as kind of a getting started for plugins, consider going through the following tutorial (link). You may also want to go through some general python tutorials first anyways. Diving straight into plugin development without some understanding of the language can make it more difficult than it needs to be. "dir(variable)" will list the attributes (well I guess it really depends on how the dir method was implemented for that class) for that class. Normally this will show you things like methods and variables associated with that class. As a future reference, you may want to look at the porting guide, for when you decided to write plugins for ST3 (link). There are some changes to the ST3 api, when compared to ST2, so you should probably look at that as well. This tutorial has been extremely helpful. I have updated my list of lessons learned so far. Thank you very much!
https://forum.sublimetext.com/t/chage-hello-world-to-insert-at-cursor-position/9270/5
CC-MAIN-2016-07
refinedweb
455
59.19
Advanced Plugin Testing¶ The complete guide to writing tests for your plugins. Why Write Tests?¶ Why should I write tests for my plugin? Here’s why. For those of you asking “Why should I write tests for my plugin? I tried it out, and it works!”, read on. For those of you who already realize that Testing is Good (TM), skip to the next section. Here are a few quick reasons why to test your Supybot plugins. - When/if we rewrite or change certain features in Supybot, tests make sure your plugin will work with these changes. It’s much easier to run supybot-test MyPlugin after upgrading the code and before even reloading the bot with the new code than it is to load the bot with new code and then load the plugin only to realize certain things don’t work. You may even ultimately decide you want to stick with an older version for a while as you patch your custom plugin. This way you don’t have to rush a patch while restless users complain since you’re now using a newer version that doesn’t have the plugin they really like. - Running the automated tests takes a few seconds, testing plugins in IRC on a live bot generally takes quite a bit longer. We make it so that writing tests generally doesn’t take much time, so a small initial investment adds up to lots of long-term gains. - If you want your plugin to be included in any of our releases (the core Supybot if you think it’s worthy, or our supybot-plugins package), it has to have tests. Period. For a bigger list of why to write unit tests, check out this article: and also check out what the Extreme Programming folks have to say about unit tests: Plugin Tests¶ How to write tests for commands in your plugins. Introduction¶ This tutorial assumes you’ve read through the plugin author tutorial, and that you used supybot-plugin-create to create your plugin (as everyone should). So, you should already have all the necessary imports and all that boilerplate stuff in test.py already, and you have already seen what a basic plugin test looks like from the plugin author tutorial. Now we’ll go into more depth about what plugin tests are available to Supybot plugin authors. Plugin Test Case Classes¶ Supybot comes with two plugin test case classes, PluginTestCase and ChannelPluginTestCase. The former is used when it doesn’t matter whether or not the commands are issued in a channel, and the latter is used for when it does. For the most part their API is the same, so unless there’s a distinction between the two we’ll treat them as one and the same when discussing their functionality. The Most Basic Plugin Test Case¶ At the most basic level, a plugin test case requires three things: - the class declaration (subclassing PluginTestCase or ChannelPluginTestCase) - a list of plugins that need to be loaded for these tests (does not include Owner, Misc, or Config, those are always automatically loaded) - often this is just the name of the plugin that you are writing tests for - some test methods Here’s what the most basic plugin test case class looks like (for a plugin named MyPlugin): class MyPluginTestCase(PluginTestCase): plugins = ('MyPlugin',) def testSomething(self): # assertions and such go here Your plugin test case should be named TestCase as you see above, though it doesn’t necessarily have to be named that way (supybot-plugin-create puts that in place for you anyway). As you can see we elected to subclass PluginTestCase because this hypothetical plugin apparently doesn’t do anything channel-specific. As you probably noticed, the plugins attribute of the class is where the list of necessary plugins goes, and in this case just contains the plugin that we are testing. This will be the case for probably the majority of plugins. A lot of the time test writers will use a bot function that performs some function that they don’t want to write code for and they will just use command nesting to feed the bot what they need by using that plugin’s functionality. If you choose to do this, only do so with core bot plugins as this makes distribution of your plugin simpler. After all, we want people to be able to run your plugin tests without having to have all of your plugins! One last thing to note before moving along is that each of the test methods should describe what they are testing. If you want to test that your plugin only responds to registered users, don’t be afraid to name your test method testOnlyRespondingToRegisteredUsers or testNotRespondingToUnregisteredUsers. You may have noticed some rather long and seemingly unwieldy test method names in our code, but that’s okay because they help us know exactly what’s failing when we run our tests. With an ambiguously named test method we may have to crack open test.py after running the tests just to see what it is that failed. For this reason you should also test only one thing per test method. Don’t write a test method named testFoobarAndBaz. Just write two test methods, testFoobar and testBaz. Also, it is important to note that test methods must begin with test and that any method within the class that does begin with test will be run as a test by the supybot-test program. If you want to write utility functions in your test class that’s fine, but don’t name them something that begins with test or they will be executed as tests. Including Extra Setup¶ Some tests you write may require a little bit of setup. For the most part it’s okay just to include that in the individual test method itself, but if you’re duplicating a lot of setup code across all or most of your test methods it’s best to use the setUp method to perform whatever needs to be done prior to each test method. The setUp method is inherited from the whichever plugin test case class you chose for your tests, and you can add whatever functionality you want to it. Note the important distinction, however: you should be adding to it and not overriding it. Just define setUp in your own plugin test case class and it will be run before all the test methods are invoked. Let’s do a quick example of one. Let’s write a setUp method which registers a test user for our test bot: def setUp(self): ChannelPluginTestCase.setUp(self) # important!! # Create a valid user to use self.prefix = 'foo!bar@baz' self.feedMsg('register tester moo', to=self.nick, frm=self.prefix)) m = self.getMsg(' ') # Response to registration. Now notice how the first line calls the parent class’s setUp method first? This must be done first. Otherwise several problems are likely to arise. For one, you wouldn’t have an irc object at self.irc that we use later on nor would self.nick be set. As for the rest of the method, you’ll notice a few things that are available to the plugin test author. self.prefix refers to the hostmask of the hypothetical test user which will be “talking” to the bot, issuing commands. We set it to some generically fake hostmask, and then we use feedMsg to send a private message (using the bot’s nick, accessible via self.nick) to the bot registering the username “tester” with the password “moo”. We have to do it this way (rather than what you’ll find out is the standard way of issuing commands to the bot in test cases a little later) because registration must be done in private. And lastly, since feedMsg doesn’t dequeue any messages from the bot after being fed a message, we perform a getMsg to get the response. You’re not expected to know all this yet, but do take note of it since using these methods in test-writing is not uncommon. These utility methods as well as all of the available assertions are covered in the next section. So, now in any of the test methods we write, we’ll be able to count on the fact that there will be a registered user “tester” with a password of “moo”, and since we changed our prefix by altering self.prefix and registered after doing so, we are now identified as this user for all messages we send unless we specify that they are coming from some other prefix. The Opposite of Setting-up: Tearing Down¶ If you did some things in your setUp that you want to clean up after, then this code belongs in the tearDown method of your test case class. It’s essentially the same as setUp except that you probably want to wait to invoke the parent class’s tearDown until after you’ve done all of your tearing down. But do note that you do still have to invoke the parent class’s tearDown method if you decide to add in your own tear-down stuff. Setting Config Variables for Testing¶ Before we delve into all of the fun assertions we can use in our test methods it’s worth noting that each plugin test case can set custom values for any Supybot config variable they want rather easily. Much like how we can simply list the plugins we want loaded for our tests in the plugins attribute of our test case class, we can set config variables by creating a mapping of variables to values with the config attribute. So if, for example, we wanted to disable nested commands within our plugin testing for some reason, we could just do this: class MyPluginTestCase(PluginTestCase): config = {'supybot.commands.nested': False} def testThisThing(self): # stuff And now you can be assured that supybot.commands.nested is going to be off for all of your test methods in this test case class. Temporarily setting a configuration variable¶ Sometimes we want to change a configuration variable only in a test (or in a part of a test), and keep the original value for other tests. The historical way to do it is: import supybot.conf as conf class MyPluginTestCase(PluginTestCase): def testThisThing(self): original_value = conf.supybot.commands.nested() conf.supybot.commands.nested.setValue(False) try: # stuff finally: conf.supybot.commands.nested.setValue(original_value) But there is a more compact syntax, using context managers: import supybot.conf as conf class MyPluginTestCase(PluginTestCase): def testThisThing(self): with conf.supybot.commands.nested.context(False): # stuff Note Until stock Supybot or Gribble merge the second syntax, only Limnoria will support it. Plugin Test Methods¶ The full list of test methods and how to use them. Introduction¶ You know how to make plugin test case classes and you know how to do just about everything with them except to actually test stuff. Well, listed below are all of the assertions used in tests. If you’re unfamiliar with what an assertion is in code testing, it is basically a requirement of something that must be true in order for that test to pass. It’s a necessary condition. If any assertion within a test method fails the entire test method fails and it goes on to the next one. Assertions¶ All of these are methods of the plugin test classes themselves and hence are accessed by using self.assertWhatever in your test methods. These are sorted in order of relative usefulness. - assertResponse(query, expectedResponse) - Feeds query to the bot as a message and checks to make sure the response is expectedResponse. The test fails if they do not match (note that prefixed nicks in the response do not need to be included in the expectedResponse). - assertError(query) - Feeds query to the bot and expects an error in return. Fails if the bot doesn’t return an error. - assertNotError(query) - The opposite of assertError. It doesn’t matter what the response to query is, as long as it isn’t an error. If it is not an error, this test passes, otherwise it fails. - assertRegexp(query, regexp, flags=re.I) - Feeds query to the bot and expects something matching the regexp (no m// required) in regexp with the supplied flags. Fails if the regexp does not match the bot’s response. - assertNotRegexp(query, regexp, flags=re.I) - The opposite of assertRegexp. Fails if the bot’s output matches regexp with the supplied flags. - assertHelp(query) - Expects query to return the help for that command. Fails if the command help is not triggered. - assertAction(query, expectedResponse=None) - Feeds query to the bot and expects an action in response, specifically expectedResponse if it is supplied. Otherwise, the test passes for any action response. - assertActionRegexp(query, regexp, flags=re.I) - Basically like assertRegexp but carries the extra requirement that the response must be an action or the test will fail. Utilities¶ - feedMsg(query, to=None, frm=None) - Simply feeds query to whoever is specified in to or to the bot itself if no one is specified. Can also optionally specify the hostmask of the sender with the frm keyword. Does not actually perform any assertions. - getMsg(query) - Feeds query to the bot and gets the response. Other Tests¶ If you had to write helper code for a plugin and want to test it, here’s how. Previously we’ve only discussed how to test stuff in the plugin that is intended for IRC. Well, we realize that some Supybot plugins will require utility code that doesn’t necessarily require all of the overhead of setting up IRC stuff, and so we provide a more lightweight test case class, SupyTestCase, which is a very very light wrapper around unittest.TestCase (from the standard unittest module) that basically just provides a little extra logging. This test case class is what you should use for writing those test cases which test things that are independent of IRC. For example, in the MoobotFactoids plugin there is a large chunk of utility code dedicating to parsing out random choices within a factoid using a class called OptionList. So, we wrote the OptionListTestCase as a SupyTestCase for the MoobotFactoids plugin. The setup for test methods is basically the same as before, only you don’t have to define plugins since this is independent of IRC. You still have the choice of using setUp and tearDown if you wish, since those are inherited from unittest.TestCase. But, the same rules about calling the setUp or tearDown method from the parent class still apply. With all this in hand, now you can write great tests for your Supybot plugins!
http://doc.supybot.aperio.fr/en/latest/develop/advanced_plugin_testing.html
CC-MAIN-2020-10
refinedweb
2,458
60.95
Is there something similar to @import in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file? It is possible to dynamically generate a JavaScript tag and append it to HTML document from inside other JavaScript code. This will load targeted JavaScript file. function includeJs(jsFilePath) { var js = document.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; document.body.appendChild(js); } includeJs("/path/to/some/file.js"); Maybe you can use this function that I found page How do I include a JavaScript file in a JavaScript file?: function include(filename) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; head.appendChild(script) } There isn't any import, include or require in JavaScript, but there are two main ways to achieve what you want: 1 - You can load it with an Ajax call and then use eval. This is the most straightforward way, but it's limited to your domain because of the JavaScript safety settings, and using eval is opening the door to bugs and hacks. 2 - Add a script tag with the script URL in the HTML. This is definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the <script /> tag in the head of the web page, or at the bottom of the body. Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading. Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example: function loadScript(url,); } Then you write the code you want to use AFTER the script is loaded in a lambda function: var myPrettyCode = function() { // Here, do what ever you want }; Then you run all that: loadScript("my_lovely_script.js", myPrettyCode); OK, I got it. But it's a pain to write all this stuff. Well, in that case, you can use as always the fantastic free jQuery library, which let you do the very same thing in one line: $.getScript("my_lovely_script.js", function(){ alert("Script loaded and executed."); // Here you can use anything you defined in the loaded script }); type="text/javascript" src="' + script + '">< type="text/javascript" src="' + script + '"></script>'); import_js_imported.push(script); } } }); })(jQuery); So all you would need to do to import JavaScript is: $.import_js('/path_to_project/scripts/somefunctions.js'); I also made a simple test for this at.(); I came to this question because I was looking for a simple way to maintain a collection of useful JavaScript plugins. After seeing some of the solutions here, I came up with this: 1) Set up a file called "plugins.js" (or extentions.js or what have you). Keep your plugin files together with that one master file. 2)('<script src="js/plugins/' + this + '.js"></script>'); }); 3) manually call just the one file in your head: <script src="js/plugins/plugins.js"></script> js); } This is perhaps the biggest weakness of Javascript in my opinion. Its caused me no end of problems over the years with dependency tracing. Anyhow it does appear that the only practical solution is to use script includes in the HTML file and thus horribly making your JS dependent upon the user including the source you need and making reuse unfriendly. Sorry if this comes across as a lecture ;) Its a bad habit of mine, but I want to make a point. The problem comes back to the same as everything else with the web, the history of Javascript. It really wasn't designed to be used in the widespread manner its used in today. Netscape made a language that would allow you to control a few things but didn't envisage its widespread use for so many things as it is put to now and for one reason or another its expanded from there, without addressing some of the fundamental weaknesses of he original strategy. Its not alone of course, HTML wasn't designed for the modern webpage, it was designed to be a way of expressing the logic of a document, so that readers (browsers in the modern world) could display this in an applicable form that was within the capabilities of the system and it took years for a solution (other than the hacks of MS and Netscape) to come along. CSS solves this problem but it was a long time coming and even longer to get people to use it rather than the established BAD techniques, it happened though, praise be. Hopefully Javascript (especially now its part of the standard) will develop to take on board the concept of proper modularity (as well as some other things) as every other (extant) programming language in the world does and this stupidity will go away, until then you just have to not like it and lump it I'm afraid. Or rather than including at run time, use a script to concatenate prior to upload. I use Sprockets (I don't know if their are others). You build your JS in separate files and include comments that are processed by the Sprockets engine as includes. For Dev you can include files sequentially, then for production merge them...:. ... There is a good news for you. Very soon you will be able to load javascript easily. It will become a standard way of importing modules of javascript and will be part of core javascript itself. You simply have to write import cond from 'cond.js'; to load a macro named cond from a file cond.js So you don't have to rely upon any javascript framework nor you have to explicitly make AJAX calls Refer to the links below var js = document.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; document.body.appendChild(js); Now, I may be totally misguided, but here's what I've recently started doing... Start and end your JavaScript files with a carriage return, place in the PHP script, followed by one more carriage return. The JavaScript comment "//" is ignored by PHP so the inclusion happens anyways. var s=["Hscript.js","checkRobert.js","Hscript.js"]; for(i=0;i<s.length;i++){ var script=document.createElement("script"); script.type="text/javascript"; script.src=s[i]; document.getElementsByTagName("head")[0].appendChild(script) }; var s=['Hscript.js','checkRobert.js','Hscript.js']; for(i=0;i<s.length;i++){ var script = document.createElement('script'); script.type = 'text/javascript'; script.src = s[i]; document.getElementsByTagName("head")[0].appendChild(script); } What's wrong with something like the following? xhr = new XMLHttpRequest(); xhr.open("GET", "/soap/ajax/11.0/connection.js", false); xhr.send(); eval(xhr.responseText); I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: // -----); }; I did: var require = function (src, cb) { cb = cb || function () {}; var newScriptTag = document.createElement('script'), firstScriptTag = document.getElementsByTagName('script')[0]; newScriptTag.src = src; newScriptTag.async = true; console.log(newScriptTag) newScriptTag.onload = newScriptTag.onreadystatechange = function () { (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb()); }; firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag); } Works great and uses no page-reloads for me. Tried that AJAX thing. It doesn't really work. Most of solutions shown here imply dynamical loading. I was searching instead for a compiler which assemble all the depended files into a single output file. The same as less/sass preprocessors deal with CSS @import at-rule. Since I didn't find anything decent of this sort, I wrote a simple tool solving the issue. So here is the compiler which replace $import("file-path") with the requested file content securely. Here is the corresponding GRUNT plugin On jQuery master branch they simply concatenate atomic source files into a single one starting with intro.js and ending with outtro.js. That doesn't suite(){} } }; function include(js) { document.writeln("<script src=" + js + "><" + "/script>"); } This script will add JavaScript file to the top of any other <script> tag: (function () { var li = document.createElement('script'); li.type = 'text/javascript'; li.src= ""; li.async=true; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(li, s); })(); I also wrote a JavaScript dependency manager for Java web apps: JS-Class-Loader. Here is a Grunt plugin allowing you to use @import "path/to/file.js"; syntax in any file including JavaSript files. It can be paired with uglify or watch or any other plugin. Can be installed with npm install: Let me know if any questions. If you want in pure JavaScript, you can use document.write. document.write('<script src="myscript.js" type="text/javascript"></script>'); If you use the jQuery library, you can use the $.getScript method. $.getScript("another_script.js"); Surprisingly no one mentioned. Here is a synchronous version without jQuery: function myRequire( url ) { var ajax = new XMLHttpRequest(); ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous ajax.onreadystatechange = function () { var script = ajax.response || ajax.responseText; if (ajax.readyState === 4) { switch( ajax.status) { case 200: eval.apply( window, [script] ); console.log("script loaded: ", url); break; default: console.log("ERROR: script not loaded: ", url); } } }; ajax.send(null); } The @import syntax for achieving "css-like" js importing is possible using a tool such as Mixture via their special .mix file type (see here). I imagine the application simply uses one of the aforementioned methods "under the hood," app-specific file type (somewhat disappointing, agreed). Nevertheless, figured the knowledge might be helpful for others. I am adding the statement you have mentioned in the top of my .js file. document.write('<scr'+'ipt</scr'+'ipt>'); but why are you include? You don't need an include. You can just add the code to the existing JavaScript file. Or you can call js files from the HTML file. spec. Alternatively, as the second highest voted answer to your question highlights, RequireJS can also handle including scripts inside a Web Worker (likely calling importScripts itself but with a few other useful features). There are a lot of potential answers for this questions. My answer is obviously based on a number of them. Thank you for all the help..) ex: its anymore. NOTE: you must use this only while the page is loading, otherwise you get a blank screen. In other words, always place this before / outside of document.ready. I have not tested using this after the page is loaded in a click event or anything like that, but it's js; Here is the beautiful JavaScript Snippet from Google Advanced Configuration to asynchronously loads their analytics.js library onto the page. (function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o),m=s.getElementsByTagName('head')[0];a.async=1;a.src=g; m.appendChild(a); })(window,document,'script','//','ga'); ga('create', 'UA-XXXXXXX-X', 'example.com'); ga('send', 'pageview'); SO, if you're using Javascript with your website, and are loading the .js files with script tags, you can simply load multiple script files using seperate tags, and then you can use functions, global variables, arrays, and objects from one in the others. Personally, I do that to keep my Javascript and Jquery seperate. I had a simple issue, but baffled by responses to this question. I had to use a variable (myVar1) defined in one JS file (myvariables.js) in another JS file (main.js). For this I did as below: Loaded the JS variable in one JS file in another JS file but I din't need to include one in another I just needed to ensure that 1st JS file loaded before 2nd JS file, and, 1st JS file's variables are accessible in 2nd JS file, automatically. This saved my day. Hope this helps. If your intention to load js file is that using the functions from the imported/included file, you can also define a global object and set the functions as object item. For instance: global.js A = {}; file1.js A.func1 = function() { console.log("func1"); } file2.js A.func2 = function() { console.log("func2"); } main.js A.func1(); A.func2(); You just need to be careful when you are including scripts in html file, the order should be as in below: <head> <script type="text/javascript" src="global.js"></script> <script type="text/javascript" src="file1.js"></script> <script type="text/javascript" src="file2.js"></script> <script type="text/javascript" src="main.js"></script> </head> I basically do like this, create new element and attach that to head. var x = document.createElement('script'); x.src = ''; document.getElementsByTagName("head")[0].appendChild(x); in jquery: // jQuery $.getScript('/path/to/imported/script.js', function() { // script is now loaded and executed. // put your dependent JS here. }); I have the requirement to load async an array of javascripts and at the final make a callback. Basically my best approach is the following: // Load a JavaScript from other Javascript function loadScript(urlPack, callback) { var url = urlPack.shift(); var subCallback; if (urlPack.length == 0) subCallback = callback; else subCallback = function () { console.log("Log script: " + new Date().getTime()); loadScript(urlPack, = don't will load until the first is completely loaded, and so... Results: You can't import, but you can reference. PhpShtorm IDE. To reference, in one .js file to another .js, just add this to the top of the file: <reference path="../js/file.js" /> Of course, you should use you own PATH to JS file. I don`t now will it work at others IDE. Probably yes, just try. It should work in Visual Studio too.(); var xxx = require("../lib/your-library.js") or import xxx from "../lib/your-library.js" //get default export import {specificPart} from '../lib/your-library.js' //get named export import * as _name from '../lib/your-library.js' //get full export to alias _name for more details. Unfortunately this only works in Chrome Similar Questions
http://ebanshi.cc/questions/16/how-to-include-a-javascript-file-in-another-javascript-file
CC-MAIN-2017-04
refinedweb
2,389
67.96
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b5) Gecko/20051006 Firefox/1.4.1 Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b5) Gecko/20051006 Firefox/1.4.1 Assigning a __noSuchMethod__ property to an XML object does not seem to work. Reproducible: Always Steps to Reproduce: 1. Load sample. Actual Results: JS error: ws.sample is not a function Expected Results: invoked the __noSuchMethod__ handler. Created attachment 199306 [details] adds a __noSuchMethod__ handler to E4X XML objects Comment on attachment 199306 [details] adds a __noSuchMethod__ handler to E4X XML objects ><HTML><HEAD/><BODY> > <SCRIPT type="text/javascript;e4x=1"> > function ajaxObj(content){ > var ajax = new XML(content); > ajax.function::__noSuchMethod__ = autoDispatch; > return ajax; > } > > function autoDispatch(id){ > if (! this.@uri) > return; > var request = <request method={id}/>; > for(var i=0; i<arguments[1].length; i++){ > request += <parameter>{arguments[1][i]}</parameter>; > } > var xml = this; > xml.request = request; > alert(xml.toString()); > }; > > var ws = new ajaxObj('<object uri=""/>'); var test = ws.function::sample('this', 'is', 'a', 'test'); > var test = ws.sample('this', 'is', 'a', 'test'); > </SCRIPT> Open js console and reload this page.<p/> The offending js is visible in view source. > ></BODY></HTML> Created attachment 199487 [details] html file with sample js what comment #2 was supposed to be E4X sucks, in that it hides methods and always wraps property values in an XMLList. The __noSuchMethod__ you define is not working because while it is well-defined in the function:: namespace, it is not invoked by that qualified name. This will be ugly to fix -- initial plan is to hack in an OBJECT_IS_XML test and qualify for that ugly case. /be Created attachment 199523 [details] [diff] [review] proposed fix Not a minimal patch, but the right one. E4X really did a number on method name lookup.... /be Comment on attachment 199523 [details] [diff] [review] proposed fix >+ BEGIN_LITOPX_CASE(JSOP_SETMETHOD, 0) >+ /* Get an immediate atom naming the property. */ >+ id = ATOM_TO_JSID(atom); >+ rval = FETCH_OPND(-1); >+ FETCH_OBJECT(cx, -2, lval, obj); >+ SAVE_SP(fp); >+ >+ /* Special-case XML object method lookup, per ECMA-357. */ >+ if (OBJECT_IS_XML(cx, obj)) { >+ JSXMLObjectOps *ops; >+ >+ ops = (JSXMLObjectOps *) obj->map->ops; >+ ok = ops->setMethod(cx, obj, id, &rval); >+ } else { >+ CACHED_GET(OBJ_SET_PROPERTY(cx, obj, id, &rval)); >+ } CACHED_SET instead? More review after my meetings this AM. Comment on attachment 199523 [details] [diff] [review] proposed fix Oops. Another fix in the next patch to this one: set vp[1] to root thisp on successful return from getMethod in js_Invoke's __noSuchMethod__ block. /be Created attachment 199573 [details] [diff] [review] fix Comment on attachment 199573 [details] [diff] [review] fix Interdiff says it all: =199573&headers=1 /be Comment on attachment 199573 [details] [diff] [review] fix sr=shaver, though mrbkap should look closely at the decompiler because I didn't! Comment on attachment 199573 [details] [diff] [review] fix r=mrbkap Fixed on the trunk. Would like to fix for 1.8, or something that releases soon enough off it into the Firefox 1.5+ patch-stream. Thinking about going for rc1 approval. Nominating on that basis. The bug is that E4X, new in 1.8/fx1.5, can't be used with the pre-existing hook for handling a call to an undefined method on an object, __noSuchMethod__. The combination is powerful, and the lack can't be worked around at all. The patch is totally confined to __noSuchMethod__ and E4X (function::foo property get and set) code paths, so it's not going to break anything else in JS. /be This seems to cause "(function a() {this.b();}).toSource();" to return "(function a() {this.function::b();})" (was "(function a() {this.b();})") if entered in the JavaScript Console, was this intended? (In reply to comment #13) > This seems to cause "(function a() {this.b();}).toSource();" to return > "(function a() {this.function::b();})" (was "(function a() {this.b();})") if > entered in the JavaScript Console, was this intended? It's benign, but it is neither backward-compatible nor minimal. Reopening. /be *** Bug 312766 has been marked as a duplicate of this bug. *** Created attachment 199978 [details] [diff] [review] overload a srcnote to distinguish explicit function:: This is dense, but it beats adding two more opcodes. /be *** Bug 313033 has been marked as a duplicate of this bug. *** Comment on attachment 199978 [details] [diff] [review] overload a srcnote to distinguish explicit function:: I think I get it! Comment on attachment 199978 [details] [diff] [review] overload a srcnote to distinguish explicit function:: I wonder if the future archaeologists will revere the decompiler as the Platonic ideal of Internet-era Baroque. sr=shaver I checked attachment 199978 [details] [diff] [review] into the trunk. Now to prepare a consolidated 1.8 branch patch. Asa, don't panic! /be Created attachment 200301 [details] [diff] [review] branch roll-up patch To recap: SpiderMonkey supports __noSuchMethod__ as a "default method handler", for calling obj.foo() where foo is not defined. E4X, per spec, hids methods in what is effectively an unnamed namespace in the XML.prototype object. Our E4X implementation allows methods to be defined in an explicit function::-qualified namespace, both to access the E4X prototype methods, and to shadow them in any XML object that delegates to that prototype. This patch fixes bugs in the interaction of the two features. It affects code paths peculiar to those features, and a common set of paths involving "method" property access. It tests well, and the changes to common code paths are small enough to inspect. Without the fix, there is no workaround, either for using __noSuchMethod__ with E4X (something AJAX developers want), or for overriding methods with function::-qualified property assignments. The lack of workarounds motivates this request to get fixed in 1.8. The major trunk patch landed five days ago. The followup fix is for a decompiler change that is not backward compatible, and is verbose (always emitting function::, even when it wasn't used, for method calls). That's in too, and it tests as fixed. The risks at this point are minimal: something else wrong with the decompiler's output that we don't test for and haven't noticed. /be. /cvsroot/mozilla/js/tests/e4x/Regress/regress-312196.js,v <-- regress-312196.js initial revision: 1.1 done (In reply to comment #22) >. That's right, but that is a lesser bug that we can fix later. The likelihood of name collisions between functions and XML children is low and controllable. The lack of a workaround for this bug makes the probability of failure to extent XML objects with default method handlers 1. /be Fixed on branch as well as trunk now. Thanks, all! /be fyi see Bug 355258
https://bugzilla.mozilla.org/show_bug.cgi?id=312196
CC-MAIN-2017-13
refinedweb
1,108
58.48
Are you sure? This action might not be possible to undo. Are you sure you want to continue? - 6 - Department of Archaeology and Ancient History Uppsala University For my parents Dorrit and Hindrik Åsa Strandberg The Gazelle in Ancient Egyptian Art Image and Meaning Uppsala 2009 Dissertation presented at Uppsala University to be publicly examined in the Auditorium Minus of the Museum Gustavianum, Uppsala, Friday, October 2, 2009 at 09:15 for the degree of Doctor of Philosophy. The examination will be conducted in English. Abstract Strandberg, Åsa. 2009. The Gazelle in Ancient Egyptian Art. Image and Meaning. Uppsala Studies in Egyptology 6. 262 pages, 83 figures. Published by the Department of Archaeology and Ancient History, Uppsala University. xviii +262 pp. ISSN 1650-9838, ISBN 978-91-506-2091-7.). Keywords: gazelle, Egyptian art, Egyptian religion, hunt, offering, Egypt desert fauna, Heb Sed, Hathor, Solar Eye Åsa Strandberg, Department of Archaeology and Ancient History, Uppsala University, Box 626, SE-751 26 Uppsala, Sweden. Åsa Strandberg 2009 ISSN 1650-9838 ISBN 978-91-506-2091-7 Printed in Sweden by Edita Västra Aros, Västerås 2009. Distributor: Department of Archaeology and Ancient History, Box 626, SE-751 26 Uppsala, Sweden Contents List of Figures viii Chronological table xiv Abbreviations used in the text xvi Preface xvii 1 Introduction 1 1.1 Aim 2 1.2 Source material 2 1.2.1 A representative selection 3 1.3 Approach 3 1.4 Previous research 5 1.5 Imagery as cultural expression 6 2 The Gazelle 8 2.1 Description 8 2.1.1 Gazelle (Antilopinae gazella) 9 a. Dorcas gazelle (Gazella dorcas) 9 b. Soemmerring's gazelle (Nanger soemmerringii) 10 2.1.2 Ibex (Capra ibex nubiana) 11 2.1.3 Oryx (Oryx dammah, Oryx beisa) 12 2.1.4 Other animals of Egypt desert 13 a. Hartebeest (Alcelaphus buselaphus) 14 b. Aurochs (Bos primigenus) 15 c. Addax (Addax nasomaculatus) 15 d. Fallow deer (Dama mesopotamica) 16 e. Roan antelope (Hippotragus equinus) 17 f. Barbary goat (Ammotragus lervia) 17 g. Wild ass (Equus asinus africanus) 17 h. Hyena (Hyena hyena) 18 i. Red Fox (Vulpes vulpes) 19 j. Cape hare (Lepus capensis) 19 k. Hedgehog (Paraechinus aethiopicus) 20 l. Ostrich (Struthio camelus) 20 2.1.5 Ancient and modern problems of identification 21 2.1.6 Description – concluding remarks 23 2.2 Habitat and subsistence 24 2.3 Natural behaviour 24 2.3.1 Mating 25 2.3.2 Giving birth 25 2.3.3 Nursing the young 26 2.3.4 Protecting the young 27 2.3.5 Fleeing the predator 28 2.3.6 Natural behaviour – concluding remarks 29 2.4 Domestication 30 2.5 The gazelle – concluding remarks 32 3 The Initial Images - Pre- and Early Dynastic Sources 33 3.1 Rock drawings 34 3.2 Ceramics 35 3.3 Knife handles 36 3.3.1 The Petrie Museum knife handle (UC 16295) 36 3.4 Combs and hairpins 37 3.5 Palettes 38 3.5.1 The Hunters Palette 39 3.5.2 The ‘Two Dogs Palette’ 40 3.5.3 The Stockholm Palette 42 3.5.4 The Gazelle Palette 43 3.6 Hierakonpolis Tomb 100 44 3.7 The Early Dynastic Period and Hemaka’s disc 45 3.8 Initial images - concluding remarks 46 4 The Desert Hunt 47 4.1 The components of the desert hunt 47 4.1.1 Desert topography 47 4.1.2 The hunters 47 4.1.3 The prey 48 4.1.4 Hiding from the predator: the insert 50 4.1.5 The hunt and its implications 51 4.2 The royal desert hunt 51 4.2.1 The royal desert hunt: Old Kingdom 52 a. Mortuary temple of Sahure, Abusir, 5 th dyn. 52 b. Sun Temple of Niuserre, Abu Ghurob, 5 th dyn. 56 c. Pyramid complex of Unas, Saqqara, 5 th dyn. 59 d. Mortuary temple of Pepi II, Saqqara, 6 th dyn. 59 e. The royal desert hunt: Old Kingdom - concluding remarks 61 ii 4.2.2 The royal desert hunt: Middle Kingdom 62 a. Mortuary temple of Mentuhotep II, 11 th dyn. 62 b. The royal desert hunt – Middle Kingdom - concluding remarks 63 4.2.3 The royal desert hunt: New Kingdom 63 a. Tomb of Tutankhamun, KV 62, 18 th dyn. 64 a.1 Bow case 64 a.2 Painted chest 65 a.3 Embroidered tunic 66 a.4 Unguent jar 68 b. Temple of Ramses III, Medinet Habu, 20 th dyn. 69 c. The royal desert hunt: New Kingdom - concluding remarks 70 4.2.4 The royal desert hunt - concluding remarks 70 4.3 The desert hunt in private tombs 71 4.3.1 The desert hunt in Old Kingdom private tombs 72 a. Meidum, 3 rd and 4 th dyn. 72 a.1 Mastaba of Nefermaat and Atet, 3 rd - 4 th dyn. 73 a.2 Mastaba of Rahotep, 3 rd - 4 th dyn. 73 b. Saqqara, 4 th - 6 th dyn. 74 b.1 Mastaba of Raemka, 5 th dyn. 75 b.2 Mastaba of Pehenuka, mid 5 th dyn. or later 76 b.3 Mastaba of Ptahhotep [II], late 5 th dyn. 77 b.4 Mastaba of Niankhkhnum and Khnumhotep, 5 th dyn. 78 b.5 Mastaba of Meryteti, 6 th dyn. 78 c. Giza, 4 th - 6 th dyn. 79 c.1 Mastaba of Nimaatre, late 5 th dyn. 79 c.2 Mastaba of Seshemnefer [IV], late 5 th - early 6 th dyn. 80 d. Deir el-Gebrawi, 6 th dyn. 81 d.1 Rock-cut tomb of Ibi, 6 th dyn. 82 e. Old Kingdom private tombs - concluding remarks 83 4.3.2 The desert hunt in Middle Kingdom private tombs 83 a. Beni Hassan, 11 th - 12 th dyn. 84 a.1 Tomb of Khnumhotep [III], BH 3, 12 th dyn. 84 a.2 Tomb of Khety, BH 17 11 th dyn. 86 b. Meir, 12 th dyn. 87 b.1 Tomb of Senbi, B 1, 12 th dyn. 87 b.2 Tomb of Ukhhotep, B 2 12 th dyn. 89 c. Thebes, 11 th - 12 th dyn. 89 c.1 Tomb of Intefiker, TT 60, 12 th dyn. 90 iii d. El-Saff, 11 th dyn. 91 d.1 Tomb of Ip, 11 th dyn. 91 e. Middle Kingdom private tombs - concluding remarks 92 4.3.3 The desert hunt in New Kingdom private tombs 92 a. Tomb of Montuherkhepeshef, TT 20, 18 th dyn. 93 b. Tomb of Amenipet, TT 276, 18 th dyn. 94 c. New Kingdom private tombs - concluding remarks 96 4.3.4 Final examples of the desert hunt scene 96 a. Tomb of Ibi, TT 36 96 4.4 The desert hunt scenes - concluding remarks 97 5 The Gazelle as Offering 101 5.1 Offering scenes 101 5.1.1 A typology of gazelle images 104 a. Bringing the gazelle from the estates 104 a.1.Gazelle on leash 105 Tomb of Seshemnefer, LG 53, Giza, late 5 th -early 6 th dyn. 105 Tomb of Kemsit, TT 308, Deir el-Bahari, 11 th dyn. 106 Tomb of Amenemhat TT 82, Sheikh Abd el-Gurna, 18 th dyn. 106 a.2. Gazelle on leash, nursing 107 Tomb of Kagemni, LS 10, Saqqara, 6 th dyn. 107 a.3. Gazelle carried 107 Tomb of Akhethotep, D 64a, Saqqara, 5 th dyn. 107 a.4. Procession of the estates – concluding remarks 108 b. Procession of offering bearers 108 b.1 Gazelle walking 108 ________ ___the gazelle by the horns 109 Tomb of Shetui, Giza, end of 5 th - early 6 th dyn. 109 Tomb of Khnumhotep [III], BH 3, Beni Hassan, 12 th dyn. 109 Tomb of User, TT 21, Sheikh Abd el-Gurna, 18 th dyn. 110 ___________________________ 111 Tomb of Sekhemka, G 1029, Giza, end of 5 th -early 6 th dyn. 111 Tomb of Ukhhotep, C 1, Meir, 12 th dyn. 111 Tomb of Rekhmire, TT 100, Sheikh Abd el-Gurna 112 b____________________________, nursing 112 Tomb of Ankhmahor, Saqqara, early 6 th dyn. 112 b.1._____ ___‘independently’ 113 Tomb of Seshemnefer, LG 53, Giza, end of 5 th -early 6 th dyn. 113 Tomb of Khety, BH 17, Beni Hassan, 11 th dyn. 114 Tomb of Ineni, TT 81, Sheikh Abd el-Gurna, 18 th dyn. 114 iv ______Striding ‘independently’, nursing 115 Tomb of Rawer, G 5470, Giza, late 5 th dyn. 115 Tomb of Kadua, Giza, 5 th dyn. 115 b.2 Carrying the gazelle 116 ___________ ___________________________ 117 Tomb of Seshat-hotep, G 5150, Giza, 5 th dyn. 117 Tomb of Seshemnefer [III], G 5170, Giza, 117 Tomb of Ukhhotep, C 1, Meir, 12 th dyn. 118 Tomb of Menna, TT 69, Sheikh Abd el-Gurna, 18 th dyn. 118 b.2.______ ___!_"__________ 118 Tomb of Nesutnefer, G 4970, Giza, early-mid 5 th dyn. 118 ___________ _____________"_____#_________ _______ 119 Mastaba of Kaninesut, G 2155, Giza, early 5 th dyn. 119 Tomb of Amenemhat, BH 2, Beni Hassan, 12 th dyn. 120 From an unknown Theban tomb, 18 th dyn. 120 b.3 Carrying the gazelle in a basket on a pole 120 __$________ ____________ _____%___ 121 Tomb of Idut, Saqqara, 6 th dyn. 121 Tomb of Ukhhotep, B 2, Meir, 12 th dyn. 122 c. A Late Period version of the offering procession 122 Tomb of Petosiris, Tuna (Hermopolis Magna), c. 350 B.C. 122 5.1.2 Offering scene motifs – concluding remarks 123 5.2 Offering Lists 124 5.2.1 The gazelle in offering lists 125 Tomb of Seshat-hotep, G 5150, Giza, early 5 th dyn. 125 Tomb of Kapunesut, G 4651, Giza, early - mid 5 th dyn. 126 5.3 The gazelle on the offering table in scenes and on objects 126 5.3.1 Offering table scene, Tomb of Ukhhotep, B 2, Meir, 12 th dyn. 126 5.3.2 Offering tables as objects 127 Offering table of Teti, Giza, Old Kingdom 127 5.4 The gazelle as offering – concluding remarks 128 6 The Gazelle Motif on Objects 130 6.1 The gazelle wand 131 6.1.1 A pair of gazelle wands, Giza, 1 st dyn. 131 6.1.2 The gazelle wand in the Pyramid Texts, 6 th dyn. 131 6.1.3 Dancing with gazelle wands, 133 a. Tomb of Inti, Deshasheh, mid 6 th dyn. 133 v 6.1.4 The gazelle wands and the royal women at the Heb Sed 133 a. Tomb of Kheruef, TT 192, ‘Asâsîf, 18 th dyn. 133 b. Temple of el-Kab, 19 th dyn. 134 c. Temple of Bubastis, 22 nd dyn. 134 6.1.5 The gazelle wand – concluding remarks 135 6.2 Gazelle protomes 135 6.2.1 Diadem with gazelle protomes, 18 th dyn. 136 6.2.2. The Stag Diadem 137 6.2.3 Tomb of Menna, TT 69, Sheikh Abd el-Gurna, 18 th dyn. 137 6.2.4 Tomb of Pairy, TT 139, Sheikh Abd el-Gurna, 18 th dyn. 138 6.2.5 Chair of Satamun, KV 46, 18 th dyn. 139 6.2.6 Temple of el-Kab, 19 th dyn. 140 6.2.7 The gazelle protome - concluding remarks 140 6.3 Horus Cippi 140 6.3.1 An early Shed stela, 19 th dyn. 142 6.3.2 A Horus Cippus, Saite Period (?) 142 6.3.3 A Horus-Shed Relief, Karnak, Late Period 143 6.3.4 The Horus Cippi - concluding remarks 144 6.4 The palmette with antithetical gazelles on two chests 144 6.4.1 Chests of Perpaouty 146 a. The Durham Chest 146 b. The Bologna Chest 147 6.4.2 Antithetical gazelles and the palmette - concluding remarks 147 6.5 The nursing gazelle on faience bowls 148 6.5.1 The bowl of Maiherperi 149 6.5.2 The Gurob bowl 150 6.5.3 The large Ashmolean bowl 151 6.5.4 The Petrie Museum fragment 151 6.5.5 The nursing gazelle on faience bowls - concluding remarks 152 6.6 A gazelle-shaped vessel, 18 th dyn. 152 6.7 ’Cosmetic’ spoons 153 6.7.1 Typology 153 6.7.2 Function 154 6.7.3 Swimming-girl spoon with gazelle container 155 6.7.4 Cartouche Pond 156 6.7.5 A gazelle container 156 6.7.6 Cosmetic spoons and container - concluding remarks 157 6.8 Scarabs 157 6.8.1 The gazelle on scarabs 158 6.9 The gazelle motif on objects - concluding discussion 159 vi 7 The Gazelle and the Divine 160 7.1 The Predynastic gazelle burials 160 7.2 Gehesty – The “Place of the Two Gazelles” 162 7.2.1 Gehesty in the Pyramid Texts, Old Kingdom 162 7.2.2 Gehesty in the Coffin Texts, Spell 837, Middle Kingdom 164 7.2.3 Geheset in the Ramesseum Dramatic Papyrus, 12 th dyn. 165 7.2.4 The stela of May, 19 th dyn. 165 7.2.5 Khnum, Lord of Gehesty, 21 st dyn. 166 7.2.6 Sarcophagus of Pa-di-sema-tawy, 26 th dyn. 167 7.2.7 Papyrus Jumilhac, Greco-Roman Period 168 7.2.8 Gehesty – concluding remarks 170 7.3 The gazelle at Wadi Hammamat, 11 th dyn 170 7.4 The gazelle and Anukis 173 7.4.1 A relief from a temple at Buhen, 18 th dyn. 173 7.4.2 The tomb of Neferhotep, TT 216, Deir el-Medina, 19 th dyn. 174 7.4.3 Two ostraca from Deir el-Medina 175 a. A votive for Anukis (Stockholm, MM 14011) 175 b. Giving praise to Anukis (Cairo, JE 43660) 176 7.4.4 The One who Dwells in Komir 178 a. The gazelle cemetery at Geheset / Per-merw 178 7.4.5 A Demotic funerary text, Roman Period 179 7.4.6 The gazelle and Anukis - concluding remarks 180 7.5 The gazelle and the divine Eyes 180 7.5.1 The Contendings of Horus and Seth 181 7.5.2 The gazelle in the Myth of the Solar Eye 183 7.5.3 Additional references to the Myth of the Solar Eye 183 7.5.4 The gazelle and the divine eyes - concluding remarks 184 7.6 Isis and the gazelle in Roman times 184 7.7 The gazelle and the divine – concluding remarks 185 8 The Gazelle in ancient Egyptian Art – Image and Meaning 187 8.1 Abstracted motifs 188 8.1.1 The eyes of the gazelle - face turned back 189 8.1.2 Mother and child – the nursing motif 189 8.1.3 The hidden fawn 190 8.1.4 Single gazelle protome – the uraeus and Udjat Eye 190 8.1.5 The desert mountains 190 8.1.6 The gazelle pair 192 8.2 Conclusion 193 vii Appendices 195 Bibliography 215 Indices 249 List of Illustrations Frontispiece Nursing gazelle, from the tomb of Kapi, G 2091, Giza. Roth 1995: Fig. 168. With the permission of Museum of Fine Arts, Boston. Chapter 2 The Gazelle Figure 1 Two dorcas gazelles. Mortuary temple of Sahure, Berlin 9 21783. Borchardt 1913: Pl. 17 Figure 2 Soemmerring’s gazelle. Tomb of Ptahhotep, D 64b, 10 Saqqara. Davies 1900: Pl. XXII. With the permission of the EES Figure 3 Ibex. Raemka blocks, Saqqara. D3/ S 903 = MMA 11 1908.201.1 Hayes 1953: 99, Fig. 56 Figure 4 Oryx. Mortuary temple of Sahure, Berlin 21783. Borchardt 12 1913: Pl. 17 Figure 5 Hartebeest. Narmer macehead. Ashmolean Museum E 14 3631, Oxford. Quibell 1900: Pl. XXVI B. With the permission of the EES Figure 6 Aurochs attacked by lion. Tomb of Senbi, B 1, Meir. 15 Blackman 1914: Pl. VI. With the permission of the EES Figure 7 Addax. Mortuary temple of Sahure, Berlin 21783. 16 Borchardt 1913: Pl. 17 Figure 8 Fallow deer. Mortuary temple of Sahure, Berlin 21783. 16 Borchardt 1913: Pl. 17 Figure 9 Barbary goat. Mortuary temple of Sahure, Berlin 21783. 17 Borchardt 1913: Pl. 17 Figure 10 Hyena pierced by arrows. Tomb of Senbi, B 1, Meir. 18 Blackman 1914: Pl. VI. With the permission of the EES Figure 11 Fox. Tomb of Ukhhotep, B 2, Meir. Blackman 1915a: Pl. 19 VIII. With the permission of the EES Chapter 3 The Initial Images - Pre- and Early Dynastic Sources Figure 12 Desert game on D-ware. Petrie 1921: Pl. XXXIV (47 C). 35 With the permission of the EES viii Figure 13 Petrie Museum knife handle, UC 16295, Petrie Museum, 37 London. Drawn by Alicja Grenberger from Petrie 1920: Pl. XLVIII, 6 Figure 14 Predynastic comb (Naqada grave 1687), Ashmolean 38 Museum 1895.943. Oxford. Drawn by Alicja Grenberger from Wengrow 2006: 100, Fig. 5.1 Figure 15 The ‘Two Dogs Palette’, Ashmolean Museum, E.3924. 41 Oxford. Drawn by Alicja Grenberger from Asselberghs 1961: Pl. LXX, Fig. 127 Figure 16 The Stockholm palette. EM 6000, Medelhavsmuseet, 43 Stockholm. Säve-Söderbergh 1953: 18, Fig. 8 Figure 17 Disc of Hemaka, JE 70104. Cairo. Drawn by Alicja 45 Grenberger. from Emery 1938: Pl. 12b Chapter 4 The Desert Hunt Figure 18 Dog grasping a gazelle's hind leg. Tomb of Raemka. D3/ S 48 903 = MMA 1908.201.1.Hayes 1953: 99, Fig. 56 Figure 19 Recumbent gazelle in an insert. Tomb of Raemka, D3/ S 50 903 = MMA 1908.201.1. Hayes 1953: 99, Fig. 56 Figure 20 Sahure: desert hunt. Mortuary temple, Berlin 21783. 54 Borchardt 1913: Pl. 17 Figure 21 Blocks from Niuserre's sun temple. Berlin 20036, von 57 Bissing 1956: Pl. XI a-b Figure 22 Deir el-Bahari: hunted gazelle. Block temple of Mentuhotep 62 II, Deir el-Bahari. Brussels Musée Royaux E.4989. Drawn by Alicja Grenberger from Naville et al. 1907: Pl. XVI Figure 23 Back panel 1: nursing and fleeing gazelles. Embroidered 66 tunic of Tutankhamun, JE 62626 (KV 62). Crowfoot and Davies 1941: Pl. XXII. With the permission of the EES Figure 24 Back panels 3-6. Embroidered tunic of Tutankhamun, JE 67 62626 (KV 62). Crowfoot and Davies 1941: Pl. XXII With the permission of the EES Figure 25 Rahotep: Gazelle head turned. Tomb of Rahotep. Tomb no. 73 6. Petrie 1892: Pl. IX. With the permission of the EES Figure 26 Blocks of Raemka, D3/ S 903 = MMA 1908.201.1. 75 Hayes 1953: 99, Fig. 56 Figure 27 Pehenuka: gazelle nursing within desert hunt. Saqqara. 76 Berlin 1132. Harpur 1987: 530, Fig. 188 Figure 28 Desert hunt of Ptahhotep [II], D 64b, Saqqara. Davies 1900: 77 Pl. XXI. With the permission of the EES ix Figure 29 Nimaatre: mating dorcas and Soemmerring's gazelles. G 80 2097, Giza. Roth 1995: Pl. 189. With the permission of the Museum of Fine Arts, Boston Figure 30 Seshemnefer [IV]: mating gazelles in desert. LG 53, Giza. 81 Junker 1953: Fig. 63 (between pages 152-153). With the permission of the Austrian Academy of Sciences Figure 3: Ibi: desert hunt scene. Tomb 8, Deir el-Gebrawi. Davies 82 1902a: Pl. XI. With the permission of the EES Figure 32 Khnumhotep [III] desert hunt, with foaling gazelle. BH 3, 85 Beni Hassan. Newberry 1893: Pl. XXX. With the permission of the EES Figure 33 Khety: hunting aurochs and gazelles. BH 17, Beni Hassan. 86 Newberry 1894: Pl. XIII. With the permission of the EES Figure 34 Senbi: desert hunt scene. B 1, Meir. Blackman 1914: Pl. VI. 88 With the permission of the EES Figure 35 Ukhhotep: gazelle seized by dogs and pierced by arrow. B 89 2, Meir. Blackman 1915: Pls VII-VIII. With the permission of the EES Figure 36 Desert hunt of Intefiker, TT 60. Davies and Gardiner 1920: 90 Pl. VI. With the permission of the EES Figure 37 Gazelle nursing in desert. Montuherkepeshef, TT 20. 95 Davies 1913: Pl. XII. With the permission of the EES Figure 38 Desert hunt, Amenipet, TT 276. Wilkinson 1878: 92, Fig. 95 357 Figure 39 Ibi: desert hunt from the Saite Period, TT 36. Davies 1902a: 96 Pl. XXV. With the permission of the EES Chapter 5 The Gazelle as Offering Figure 40 Gazelle on leash. Tomb of Seshemnefer [IV], LG 53, 105 Saqqara. Junker 1953: 197, Fig. 76. With the permission of the Austrian Academy of Sciences Figure 41 Gazelle on leash Tomb of Amenemhat, TT 82. Davies and 106 Gardiner 1915: Pl. XXII. With the permission of the EES Figure 42 Carrying the gazelle. Tomb of Akhethotep, D 64a, Saqqara. 107 Davies 1901: Pl. XIII. With the permission of the EES Figure 43 Guiding the gazelle. Tomb of Shetui, Giza. Junker 1950: 109 187, Fig. 86. With the permission of the Austrian Academy of Sciences x Figure 44 Guiding the gazelle. Tomb of Khnumhotep III, BH 3, Beni 110 Hassan. Newberry 1893: Pl. XXXV. With the permission of the EES Figure 45 Guiding the gazelle. Tomb of User, TT 21. Davies 1913: Pl. 110 XXII. With the permission of the EES Figure 46 Pulling and pushing the gazelle. Tomb of Sekhemka, G 111 1029, Giza. Simpson 1980: Fig. 4. With the permission of the Museum of Fine Arts, Boston Figure 47 Guiding the gazelle. Tomb of Ukhhotep, C 1, Meir. 112 Blackman and Apted 1953: Pl. XV. With the permission of the EES Figure 48 Guiding a nursing gazelle. Tomb of Ankhmahor. 113 Badawy 1978: Fig. 35 Figure 49 Gazelle striding independently. Tomb of Seshemnefer [IV]. 114 LG 53, Giza. Junker 1953: 205, Fig. 79. With the permission of the Austrian Academy of Sciences Figure 50 ‘Herding’ the gazelles. Tomb of Khety, BH 17. Beni 114 Hassan. Newberry 1894: Pl. XIV. With the permission of the EES Figure 51 Nursing the fawn. Tomb of Rawer [II], G 5470, Giza. 115 Junker 1938: 233, Fig. 48. With the permission of the Austrian Academy of Sciences Figure 52 Seshat-hotep: Carrying the gazelle. G 5150, Giza. Junker 117 1934: 182, Fig. 28. With the permission of the Austrian Academy of Sciences Figure 53 Seshemnefer [III]: Carrying the gazelle, G 5170, Giza. 117 Junker 1938: 73, 8b. With the permission of the Austrian Academy of Sciences Figure 54 Female offering bearer carries a gazelle. Tomb of 118 Ukhhotep, C 1, Meir. Blackman and Apted 1953: Pl. XVIII Figure 55 Carrying next to chest. Tomb of Nesutnefer, G 4970, Giza. 119 Junker 1938: Fig 28. With the permission of the Austrian Academy of Sciences Figure 56 Carrying, holding legs. Tomb of Kaninesut [I], G 2155, 119 Giza. Kunsthistorisches Museum ÄS 8006, Vienna. Junker 1934: Fig. 18. With the permission of the Austrian Academy of Sciences Figure 57 Holding legs. Tomb of Amenemhat, BH 2, Beni Hassan. 120 Neweberry 1893: Pl. XIII. With the permission of the EES xi Figure 58 Gazelles in basket. Tomb of Idut. Saqqara. Macramallah 121 1935: Pl. XX Figure 59 Carrying two gazelles in baskets. Tomb of Ukhhotep, B 2, 122 Meir. Blackman 1915: Pl. X. With the permission of the EES Figure 60 in offering list. Tomb of Seshat-hotep, G 5150, Giza. 125 Junker 1934: 187, Fig. 33.With the permission of the Austrian Academy of Sciences Figure 61 Offering list, gazelle to the left. Tomb of Kapunesut, G 126 4651, Giza. Junker 1938: 135, Fig. 17. With the permission of the Austrian Academy of Sciences Figure 62 Gazelle head on an offering table. Tomb of Ukhhotep, B 2, 126 Meir. Blackman 1915a: Pl. VI. With the permission of the EES Chapter 6 The Gazelle Motif on Objects Figure 63 Gazelle wands, Giza. CG 69246/JE38972, Cairo. Petrie 131 1907: Pl. IV. With the permission of the EES Figure 64 Gazelle wands in the tomb of Inti, Deshasheh. Petrie 1898: 133 Pl. XII. With the permission of the EES Figure 65 Princesses at El-Kab. Wilkinson 1971: 117, Fig. 51. With 134 the permission of Methuen & Co Ltd Figure 66 Gazelle wands at Bubastis. Naville 1892: Pl. XIV. With the 135 permission of the EES Figure 67 Double gazelle protome. Tomb of the three princesses, 137 Wadi Qirud. MMA 26.8.99, New York. Drawn by B. Eriksson from Aldred 1971: Pl. 61, taken from Troy 1986 Figure 68 Daughter of Menna, TT 69. Drawn by B. Eriksson 138 from Davies 1936: Pl. LIII, taken from Troy 1986 Figure 69 The chair of Satamun, CG 51113 (KV 46). Drawn by B. 139 Eriksson from Quibell 1908: Pl. XL, taken from Troy 1986 Figure 70 A Saite Horus Cippus. Puskhin Museum I.1.a.4467, 143 Moscow. Drawn by Alicja Grenberger from Berlev and Hodjash 1982: 247, cat. No 182 Figure 71 Perpaouty chest. Bologna KS 1970, Museo Civico 147 Archeologico. Drawn by Alicja Grenberger from Capart 1947: Pl. 757 Figure 72 The bowl of Maiherperi, CG 24058/JE 33825 (KV 36). 150 Cairo. Keel 1980: 87, Fig. 49. With the permission of O. Keel xii Figure 73 The Gurob bowl. Ashmolean Museum 1890.1137, Oxford. 150 Petrie 1891: Pl. XX. With the permission of the EES Figure 74 Bowl fragment in the Petrie Museum, UC 30054, Petrie 151 Museum. London. Drawn by Alicja Grenberger from a photograph supplied by the museum Figure 75 Swimming-girl spoon with a recumbent gazelle as 155 container. MMA 26.2.47, New York. Drawn by Alicja Grenberger from Wallert 1967: Pl. 15 Figure 76 Cosmetic spoon with fawn. British Museum BM 5958, 156 London. Drawn by Alicja Grenberger from Wallert 1967: Pl. 19 Figure 77 A branch and gazelle. New York. Drawn by Alicja 158 Grenberger from Hayes 1959: 87, Fig. 48 (bottom row, second from right) Chapter 7 The Gazelle and the Divine Figure 78 Anukis giving life, a gazelle behind her. Temple of Buhen. 174 Caminos 1974: Pl. 20. With the permission of the EES Figure 79 Neferhotep’ s ‘garden’ of gazelles, with a nursing scene. 174 Tomb of Neferhotep, TT 216. Davies 1923: 52, Fig. 20 Figure 80 Anukis and two recumbent gazelles. Stockholm, MM 177 14011. Peterson 1973: Pl. 19. © Medelhavsmuseet, Stockholm. Ove Kaneberg Figure 81 Hay adoring Anukis in the shape of a gazelle. Cairo, JE 177 43660. Quaegebeur 1999: 22, Fig. 14 Chapter 8 The Gazelle in Ancient Egyptian Art. Image and Meaning Figure 82 Gazelle and the udjat eye. New York. Drawn by Alicja 190 Grenberger from Hayes 1959: 36, Fig. 17 (bottom row, second from left) Figure 83 Gazelle standing on desert ground. MMA 26.7.1292, New 192 York. Drawn by Alicja Grenberger from Arnold 1995: 10, cat. no. 3 xiii Chronology (adapted from Shaw 2000: 479-483) Predynastic Period c. 5300-3000 B.C. Early Dynastic Period c. 3000-2686 B.C. 1st Dynasty 3000-2890 B.C. Den c. 2950 B.C. 2nd Dynasty 2890-2686 B.C. Old Kingdom c. 2686-2125 B.C. 3rd Dynasty 2686-2613 B.C. Huni 2637-2613 B.C. 4 th Dynasty 2613-2494 B.C. Sneferu 2613-2489 B.C. Khufu 2589-2558 B.C. Khaefre 2558-2532 B.C. 5 th Dynasty 2494-2345 B.C. Userkaf 2494-2487 B.C. Sahure 2487-2475 B.C. Niuserre 2445-2421 B.C. 6 th Dynasty 2345-2181 B.C. Pepi I 2321-2287 B.C. Merenre 2287-2278 B.C. Pepi II 2278-2184 B.C. 7-8 th Dynasties 2181-2160 B.C. First Intermediate Period (FIP) c. 2160-2055 B.C. 9-10 th Dynasties 2160-2025 B.C. 11 th Dynasty (in Thebes) 2125-2055 B.C. Middle Kingdom c. 2055-1650 B.C. 11 th Dynasty 2055-1985 B.C. Mentuhotep II 2055-2004 B.C. Mentuhotep IV 1992-1985 B.C. 12 th Dynasty 1985-1773 B.C. Amenemhet I 1985-1955 B.C. Sesostris I 1965-1920 B.C. Sesostris III 1874-1855 B.C. xiv 13-14 th Dynasties 1773-1650 B.C Neferhotep - Second Intermediate Period (SIP) c. 1650-1550 B.C. 15 th Dynasty (Hyksos) 1650-1550 B.C. 16 th Dynasty (Thebes) 1650-1580 B.C. 17 th Dynasty (Thebes) 1580-1550 B.C. New Kingdom c. 1550-1069 B.C. 18 th Dynasty 1550-1295 B.C. Amosis 1550-1525 B.C. Amenhotep I 1525-1504 B.C. Tuthmosis III 1479-1425 B.C. Hatshepsut 1473-1458 B.C. Amenhotep II 1427-1400 B.C. Tuthmosis IV 1400-1390 B.C. Amenhotep III 1390-1352 B.C. Akhenaton 1352-1336 B.C. Tutankhamun 1336-1327 B.C. 19 th Dynasty 1295-1186 B.C. Seti I 1294-1279 B.C. Ramses II 1279-1213 B.C. 20 th Dynasty 1186-1069 B.C. Ramses V 1147-1143 B.C. Third Intermediate Period c. 1069-664 B.C. 21 st Dynasty 1069-945 B.C. Pinudjem II 22 nd Dynasty 945-715 B.C. Osorkon II 23 rd Dynasty 818-715 B.C. 24 th Dynasty 727-715 B.C. 25 th Dynasty 747-656 B.C. Late Period 664-332 B.C. 26 th Dynasty 664-525 B.C. Psamtek I 664-610 B.C. Psamtek II 595-589 B.C. xv 27 th Dynasty (1 st Persian Period) 525-404 B.C. 28 th Dynasty 404-399 B.C. 29 th Dynasty 399-380 B.C. 30 th Dynasty 380-343 B.C. Second Persian Period 343-332 B.C. Ptolemaic Period 332-30 B.C. Roman Period 30 B.C. – A. D. 395 Abbreviations in the text CT Coffin Texts OK Old Kingdom FIP First Intermediate Period PT Pyramid Texts MK Middle Kingdom SIP Second Intermediate Period NK New Kingdom xvi Preface It is hard to believe that these words are finally being written. While my goal has been unwavering, the path has been rocky at times. There are several people who have contributed to the completion of this dissertation; the following represents merely a small but vital part. A visit to the Griffith Institute Archive in the Fall of 2003 was very important for my research. I’ll never forget the professional and warm welcome that I received from Jaromir Malek, Elizabeth Fleming and Alison Hobby. With their help I was able to finish the collection of source material. I gratefully acknowledge the financial support that made that visit possible furnished by grants from Gernandts, S. V. Wångstedts and V. Ekmans (Uplands nation) funds. I believe my adviser Professor Lana Troy has had a trial in endurance. Her infallible guidance during the process has been far more than I’ve ever had the right to ask for. Our numerous discussions have been most gratifying for me, and I hope that I’ve managed to transform their essence into this work; it symbolizes my appreciation, gratitude and respect for such continuous support. It goes without saying that I am also grateful for her help in making sure that the English text is readable, as well as for editorial assistance. Professor Lars Karlsson has functioned as my associate adviser and in this role has had the task of reading the manuscript in the last stages of its completion. His comments have been useful in improving the text and his willingness and enthusiasm has been gratifying. The majority of the 83 figures in this volume are reproduced with the permission of the Egypt Exploration Society (EES), the Museum of Fine Arts in Boston and the Austrian Academy of Sciences. Further permissions have been granted by Othmar Keel, the Methuen & Co Ltd and Medelhavsmuseet in Stockholm. The generosity with which this permission was granted is greatly appreciated. Some of the figures are the result of Alicja Grenberger’s skill in drawing ancient objects. Although this was an unusual challenge for her, she delivered remarkable illustrations. The credit is all yours Alicja, nonetheless I am proud of them! I have been lucky to have numerous supportive friends in both Finland and Sweden, who by not being a part of this field, have shown me xvii that there is a world outside. Thank you for all the fun and silly parties…! It goes without saying that some, closer to home, have had more than their fair share of my frustration over the years, in particular Gabriella Jönsson and Eva- Lena Wahlberg. Thank you for listening without judging and adjusting my occasional blurry focus, on the truly important matters in life. The task of writing a dissertation requires a practice in patience for the researcher. My grandfather lost his nearly finished thesis in the bombings of Helsinki during WWII. This has given me perspective and generated great motivation for finishing what I started long ago. I feel sincerely privileged to have had this opportunity. There are no words that are sufficient to even begin to describe the gratitude I feel for the never-ending patience my parents have shown me. Their genuine interest in my strivings has been inspiring, not to mention all our visits to various museums around Europe. Without their significant financial contributions throughout these years, this work would simply not exist. It is dedicated to you. Tack mamma och pappa! Åsa Strandberg Uppsala in August 2009 xviii Auch in der Ägyptologie ist es höchste Zeit, die Bilder mit gleicher Genauigkeit zu lesen wie die Texte. (Hornung 1973: 37) 1 Introduction Ancient Egyptian art and particularly its animal imagery has been a source of fascination since Greco-Roman times. Animal motifs can be found in virtually all aspects of this art, in more or less imaginative compositions. In this way it is an integral part of the multifaceted interaction between ancient Egyptian art, its context and religious beliefs. What we term “art” was, for the Egyptians, a way of formulating ideas, with the most comprehensive expression being given priority over realistic depiction. Concept and “message” shaped Egyptian art. This made static canonical motifs a viable mode of expression (Gaballa 1976: 1ff.). Animal images formed a substantial part of the catalogue of these motifs. Central ideas are often illustrated in ancient Egyptian art with animal imagery with some animals appearing more frequently than others, sug-gesting some kind of conceptual hierarchy. This may relate to a level of recognition that allows the same image to embody multiple connotations. Species connected to the pharaoh and to the main deities have a well defined status in the iconography. The falcon represents the ruling king at the very beginning of the kingship. The domestic cow is another animal that has strong iconic power with a connection to the idea of divine motherhood, later developed in the roles of Isis and Hathor, both of whom can appear as nurturers of a divine calf. The gazelle can not be compared to falcon or the cow in terms of distinctive correspondences, yet it is represented in well defined images that function on several levels. The gazelle belongs to that group of animals that, although they are found repeatedly in an ancient Egyptian context, has not received in depth attention. The lack of a conspicuously divinity may have contributed to this neglect, or perhaps there is a fixed idea regarding which animals fall into the category “symbolic” that has led to the assumption that there is nothing behind the image. The simple fact that the gazelle does not have a given place in the modern world may contribute to our classification of its representation as “naturalistic”. A closer look at the representations of less well researched animals contributes however to a broader understanding of 1 the complexity of the Egyptian worldview. This study of the imagery of the gazelle is an attempt to add insights into that worldview, and into the multitude of ways in which it was expressed. 1.1 Aim The aim of this study is to present a comprehensive overview of the depiction of the gazelle in ancient Egyptian art and to define its status as a cultural expression. This is achieved by reviewing the distinctive images of the gazelle, referred to here as “motifs” and the contexts in which they occur. Depictions of the gazelle are found throughout ancient Egyptian civilization. It is portrayed with a consistency in form over the thousands of years covered by this study. Specific images of the gazelle are often exclusive for this species, indicating that there are important conceptions associated with its representation. One of the main questions is why the gazelle, an animal found on the geographic margins of the culture zone, was selected to connote certain ideas and associations. In order to understand the background to the way the gazelle is represented, it is necessary to have a rudimentary understanding of its ‘zoology’ (Chapter 2). Knowledge of the behaviour of the gazelle in its natural surroundings facilitates a comprehensive of its presentation in pictorial form. A ‘two fold’ pattern emerges when tracing the representation of the gazelle in Egyptian art. The depiction of the gazelle, while naturalistic both in form and context, is also aligned with concepts that give it the role of “symbol”. With the emergence of this double trajectory follows another main question, namely what distinguishes the different depictions of the gazelle and what do they convey. This work aims to delineate the role of the gazelle as a naturalistic bearer of meaning. 1.2 Source material The most important source for the depiction of the gazelle is the two- dimensional representation found primarily on wall surfaces but also on objects. There are also a variety of three-dimensional representations, these are mainly in the form of adornments on objects and only exceptionally as sculpture. A chronological review within the different categories of sources provides the reoccurring motifs. The basic motifs established by this review are further clarified in textual references often originating in the so-called religious text corpus. This combination of source material comprises a diversity in terms of form, chronology and geography, while confirming a thematic complex. 2 1.2.1 A representative selection The source material discussed in Chapters 3 through 7 is divided up in terms of chronology with regard to Chapter 3, discussing the Predynastic material; scene type, with regards to Chapters 4 and 5, treating hunt and offering scenes from temple and tomb; and form in Chapter 6, which examines various categories of objects. Chapter 7 that deals primarily, but not exclusively, with the written sources that give an insight into the way in which the gazelle was associated with divine imagery, also has a chronological structure. All in all the material covers approximately 4,000 years, beginning with rock drawings and animal motifs on combs and knife handles and ending with Demotic text references. By dividing the material into these groups, it has, in some instances, been possible to be as thorough as possible, such as with the discussion of some of the objects groups in Chapter 6. Other material, such as the offering procession scenes discussed in Chapter 5, is so abundant that another form of presentation, with a typological slant, has been chosen. In spite of the diversity of the material, it has been possible to identify specific motifs that are both incorporated in a narrative framework and isolated for use as decorative motifs. Some individual representations of the gazelle have been omitted, mostly because they are unique and not part of a larger category. However, even these random examples reflect the gazelle compositions otherwise utilized in the more representative categories. One example of this is the bronze weight in the shape of a recumbent gazelle (New York, MMA 68.139.1; Arnold 1995: 11, cat. no. 4) that corresponds to one of the basic motifs of the gazelle (cf. 4.1.4, Figure 19). The broad collar of Ahhotep (Cairo, CG 52672; Aldred 1971: 202, Pl. 55) has pendants showing fleeing gazelles with their head turned back, referring to a typical gazelle motif (cf. 4.1.2, Figure 18). These two examples illustrate the broad use of gazelle motifs and the need to establish basic forms in order to deal with the diversity of contexts in which they are found. 1.3 Approach This is an empirical study based on the compilation, classification and analysis of primary material. The motifs that have results from the analysis have the character of icons that are bearers of meaning within the context that they are found (Hornung 1973: 40). The large majority of gazelle images do not give the immediate impression of being anything other than naturalistic representations of the 3 animal life of the desert. However, even though the various gazelle motifs can be related to real behaviour, it would be too simple to dismiss them as pictorial reproductions: ”Die ägyptische Kunst hat niemals Konkretes abstrakt dargestellt, sie entfaltet ihre Meisterschaft in der Darstellung des Abstrakten durch konkrete Bilder...” (Hornung 1973: 36). Art and written sources refer to similar concepts (Assmann 2001: 112). There is thus no reason to distinguish between the two as sources for cultural understanding. This similarity between image and text has not however been actualized in terms of a theoretical approach. While the field of semiotics is well established (e.g. Goldwasser 1995), pictorial semiotics is at an initial stage of development, with an emphasis on the impact of imagery on modern society (Sonesson 1989). This discrepancy is also reflected in the general view of the weight of text contra image. The written word is generally treated as reflecting the “real world”, with pictorial representations seen as a allowing a freedom of expression that can extend beyond reality. The nexus between image and word, as means of expressing an idea, which is a particular characteristic of the ancient Egyptian mode of communication, is only beginning to be understood and placed within a theoretical framework. One of the ways of approaching the question of the relationship between image and word in Egyptian art is through the identification of repeated “motifs”, a term used here to represent isolated representations of the gazelle, often found within larger compositions. These motifs display minimal development within these compositions, indicating that they had become “canonical” (Tefnin 1984: 56-57), with a fixed relationship to a concept. The transference of isolated motifs to ‘new’ contexts further underline that the basic gazelle images were expressions of vital notions that were in turn informed by an original context. The form of repeated, and thus selected, motifs clarifies the field within which the concept embodied by the motifs is to be found. The specific preference shown for relating the gazelle to divine feminine imagery is further explicated in the textual sources. This material, it should be noted, is used as support for the implications of the pictorial material, articulating the implicit message of the motifs. The process of analysis, applied here to the imagery of the gazelle, can be described as identifying the basic and often reproduced images, describing what they show and finally tracing the evidence that leads to understanding its meaning (Hornung 1973: 40). 4 1.4 Previous research Only a small number of species, among the many found in ancient Egyptian art, have been the subject of in depth study. These include the hedgehog (von Droste zu Hülshoff 1980), birds (Houlihan 1986) and fish (Brewer and Friedman 1989, Gamer-Wallert 1970). While these general works provide an interesting overview, they only touch upon the question of why these animals are repeatedly represented. One example of the difficulty involved in studying animal imagery in terms of species is illustrated by the work of Stolberg- Stolberg (2003) that attempts to review the occurrence of antelope imagery, however without a well defined structure or aim. The vast majority of the images of the gazelle are found embedded in the well established scenes found in private tombs from the Old, Middle and New Kingdoms. The standard iconography of the tomb has been the subject of several studies (e.g. Klebs 1915-1934, Vandier 1964, 1969 and Decker and Herb 1994). These publications present a thorough examination of the different categories of scenes in the private tombs. The focus is on the chronological development of the different scenes and those compositional changes that take place. These works have provided a framework for an overview of the hunt and offering procession scenes. Harpur’s Decoration in Egyptian Tombs of the Old Kingdom. Studies in Orientation and Scene Content from 1987 illustrates the complexity of analyzing tomb iconography. The size and architecture of the tomb clearly dictated the selection of scenes, which is further reflected by the tomb owner’s status and the times; this is illustrated by the visible difference in the scene content from the earlier part of the Old Kingdom and the later part of the period. Each type of scene followed a schema of basic and established rules. This includes the desert hunt, although it is not cited as a category of its own in Harpur’s study, but only mentioned in passing (Harpur 1987: 82). Harpur demonstrates that the location of each scene is specific. This supports the idea that these scenes are more than decoration, but rather reflect an intent and purpose. The independent existence of motifs is illustrated by Ikram’s article Hunting Hyenas in the Middle Kingdom: the Appropriation of a Royal Image? (Ikram 2003b: 141-147) that traces the origin and reoccurrence of the depiction of a hyena with an arrow piercing its muzzle, found first in a royal context in the 5 th dynasty. This study demonstrates the specificity of the motifs found within the larger hunt narrative. Ikram touches on the issue of “iconicity” when she suggests that the hyena motif was popular due to the connotations it represented, describing the hyena as similar to the lion in 5 terms of “ferocity” (Ikram 2003b: 142). Ikram thus provides an example of not only material but also method similar to that applied in this study. Closer in detailed discussion is Quaegebeur’s article from 1999, “La Naine et le Bouquetin ou l’Énigme de la Barque en Albâtre de Toutankhamoun”. This is an attempt to interpret the well known calcite boat (JE 62120). This discussion of the imagery of the boat, with an ibex head at both prow and stern (cf. Osborn 1987: 244), exemplifies the difficulties involved in dealing with the “antelopes” (gazelle, ibex and oryx) of the desert, all of which appear on objects, temple and tomb walls as well as being found in textual references. Quaegebeur (1999: 21-22) however tends to underestimate the importance of the distinction between the gazelle and the ibex. His discussion demonstrates the problem caused by treating different species as “interchangeables”. This not only results in confusion in terms of description, but also undermines the possibility of an analysis based on the meaning conveyed in the choice of the specific animal. On a more general level, the emergence of a preference for feminine attributes in the image of the gazelle, also reflected in the textual material, requires a more overarching understanding of feminine imagery. The applicability of the “feminine prototype” outlined in Troy’s study Patterns of Queenship (1986: esp. 43-50, cf. also Troy 1997) was an unexpected surprise in the progression of this study. A model that encompassed both the parallels with the cow and the references to the solar eye provided a needed framework for understanding the subtle interconnections found in this multifaceted material. 1.5 Imagery as cultural expression There are few cultures that display the same vast range of imagery found with the ancient Egyptians (Hornung 1973: 35). It plays an important role in the aesthetics of the culture but above all the imagery of Egyptian art is a conveyer of concepts. The relationship of image and meaning is a thread that connects this imagery to the hieroglyphic writing system (Houlihan 2002: 100). Goldwasser (1995: 12) has described hieroglyphs as functioning as “the pictorial representation of a metaphor”. Similarly static iconic motifs, such as those identified for the gazelle, express concepts that are integral to the ancient Egyptian culture. The selection of specific motifs at an early stage in the development of Egyptian art suggests that the individual images did not acquire meaning as the result of later perceived associations but rather that it was the perception of meaning that determined the choice of image (Lévi-Strauss 6 1963: 13, Goldwasser 1995: 26, Mullin 1999: 209). Using the world of animals to express concepts relating to human experience represents the ‘arena’ within which the pictorial representation became an image with meaning (Lévi- Strauss 1963: 61). The famous words of Lévi-Strauss (1963: 89) are well suited to the ancient Egyptian’s choice of animal imagery: “… natural species are chosen not because they are “good to eat” but because they are “good to think””. The extensive, consistent and specific use of this imagery is a feature that characterizes ancient Egypt (Schäfer 1974: 14). 7 2 The Gazelle Observation in the wild is the most likely origin of the attributes given the gazelle in Egyptian art. The earliest images of the gazelle are found in a naturalistic context, as a prey animal hunted by men and dogs (cf. Chapters 3 and 4 below). The desert context is an important element in its depiction as well as in its textual characterisation. Other animals occur together with the gazelle in this environment. The modern lack of familiarity with diversity of desert fauna has on occasion made it difficult for Egyptology to deal with the gazelle as a distinctive image. A review of the life of the gazelle in the wild, as well as descriptions of the animals with which it is commonly associated, reveals characteristics transferred to its depiction in Egyptian art. 2.1 Description The gazelle is represented in ancient Egyptian art with specific and distinct characteristics. 1 The identity of the animal is also often confirmed with accompanying labels reading “gazelle” ( ), commonly written phon- etically. Although some artistic and philological mistakes are found, identification of the gazelle rarely poses a problem when the details of the depiction and context are taken into account. The gazelle is often found together with the ibex and the oryx. Egyptologists, lacking the expertise of the ancient Egyptians, tend to apply the term gazelle to all three. Similarly the term “antelope” is used loosely as descriptive of these three, even though only the gazelle is a member of the subfamily Antilopini. Found together in numerous scenes as desert game (cf. e.g. Mereruka, Duell 1938: Pls 24-25), as well as occurring separately in other contexts, not least as individual motifs, the three animals, the gazelle, ibex and oryx, are distinctively depicted. The gazelle, ibex and oryx are members of different subfamilies of the Bovidae family. Each of the three species represents a separate genus and subgenus (Estes 1992: 63, 115, Kingdon 1997: 445). 1 The descriptions of the different species have been adapted from Osborn (1998), with special reference to the ancient Egyptian material. Additional information concerning anatomical features and behavioural details has been found in Estes (1992). For an understanding of the original distribution of these three species The Mammals of Africa (1971) has been consulted. Kingdon (1997) has provided additional insight. 8 2.1.1 Gazelle (Antilopinae gazella) , The gazelle is “by far the most widely distributed genus of the subfamily of antelopes, ranging from South Africa across Asia and China” (Estes 1992: 63, cf. Kingdon 1997: 409). There are several species of the gazelle represented in Egyptian art: Gazella dama, Gazella dorcas, Gazella leptoceros, Gazella rufifrons, and Gazella subgutturosa (Osborn 1998: 175-180). All of these appear to have been grouped under the heading , the generic term for gazelle (Wb V: 191, 1-9), although given individual traits when depicted. The only to be given a different name is Soemmerring’s gazelle (Gazella soemmerringii), labelled (Osborn 1998: 179). 2 Among the various species of gazelle, the dorcas gazelle is by far the one most commonly depicted in Egyptian art (Brunner-Traut 1977: 426), although other members of the gazelle genus are also found in some number, such as Gazella subgutturosa, “Persian Gazelle” (Osborn 1998: 180), found in the so-called Botanical garden of Tuthmosis III in Karnak (PM II: 120 (407), cf. Osborn 1998: 177-180 for the other gazelle species in ancient Egyptian iconography). a. Dorcas gazelle (Gazella dorcas) The dorcas gazelle is the species that is most frequently depicted in ancient Egyptian art. It is one of the smallest gazelles (Osborn 1998: 176, Kingdon 1997: 410), measuring c. 60 cm at the shoulder, with a length of c. 1 m. An adult animal can weigh up to 20 kg. Although small, it has proportionally the longest legs (Kingdon 1997: 410). This characteristic can be exaggerated in its depiction (e.g. mastaba of Ptahshepshes, Verner 1977: Pl. 41; mastaba of Sekhemka, G 1029, Simpson 1980: Pl. IVc). The tail is short, not more than 20 cm long (Estes 1992: 63, Kingdon 1997: 410) and is occasionally portrayed curled upward (e.g. gazelle statuette, MMA 26.7.1292, Arnold 1995: 10, cat. no. 3). The most distinctive characteristic of the gazelle is its horns, found in both male and female. They are ridged and lyre-shaped, bending backwards in a slightly S-shape. The horn's curve is sharper in the males than the females (cf. Ansell 1971: 58). The horns of the female are occasionally represented with only the tip curved inward (Boessneck 1988: 2 Cf. the rock drawing at el-Hagandia, north o<_>_@___Z\__^_`_%__{|}~_$•__€ ____$••______ ____ of Predynastic date, for individual depictions of the dorcas and Soemmerring’s gazelle. 9 Figure 1. Two dorcas gazelles Fig 79; cf. e.g. Beni Hassan, tomb of Khety, BH 17, Newberry 1894: Pl. 14 and the gazelle headed diadem, MMA 26.8.99, cf. below 6.2.1). The horns of the male can grow to c. 30 cm, while those of the female, with fewer ridges, are shorter, measuring c. 20 cm at most (cf. Estes 1992: 63). These can be exaggerated in length in the Egyptian depictions (Osborn 1998: 175, cf. e.g. the tomb chapel of Meru at Naga el-Deir, Dunham 1937: Pl. XIV/N 3737 and the mastaba of Nefer-seshem-ptah, Capart 1907: Pl. LXXX). The young gazelle does not have fully grown horns (Estes 1992: 63), even though depictions of young animals can feature typical horns, most likely as a way to emphasize the identity of the species (cf. e.g. young gazelles in baskets in the tomb of Niankhkhnum and Khnumhotep, Moussa and Altenmüller 1977: Pl. 34). The coat of the dorcas gazelle can be anything “from pale fawn to dark plum, and is individually and geographically variable (desert forms lightest); white under-parts and rump patch, a dark flank stripe present or absent …” (Estes 1992: 63). The Egyptian artist has often reproduced this colouring. This is particularly evident in the Theban tombs (cf. e.g. the tombs of Menna TT 69, Mekhitarian 1978: 87; Amenemhat, TT 82, Mekhitarian 1978: 41 and Ineni, TT 81, Dziobek 1992: Pl. 16). The dorcas has a white eye ring, and white and brown stripes between the eye and the mouth. The eyes of the gazelle are usually depicted as very large (e.g. Amenemhat, TT 82, Mekhitarian 1978: 41) and almost out of proportion, as are the ears. This emphasis may reflect the importance of hearing and sight for detecting danger (Kingdon 1997: 409-410). b. Soemmerring's gazelle (Nanger soemmerringii) The distinction between the dorcas and Soemmerring’s gazelle is indicated in the 5 th dynasty mastaba tomb of Princess Idut, of Saqqara, where each animal is carefully labelled (Macramallah 1935: Pl. XX), giving the distinctive term for the Soemmerring’s gazelle (cf. Wb V: 206, 2). The dorcas and Soemmerring’s gazelle are found paired in a number of desert hunt scenes 3 . Although size distinguishes these two in real life, they are 3 Cf. e.g. the mortuary temple of Sahure (4.2.1/a). There are also depictions of both the dorcas and Soemmerring’s giving birth in Niuserre’s temple (4.2.1/b). The only example of a mating scene with the Soemmerring’s is found in the mastaba of Nimaatre (4.3.1/c2). 10 Figure 2. Soemmerring’s gazelle depicted as similar in size. The Soemmerring’s gazelle, in reality, is larger than the dorcas, measuring c. 90 cm at the shoulder, compared to the c. 60 cm of the dorcas. It also weighs approximately twice as much as the dorcas at c. 40 kg. Its coat is a darker brown-red than the lighter colouring of the dorcas and it has a black tuff at the end of its tail. Its horns are also more than twice as long as the dorcas, with the horns of the male growing up to 58 cm in length. Like the dorcas, the horns are “lyre-shaped”. 2.1.2 Ibex (Capra ibex nubiana) The ibex, sometimes referred to as an “antelope”, belongs to the Caprini subfamily that includes sheep and goats. Kingdon (1997: 443) describes it as “an advanced type of goat”. The species found in North Africa and modern Israel is Capra ibex nubiana or the Nubian ibex (Kingdon 1997: 445). The Nubian ibex is small in comparison to other ibex. It measures c. 70 cm at the shoulder, with a length of 1.0-1.25 m. It has a maximum weight of 70 kg. The horns of the ibex have a distinctive circular curve (Ansell 1971: 70), going first upward, then back and down. Both male and female have horns, with the male’s horns being much longer, at up to 120 cm, in comparison with those of the female that grow to a mere 35 cm. The horns are heavily ridged with pronounced knobs on the outer curve. The Nubian ibex also has a short tail, of c. 20 cm. The body is compact compared to the slender form of the gazelle. The coat of the Nubian ibex is light brown, with lighter hindquarters. The underbelly is lighter, almost white. The males have a dark stripe along their back as well as on their front legs. Like other members of this subfamily, the male ibex has a beard that is often darker than the main colour of its coat. The female only grows a beard when older (Osborn 1998: 180). The ibex is not only depicted as a prey animal in the desert hunt 4 and in offering lists, but is also found in 3-dimensional representations. One example of this is the ibex-shaped milk jar for which the curved horns could function as handles (cf. e.g. Louvre E 12659, Paris 1981: 226-227). Its form 4 E.g. in the tombs of Raemka, (Hayes 1953: 99, Fig. 56, below 4.3.1/b.1), Senbi (Blackman 1914: Pl. VI, below 4.3.2/b.1), Rekhmire, TT 100 (Davies 1943: Pl. XLIII). 11 Figure 3. Ibex also appears as cosmetic dishes (e.g. Louvre E 11124, Paris 1993: 30 (top)). The ibex appears to be the preferred animal, followed by the oryx, for scarab decoration (cf. 6.8 below), perhaps because the horns were easily carved on a small scale. There are two terms associated with the ibex. The most specific is (alt. , Wb IV: 202, 1-4). In addition, the word is found (cf. Wb I: 79, 1-2). Used for male as well as female, this term has a broader meaning, covering wild game in general (Hannig 1997: 69). 2.1.3 Oryx (Oryx dammah, Oryx beisa) The oryx, also included among the “antelopes” of Egyptian art, belongs to the subfamily Hippotraginae (literally horse- goats). The animals of this family are large, with heavy bodies and thick necks (Kingdon 1997: 435, 439; Estes 1992: 117). The two geni represented in ancient Egyptian art are Oryx dammah (Scimitar-horned oryx) and Oryx beisa (Estes 1992: 115). The oryx dammah is the larger of the two animals, measuring c 120 cm at the shoulder, being close to 2 m long and weighing as much as 200 kg. The oryx beisa is only slightly smaller. Both male and female have long, narrow and essentially parallel horns that can be straight or curve slightly backward (Ansell 1971: 48). Ridges are found on the lower part of the horns, which occur in both male and female. They can grow to be over 1 m long. The tail of the oryx is also much longer than that of either the gazelle or ibex, measuring about 60 cm. Its coat is white with a reddish chest. The distinctive facial markings include vertical stripes of colour. The ancient Egyptian name for the oryx is , literally “seeing white” (Wb II: 11, 4-8; cf. Kees 1941: 26, n. 2), apparently referring to the colouring of the animal, as mainly white (Ansell 1971: 48). The name for the oryx provides the opportunity for a pun in one version of Chapter 112 of the Book of the Dead. (Re speaking to Horus) ‘Look at that black stroke with your hand covering up the sound eye which is there.’ Horus looked at that stroke and said: ‘Behold, I am seeing it as altogether white.’ And that is how the oryx came into being. (cited in Faulkner 1990: 108) 12 Figure 4. Oryx The distinction between the depiction of the gazelle and the oryx can be noted in Sethe’s transcription of the Pyramid Texts, where the horns of each animal are given their distinctive forms (PT § 806c for , and cf. e.g. PT § 972c, N, PT §1799b, N for ). The oryx also has a place in religious iconography. It is found as the prow ornament of the Henu bark of the Sokar Festival (Graindorge- Héreil 1994: 17-18, 62-63). The ibex and the gazelle are also documented as prow ornaments during Predynastic times, the ibex with a few examples (Berger 1992: Fig. 12.73 5 ) and the gazelle only once (Berger 1992: 113, Fig. 8.17), suggesting a connection between desert game and ceremonial barks. The design of the Henu bark, incorporating the oryx head, is documented no later than the Old Kingdom (Brovarski 1984: 1066-1067), with perhaps the best example that found on the walls of the late New Kingdom temple at Medinet Habu (Epigraphic Survey 1940: Pls 196 C, 221-223; PM II: 498, (93)-(95)). The form of the oryx also occurs as cosmetic dishes (cf. EGA 1982: cat. nos 254-256). There are singular examples of the oryx as a royal offering, perhaps as early as the end of the Old Kingdom, with reference to a heavily reconstructed scene from the vestibule of the mortuary temple of Pepi II at Saqqara (cf. Jéquier 1938: Pl. 41 6 ). A more certain example of this motif is dated to the reign of Amenhotep III and is located in the hypostyle in the Luxor temple (PM II: 318, (102), 3). In this scene the animal is positioned as a defeated enemy as the king raises a weapon to dispatch it (Derchain 1962: 9, Fig. 1), suggesting, that the oryx, perhaps representing desert game generically, is associated with powers to be controlled (cf. below 4.2.3/a, Tutankhamun’s painted chest). This is further indicated by what Kákosy (1998: 136) describes as the oryx’s role in the Late Period as the enemy of the Sound Eye, as well as of the moon as Eye (cf. cited works in Derchain 1962: 28-30 and Germond 1989: 54). 2.1.4 Other animals of the desert The gazelle, ibex and oryx were not the only species hunted in the desert scenes. Other common animals include the hartebeest, aurochs and occasionally the addax and fallow deer. The hyena, wild ass and ostrich also appear from time to time in the desert hunt scene. Small animals, such as the 5 Berger (1992: 117) refers____\__^_`_%’s (1974) publication of rock drawings; while most of his references are correct, the rock drawing with an ibex headed prow is not accurately cited. 6 This scene in the vestibule of the mortuary monument of Pepi II (PM III/2: 427 (27)) is very fragmentary and its interpretation should be treated as with caution. 13 hare and hedgehog, add to the multitude of desert species. The variation of animals, although seemingly endless, was partially determined by the trend of the different periods and whether it was a royal or private desert scene. In addition, the combination of desert animals does not always reflect reality (Osborn 1998: 11), with some being distinct desert species and others inhabitants of the savannah. a. Hartebeest (Alcelaphus buselaphus) The (bubal) hartebeest is one of the most common species featured in the desert hunt (e.g. Sahure, 4.2.1/a below; Senbi, 4.3.2/b.1 below; Amenemhat, TT 82, Davies and Gardiner 1915: Pl. IX) and occur in the majority of these scenes. The hartebeest figures in the offering scenes as well, though not to the same extent as in the desert hunt (cf. e.g. Akhethotep, Davies 1901: Pl. XIX). The species belongs to the medium to large sized antelopes (Estes 1992: 133) with a shoulder height measuring 107-150 cm, body length c. 160-215 cm (Kingdon 1997: 429). The most recognizable feature in ancient Egyptian iconography is its horns, generally portrayed in a frontal view, while the rest of the animal is in profile. The horns are U-shaped, with the tips curving ‘sharply’ outward (‘recurved’). They are ridged at the base and the length of them varies from 40 to 75 cm (Estes 1992: 138). The hartebeest muzzle is long and narrow, which is a distinctive feature of its depiction. The tail measures between 30 to 70 cm; this variation is reflected in the representations where the tail length varies greatly (Osborn 1998: 172). The colouring of the coat differs, depending on region and even individual variations within a herd can be observed (Kingdon 1997: 429); “light yellowish- to dark reddish-brown” (Osborn 1998: 172). The belly and hind quarters are lighter in colour than the body. An early depiction of the hartebeest is found on the Narmer macehead from the main deposit in Hierakonpolis. This object features a scene that includes three animals in an enclosure (Quibell 1900: Pl. XXVI, B), all of these can be identified as hartebeest (Osborn 1998: 171) by the shape of the horns and the narrow muzzle. The term (Wb IV: 543, 5-6) for the hartebeest is found e.g. in the OK mastaba of Sekhemankhpath (Simpson 1976: Pl. D). 14 Figure 5. Hartebeests in an enclosure b. Aurochs (Bos primigenus) e.g The aurochs is also referred to as the “wild bull”, in contrast to the domesticated cattle (Bos taurus). The aurochs, like the domesticated cattle, belong to the Bovinae family. The aurochs has a dark coat and long and lyre- shaped horns with a quite broad span. It is the largest animal of the hunted desert species and this is reflected in its depiction. Apart from the lion, the aurochs is found as one of the ‘large’ animals hunted by the king (cf. Tutankhamun’s unguent jar, discussed below at 4.2.3/a.4). In several examples 7 of the desert hunt an aurochs is attacked by a lion, displaying a conflict between two majestic creatures. The lion targets either the muzzle or the neck creating a naturalistic antithetical composition. It has been pointed out by Otto (1950: 170) that the aurochs is regularly depicted confronting its hunter, which could also include human hunters equipped with bow and arrow (cf. e.g. Khnumhotep III, Newberry 1893: Pl. XXX). The aurochs occurs seldom in the offering rows, (the bulls there are generally labelled , ‘cattle’), but is represented by the -foreleg. Consequently Otto (1950: 170-173) regarded the hunt of the aurochs as a part of the ritual of the Opening the Mouth (cf. also Eyre 2002: 193). The term “cattle”, referring to both domesticated and wild animals, is represented by a variety of Egyptian words. The term (Wb V: 94-98) is used in a wide sense, while refers more neutrally to domesticated cattle (Ikram 1995: 14, Wb I: 49, 10-11) and is perhaps the most common in the offering scenes and lists. The term (Wb I: 119-120) is similarly a general term. The aurochs that was to be slaughtered and offered was termed (Eyre 2002: 192, cf. Wb IV: 124-5). The long-horned bull or ox was called (Wb II: 349, 1; cf. Ikram 1995: 8-15 for the various names for cattle). c. Addax (Addax nasomaculatus) The addax belongs to the subfamily Hippotraginae, i.e. the same as the oryx, being somewhat smaller, at c. 110 cm tall, with a length of about 160 cm. The most recognizable feature of the addax is its horns. They are exceptionally long and twisted in a spiral (“corkscrew”, Estes 1992: 115). The addax is quite stocky and the fur is white (cf. the oryx), the head and 7 E.g. In the OK, Seshemnefer (4.3.1/c.1 below), Ptahhotep (4.3.1/b.3 below) and Mereruka (Duell 1938: Pls 24-24), and MK, Senbi (4.3.2/b.1 below). 15 Figure 6. Lion attacking aurochs muzzle have different shades of brown (Kingdon 1997: 442). Compared to other Hippotragini, the addax has short legs and a stocky body, making it a slow runner and easily captured, which may explain the comment that they are apparently “easily tamed in captivity” (Osborn 1998: 159). This may also provide a reason why the addax is more commonly found in the offering rows than as desert prey. The horns are generally depicted in profile, with however one example of a frontal view in the Middle Kingdom desert scene of Djehutihotep at el-Bersheh (Newberry 1895: Pl. VII, right section, c. center row). The addax is most commonly depicted during the Old Kingdom (Osborn 1998: 160) and is sometime identified with the label (Wb II: 226, 15-16). d. Fallow deer (Dama mesopotamica) There are few but distinctive examples of fallow deer in the desert hunt scenes. The fallow deer belongs to the Cervidae family and is distinguishable by its characteristic antlers. Only the male animals grow the branched horns, which “are shed each year” 8 (Kingdon 1997: 338). The coat is yellow-brown with light spots, the belly and the tail is partially white; this can be observed in the tomb of Intef (TT 155, Säve- Söderbergh 1957: Pl. XVI). The examples of representations of fallow deer decreased over time (as do those of the addax), which may reflect the limited number of this animal in North Africa (Kingdon 1997: 338). It is thought to have become extinct in the region by the New Kingdom due to loss of habitat and to “overhunting” (Osborn 1998: 154, cf. also Ikram 1995: 21). The ancient Egyptian term for the fallow deer was (Wb II: 495, 8 Cf. the example in the tomb of Puimre (TT 39, Davies 1922: Pl. VII) where the nursing female is shown with antlers, most likely in order to specify the species. This may however be a ‘mistake’ as it is the gazelle that generally occurs in this motif. An association between the two animals is also possible. Cf. the combination of the gazelle and fallow deer found on the electrum diadem (MMA 68.1361) discussed below as 6.2.2. 16 Figure 8. Fallow deer Figure 7. Addax 19) which is used with consistency. One discrepancy is however found in the Old Kingdom tomb of Ibi at Deir el-Gebrawi (Davis 1902 a: Pl. XI), where a pair of mating roan antelopes (Osborn 1998: 169) has been labelled as and . e. Roan antelope (Hippotragus equinus) , The roan antelope is only infrequently found in the desert hunt scenes or in the offering rows. This is most likely explained by the fact that it does not occur naturally in the Egyptian desert, but is found primarily south of the Sahara (cf. map in Estes 1992: 120). It is tall and robust, with a thick neck. Its horns are curved (Kingdon 1997: 436), although they are not as long and prominent as the ibex (Estes 1992: 120). It seems that there is no specific ancient Egyptian word related to this animal, which may explain the use of the term fem. (Wb II: 495, 19) that more properly refers to the fallow deer (cf. tomb of Ti, Wild 1966: Pl. CLXVI). f. Barbary goat (Ammotragus lervia) The barbary goat can be observed in a few desert hunt and offering scenes. Like the domestic goat (Capra hircus), and the domestic sheep (Ovis aries), the barbary goat is a member of the Caprini family. It is heavily built, with short legs and is described as “intermediate between a sheep and goat” (Kingdon 1997: 444). Again, the shape of the horns, arching outward and then inward, are the best detail to identify this species, commonly portrayed in frontal view. The barbary goat is called in ancient Egyptian (Wb I: 61, 7). This distinguishes it from the domestic goat, for which the term (Wb I: 326, 3) is used. g. Wild ass (Equus asinus africanus) The wild ass appears in a few desert hunt scenes, while the domesticated donkey (Equus asinus asinus) is primarily found in scenes relating to agriculture. Both species are a part of the Equidae family and the wild ass is the ancestor of “all domestic donkeys and asses” (Estes 1992: 235). The wild ass has a grey or fawn coloured coat, with white belly and legs. The mane is short and black and its ears are long and “leaf-shaped” (Kingdon 1997: 310). There is a large number of textual references to the domestic donkey as (Wb I: 165, 6) and this term appears to apply to the wild ass as well. Examples of the wild ass in private scenes are rare. When found, the 17 Figure 9. Barbary goat most characteristic motif is foaling. Examples can be observed e.g. in the Middle Kingdom tombs of Ukhhotep (Blackman 1915a: Pl. VII) and Senbi at Meir (Blackman 1914: Pl. VI) and in the New Kingdom tombs of Montuherkepeshef (TT 20, Davies 1913: Pl. XII) and Kenamun (TT 93, Davies 1930: Pl. XLVIII). The wild ass is not included among the animals of the offering scenes or lists, nor is there direct evidence that the donkey was one of the animals kept for its meat, although this may have been the case (cf. Ikram 1995: 5). At least two examples of hunt scenes where wild ass are the prey can be found. One is on Tutankhamun’s painted chest (cf. discussed below 4.2.3/a.2) and the other is on the south wall of the first pylon in Medinet Habu (Epigraphic Survey 1932: Pls 116-117, cf. 4.2.3/b), both examples of the royal hunt. Even though the wild ass appears as early as the Predynastic period in rock drawings (_____\__^_`_%__{|}~_€ ____‚‚•________________Z__ ___ 14238 (‘Towns Palette’), Asselberghs 1961: Pl. XCII, Fig. 165; cf. also Pl. LXXXIV), hunting this species does not seem to have been common. h. Hyena (Hyena hyena) One of the perhaps most unlikely animals to be hunted in the desert is the striped hyena, known as (Wb III: 203, 16-17). The hyena skull is massive, with powerful jaws and a “blunt muzzle” (Kingdon 1997: 258). The ears are fairly large and pointed. The shoulders are higher than the hind part (Estes 1992: 323), creating a sloping posture. The crest that goes from neck to tail is bushy and spiky, as is the tail. The hunted hyena in the desert scenes are generally seen either fleeing from the arrows or with an arrow piercing its muzzle; this latter composition appears as a motif in Sahure desert scene and was “appropriated” in the private tombs of Middle and New Kingdom (cf. Ikram 2003b, with an extensive discussion on this particular motif). The striped hyena does not only appear in the desert hunt scenes, but also in some of the offering rows (Murray 1905: Pl. VII) and occasionally in the offering list as well (e.g. Seshat-hotep, Junker 1934: 187, Fig. 33). There are a few depictions of attempts to domesticate the hyena (e.g. the Old Kingdom tombs of Kagemni, von Bissing 1905: Pl. XI and Mereruka, Duell 1938: Pl. 153); however such experiments seem to have been restricted to the Old Kingdom and were not very successful (Ikram 1995: 22-23). 18 Figure 10. A hyena with arrows i. Red Fox 9 (Vulpes vulpes) (?) The red fox occurs in the desert hunt scenes, in differing depictions. The most recognizable features of the fox are the pointed ears and muzzle and the long bushy tail. The colouring of the coat varies from red to sand to grey according to season (Kingdon 1997: 221). The fox can be mistaken for the jackal; however, the fox is considerably smaller (both fox and jackals are part of the Canidae family, Estes 1992: 384). The role of the fox is also remarkably varied. It is found attacked by a dog (e.g. tombs of Nefermaat and Rahotep, cf. 4.3.1/a.1-2 below), mating (e.g. Ptahhotep, 4.3.1/b.3 below) or hiding (e.g. tomb of User, TT 21, Davies 1913: Pl. XXII). The most common composition shows a fox sniffing a young animal as it is being born (cf. Montuherkhepeshef, TT 20, 4.3.3/b below). In contrast to the hyena, the fox cannot be found in any offering scenes or lists, nor does there seem to have been any attempts at domestication. Ikram (1995: 22-23) does not mention the fox among those hunted for its meat, and may thus be included in the desert hunt as an attribute of desert topography or as a reminder of the dangers in the desert. There does not seem to be a specific term recorded for the fox and the suggested is primarily applied to the so- called jackal (Wb III: 420, 5 - 421, 5). j. Cape hare (Lepus capensis) The cape or brown hare is a common feature of the desert hunt scenes. It is easily recognized by its long ears, measuring close to a third of the length of head and body, and its long legs and short tail. The colour of the fur varies greatly, from yellow to grey to brown (Kingdon 1997: 153). This variation is also found in the way it is represented (Osborn 1998: 43). The cape hare is well adapted to the desert environment, which is also reflected in the iconography. The hare would have been a common sight in the Egyptian landscape. This may be the background to its occurrence as the biliteral hieroglyphic sign read as . (Gardiner Sign List E 34, for , Wb IV: 268, 11). The hare is depicted fleeing among the other hunted animals and in 9 The other species of fox possibly found in ancient Egypt are the sand or desert fox (Vulpes rueppelli) and the fennec (Fennecus zerda) (cf. Osborn 1998: 73-74). 19 Fox sniffing an ass foal Figure 11. the so-called inserts where it is seen hiding and escaping the hunt, in the same way as the young gazelle. The hare only occurs infrequently in the offering rows, being carried in baskets (e.g. Nebemakhet, Keel 1980: 73, Fig. 32 and Khnumhotep III, Newberry 1983: Pl. XXXV) or grasped by their ears (especially during the New Kingdom, e.g. Amenemhat, TT 53, Wreszinski 1923: Pl. 53 and Nebamun, TT 90, Davies 1923: Pl. XXIII). It is likely that the hare was commonly hunted for food rather than as an offering (Ikram 1995: 22). k. Hedgehog (Paraechinus aethiopicus 10 ) The hedgehog is one of the so-called small animals that are included as prey in the desert hunt scenes. The desert hedgehog has long ears, long limbs, a short tail and spikes that are shorter than those on species found south of the Sahara (Kingdon 1997: 141-142). The hedgehog is depicted striding calmly among the frenzy of fleeing animals. It is also found in the so-called inserts, most likely hiding in the same way as the hare and the gazelle. Two probably related terms are used for the hedgehog, and (Wb III: 121, 15, 122, 7), While the hedgehog hardly formed a part of the ancient Egyptian diet (Ikram 1995: 22), it is still occasionally included in the offering rows, carried in baskets (e.g. tombs of Pehenuka, Harpur 1987: 530, Fig. 188 and Mereruka, Duell 1938: Pl. 191). This is more common during the Old Kingdom, with the occurrence of the hedgehog as offering declining during the succeeding periods. l. Ostrich (Struthio camelus) In contrast to the other hunted animals in the desert scenes, the ostrich represents the only species that is not a mammal but is rather a member of the avifauna group. The ostrich is easily spotted with its long neck and long legs. In the desert scenes, it is shown trying to escape the hunters, generally striding with wings outstretched. Its depiction seems to have been most popular during the Predynastic Period and the New Kingdom (Houlihan 1986: 3). The ostrich egg in particular appears to have been eaten (Ikram 1995: 25). The ostrich is also one of the tributes that Ramses II received from the Nubians (e.g. the Beit el-Wali temple, Roeder 1938: Pl. 9b), possibly 10 Cf. Osborn 1998: 19-20 for the discussion of which species the ancient Egyptian hedgehog belongs to (i.e. either Paraechinus deserti, Paraechinus dorsalis or Paraechinus aethiopicus). See also the extensive study of the hedgehog in ancient Egypt by von Droste zu Hülshoff (1980). 20 suggesting that it was regarded to be an ‘exotic’ animal. It is called (Wb II: 202, 8-11). Mentioned in the Pyramid Texts as an animal that can “open the way” for the dead (§469a, W, N), the ostrich is among those animals that may have had an earlier, now lost, religious significance. Finds of ostrich feathers 11 as well as the role that these play as symbol of both the divinity of kingship, as elements of divine and royal crowns, and of the principle of justice, Maat, indicate iconographic significance. The ostrich feather is also found as a common hieroglyph (cf. Gardiner sign list H 8) used generically to mean “feather”. 2.1.5 Ancient and modern problems of identification Many of the animals found in desert hunt scenes are easily distinguishable and drawn with attention to anatomical details. This is not always the case however and the attributes of similar but different species can be combined in one animal. This is particularly true of those animals grouped together as antelopes. There are examples of animals labelled “gazelle” drawn with the horns of the ibex (e.g. tomb of Pehenuka, Harpur 1987: 530, Fig. 188) or the long tail of the oryx, but with the horns of a gazelle (mastaba of Idu, G 7102, Simpson 1976: Pl. XXVII). In the Beni Hassan tomb of Khnumhotep III (Newberry 1893: Pl. XXXV), a fattened gazelle ( ) 12 is depicted with rather straight horns, more like those of an oryx (Newberry 1893: Pl. XXXV), although similar horns may also be found on some gazelle species (Gentry 1971: 90). The addition of details, properly belonging to another animal, is also found in the depictions of the ibex and oryx. The length of the tail, in particular, can be incorrect. Even with the occasional mix-up in term of details, the identification of individual animals is clear in the majority of the cases, much due to contextual standardisation. The spelling of the word rarely posed any difficulties for the ancient Egyptians, with only rare examples where mistakes have been made. One such example is found in the tomb of Wernu at Saqqara (PM III: 519), where the hieroglyph ( ) was shifted to the end of the word, so that the word above the gazelle reads (Saad 1943: Pl. XLIII). The word ‘gazelle’ has often been used incorrectly in Egyptological works. Helck (1963: 502) for example translated as gazelle and as 11 Ostrich feathers have been found at Hierakonpolis (Friedman 1999: 103) and are mentioned as offerings in the ritual relating to the return of the “Distant” goddess (e.g. Verhoeven and Derchain 1985: 22-23. Cf. Darnell 1995: 70-73 for alternative translation of this section of the Mut Ritual, P. Berlin 3014 + 3053, XVI 6 – XVII 1). 12 Cf. the discussion in Chapter 5.1. 21 antelope. Another frequently repeated error is found in the translation of the name of the 16 th Upper Egyptian nome. It is often referred to as the ‘Gazelle nome’ (e.g. Helck 1977: 391). However, the horns of the animal on the standard clearly indicate that it is an oryx, making the correct name of the nome the ‘Oryx ( ) nome’. The word is not spelled out in the name of the nome, only with the animal occurring on a standard. The same animal is often featured however in the Beni Hassan hunting and offering scenes, where it is specifically referred to as (Khnumhotep III, BH 3, Newberry 1893: Pls XVII, XXXV; Baqt III, BH 15, Newberry 1894: Pl. IV). As Beni Hassan is located in the 16 th Upper Egyptian nome, the occurrence of the oryx in these scenes is significant. Similarly, the term ‘oryx’ ( ) is read as “antilope” by Störck, although he refers mainly to Oryx gazella, and points out (correctly) the use of the term gazelle as “summarisch” (Störck 1973: 319-323). The idea that the term gazelle ( ) is “a generic term used for smaller antelope rather than any specific species” (Ikram 1995: 21) is not reflected in the ancient Egyptian material. There are occasions on which the more general use of the term ‘antelope’ 13 is justified, for example when it is intended as a rudimentary description of a poorly preserved image where an accurate identification is uncertain. Less distinct images, such as those found in rock drawings, present some problems in the interpretation of species and there it is more correct to label an archaic picture of a four-legged, horned animal as an ‘antelope’ than to use specific terminology such as gazelle, ibex or oryx. It is also used here as a collective term for a mixed group of members of the bovidae family. The term antelope does not imply however the classification antilopini. 14 Quaegebeur (1999: 21) describes the ambivalence of the imagery with regard to the gazelle and ibex using the term “interchangeables”. This discussion is immediately followed by a quotation from an inscription from the small temple of Hathor at Philae, reading (‘the female gazelle of the mountain’, Quaegebeur 1999: 21-22). Quaegebeur concludes from this 13 “Antelope” is defined by Estes (1992: 8) in the following way: “Technically, it is the name of the Indian blackbuck, Antilope cervicapra, and applies to the members of its tribe, the Antilopini. In practice, bovids of all tribes apart from cattle (Bovini), sheep and goats (Caprini), and goat-antelopes (Rupicaprini) are called antelopes”. 14_ \__^_`_%_ Z_{|}•_ ___ < ___ __^_____ __@ ____ ___ __________ __„__ _<_ @_ #__ ____ questionable (e.g. Figs 112, 124, 159). Where the identification is uncertain, this is pointed out. He also uses the description “gazellenänliche” (1974: 174). Another label is “Antilopen” (1974: 169-170). Cf. Osborn (1998: _†‚•____\__^_`_%‡_______<_ antelope for ibex. 22 citation that there is a distinctive connection between the ibex and Hathor. He further refers to several examples of the gazelle headed crowns worn by the royal women (cf. below 6.2), first correctly describing them as gazelles and then later in the same text referring to the species as ibex “... le motif de la tête de bouquetin ornant le front des éspouses royales en Egypte...” (Quaegebeur 1999: 40). There are no known examples of ibex protomes adorning the forehead of any royal woman in ancient Egyptian art, this role is reserved for gazelle (cf. Lilyquist 2003: 347-348, Appendix 4), along side the cobra (uraeus) and vulture. 15 It is clear from the primary sources that the ancient Egyptians knew the difference between the gazelle, oryx and ibex, as there were separate names for them, and distinctive representational details to indicate species. This seems to have been the case from the very beginning, as can be seen on a Naqada vase in Brussels (E.2631, de Meulenaere and Limme 1988: 12) where the three animals have been incised with their particular features, i.e. shape of horns, body and tail. The depictions and designations of these animals do not alter with time. A gazelle is rendered with the same anatomical details throughout the life of ancient Egyptian art. The depictions in the tomb of Petosiris (c. 350 B.C.), for example, display clear distinctions between the dorcas gazelle and Soemmerring’s gazelle, and the ibex and oryx (Lefevbre 1924: Pl. XXXV). 2.1.6 Description – concluding remarks Three species, the gazelle, ibex and oryx, are part of a group of animals depicted as desert game that also includes, among others, hartebeest, addax, aurochs, hedgehog, hyena and hare. The gazelle, ibex and oryx are commonly grouped together and regularly represented as desert animals in the offering rows, both in private tombs (e.g. Mereruka, Duell 1938: Pl. 25; Sabi Ibebi, wall fragment (CG 1419), Quaegebeur 1999: 15, Fig. 6) and on temple walls (e.g. Kom Ombo; Quaegebeur 1999: 15, Fig. 7 and below 5.1). This does not mean however that by being grouped, their identities as members of different species is ignored “… since animal icons carry strong iconic power, it is probable that no prototypical member could be generalized to the extent of representing the whole category” (Goldwasser 1995: 87). It is clear that although the three are often found together and even on occasion overlap in depiction, they each had their own distinct iconic identity. 15 One of the gazelle headed diadems has a stag as centre protome, nonetheless flanked by gazelles. Cf. below 6.2.1/a, describing MMA 68.1361. 23 2.2 Habitat and subsistence The gazelle is depicted as a desert animal in Egyptian art. This is the environment for which it is ideally adapted (Kingdon 1997: 411). The dorcas gazelle is found on savannas and in semi-desert and desert environments. 16 These are areas with extreme heat, making the gazelle’s ability to subsist only on the water from the vegetation that makes up their diet (Estes 1992: 9, cf. 65, Table 5.1) of great importance, as is their ability to “store” water, drinking as much as 10% of their body mass per day when water is available. An important food and water source is the various species of acacia, of which they eat the leaves, flowers and pods. There is a correlation between the number of acacia trees and the density of gazelle population, with a large number of trees supporting as many as five individuals per km. They sometimes feed on trees while standing on their hind legs. A study of the dorcas gazelle in the southern Negev (Mendelssohn et al 1995: 4) shows that they spend between two to eight hours a day grazing, travelling over an area of 12 km. There is a migration pattern from winter desert to a summer water source where necessary. When the climate is extreme, the dorcas gazelle live in pairs. Otherwise the herds consist of family groups with one adult male and several female. Herds of five to 12 individuals are common in areas such as wadis that are geographically limited. When the herd migrates however they gather into larger groups. Herds of dorcas gazelle live mainly in the Eastern Desert of Upper Egypt today (Boessneck 1988: 37- 38, cf. Gentry 1971: 89, Kingdon 1997: 410), migrating to the Red Sea coastal area in the summer months. 2.3 Natural behaviour The presentation of the gazelle in ancient Egyptian art is based on observation of the animal in its natural surroundings and when in captivity. The most iconic images derive from the Pre- and Early Dynastic Periods and thus date to a time when hunting may still have been a part of a subsistence strategy. As the gazelle was a prominent game animal, close observation of its behaviour would have been of benefit. Consequently most of the characteristic gazelle motifs relate to the animal’s behaviour in the context of the hunt. Many different stages of the life of this animal are represented in the hunt scenes. 16 This section relies on Mendelssohn et al 1995, which provides a detailed description of the attributes and behaviour of the dorcas gazelle. 24 2.3.1 Mating Gazelles mate sometime between September and November. During this time the male is territorial, marking boundaries with piles of dung. The mating ceremony is described as ritualized, with the male lowering his head, stretching out his neck, as he follows the female with a characteristic pace, lifting a foreleg, and making noises. After circling around, the female responds by lifting her tail. Depictions of mating gazelles are limited, with only four examples found in this material. 17 The rarity of the mating motif, with the exception of those involving cattle, has been observed by Ikram (1991: 51). Images of copulating wild animals are limited to desert hunt scenes, where the natural environment for this activity is depicted. All four examples of mating gazelles are similar in their composition; the female stands on all four legs as she is mounted by the male, who supports himself on two hind legs, corresponding to a realistic mating posture (Estes 1992: 68-69). The accuracy with which the mating gazelles are depicted can be compared with other examples of mating motifs found on tomb walls. Felines, for example, are shown copulating in the highly unlikely standing position (cf. Ikram 1991: 62-63, Tables I-II), whereas the recumbent position is the natural one (Estes 1992: 356, Fig. 21.9). Ikram (1991: 59) offered the following explanation for this discrepancy: “It is possible that the Egyptians had neither the opportunity, nor the inclination to observe these animals in the wild as they are quite dangerous, especially when thus engaged.” 2.3.2 Giving birth Gazelles carry their young for about six months. The mother alternates between standing and lying down during labour. The fawn stands up to nurse after about 20 minutes. When not feeding, the young hides in the grass. A different place is chosen to hide the fawn after each feeding, with the mother keeping watch from a distance. When food is plentiful, gazelles can reproduce twice a year. Depictions of gazelles giving birth appear to be limited during the Old Kingdom to the royal mortuary temples of Niuserre (PM III/1: 319-324, von Bissing 1956: Pls XI, XII) and Unas 18 (PM III/2: 419, Hassan 1938: Pl. 17 In the tombs of Seshemnefer (Junker 1953: Fig. 63), Nimaatre (Roth 1995: Pl. 95b), Ukhhotep, (Blackman 1915a: Pl. VII) and on a silver jar (CG 53262/JE 39867, Edgar 1925: Pl. I, Fig. 1). Cf. Appendix III. 18 The blocks from the causeway of Unas show hartebeest and roan antelope foaling (Osborn 1998: 169). The two gazelles (dorcas and Soemmerring’s) found in this group are most likely giving birth as well, unfortunately only the head of these two animals remain. 25 CXVII A). The gazelles are seen foaling standing, corresponding to natural behaviour. A single example of a gazelle giving birth in a recumbent position is included in the Middle Kingdom tomb of Khnumhotep III at Beni Hassan (PM IV: 145, (7)-(11); Newberry 1893: Pl. XXX). The foaling takes place in a so-called insert, separate from the register of the desert hunt. The mother has her head turned back, as if watching for danger. This image of a gazelle giving birth while lying down is unique. 19 2.3.3 Nursing the young The motif of a nursing gazelle in the desert hunt scenes appears in several of the Old Kingdom private tombs, followed by three examples dating to the Middle and New Kingdom 20 as well. The composition of mother and young is located among the chaos of fleeing animals, creating a contrast to the hunting frenzy. The act of nursing is also observable in several Old Kingdom offering scenes (e.g. Rawer II, G 5470, Junker 1938: 233, Fig. 48; Kadua, Hassan 1951: Pl. XLVI and Kagemni, von Bissing 1905: Pl. VII). This image is thus found in two different contexts: the hunt scene and the offering procession. The gazelle is the only wild animal depicted nursing, with the exception of the (Persian) fallow deer (dama dama mesopotamica, Osborn 1998: 154) in the New Kingdom tomb of Puimre (TT 39, Davies 1922: Pl. VII, cf. discussion above). Otherwise, it is only a small number of domesticated animals (e.g. cow, goat, donkey) that are shown nursing their young. The image of the nursing gazelle, when found in an offering row (cf. Chapter 5) has certain similarities to that of the domesticated cow nursing its calf. Both the cow and the gazelle are shown with the head turned back while nursing in some examples. Another shared detail is the depiction of the mother raising a hind leg to scratch an ear or muzzle (cf. Smith 1949: 327, Fig. 205; 363, Fig. 237; Vandier 1969: 67, Fig. 44; 71, Fig. 48). Common details are mainly found in material from the Old Kingdom. The nursing 19 Compare the imagery of the Wadi Hammamat inscription known as the Miracle of the Gazelle, where the mother is described as having her head turned back (Couyat and Montet 1913: 77-78) and below at 7.3. 20 The Middle Kingdom example of a nursing gazelle in a desert hunt scene is located in the tomb of Senbi at Meir (cf. below 4.3.2/b.1). The New Kingdom desert hunt scene of Montuherkhepeshef (TT 20) also features a nursing gazelle among the hunting frenzy (cf. below 4.3.3/a). The third example is found on the embroidered tunic of Tutankhamun (cf. below 4.2.3/a.3). Cf. Appendix III. 26 gazelle with raised hind leg is, for example, observable in the desert hunting scene of Ptahhotep (PM III/2: 601 (17), Davies 1900: Pl. XXI). Alongside that of the hunted gazelle, the picture of a nursing gazelle is used as an individual motif found e.g. on minor objects (cf. below 6.4 and 6.5). In a few of the nursing scenes the gazelle mother grazes or nibbles on a small bush. This variation on grazing developed into the so-called palmette motif, where two gazelles stand on either side of the palmette, nibbling on the stylized tree (cf. below 6.4) providing an example of its adaptation to the arid environment with sparse vegetation (Estes 1992: 64, Kingdon 1997: 411). 2.3.4 Protecting the young The antelope family has a specific strategy that optimizes the survival of their young. It hides the fawns from predators. The antelope family is thus labelled as “hiders” (Estes 1992: 17). Once the fawn has been born, it lies still, hidden in crevices, behind bushes and small trees and remains in hiding most of the time (depending on species). This hiding behaviour is limited to the period when the animal is young (Kingdon 1997: 410). The mother stays away from the hiding place to avoid drawing attention to it. The young leaves the hiding place when the mother calls, either for suckling or when the herd moves to new grazing areas. In addition to concealment, this behaviour has the additional benefit of containing the smell of the fawn “during the concealment stage” (Estes 1992: 17). This natural behaviour is observable in the desert hunt scenes, where the young gazelle is seen recumbent. The gazelle fawn can have its head turned back, a posture corresponding to the natural behaviour of a hider. The young animals in the grass provide an isolated motif often represented in the so-called insert, 21 a small image with its own ground line placed in the middle of a register (cf. below 4.1.4). The gazelle is much more frequently depicted in the inserts than the ibex and oryx. 22 Other common desert species such as the hare, hedgehog and jerboa, all small nocturnal animals living in burrows (Kingdon 1997: 153, 142, 191), are also found in inserts. Even though young animals generally escape predators by hiding, they are easily located if one searches. A gazelle mother, standing at some distance away to divert attention from her fawn, starts prancing if she senses danger (Osborn 1998: 176, Estes 1992: 13, cf. also 24, Table 2.4). This 21 The term is adapted from Osborn 1998: 61, 70, 103 and passim. Cf. below 4.1.4. 22 Cf. the tombs of Mereruka (Duell 1938: Pl. 25), Meryteti (Decker and Herb 1994: Pl. CXL (J 40) and Niankhkhnum and Khnumhotep (Moussa and Altenmüller 1977: Pl. 40) where the young of what is most likely ibex and oryx are included in the inserts. 27 makes it simple to find and collect a fawn, even with its mother looking on. The tendency for the mother to keep close to her young also makes her vulnerable. The collection of young gazelles is thought to be represented in the so-called basket motif (Osborn 1998: 176, cf. 5.1.1/b.3). A man in a hunting scene (below 4.3.1/b.5), as well as an offer bearer in an offering scene (below 5.1.1/b.3), can be found carrying a pole across the shoulders, with baskets hanging from either end, containing young gazelles. While the gazelle is one of the most common animals portrayed in this motif, hares and hedgehogs, also found in the inserts, are also among the animals carried in such baskets. 2.3.5 Fleeing the predator The oldest gazelle motif features it as a prey animal (cf. Chapter 3). In the wild, the gazelle is common prey for most of the large felines (e.g. lion, leopard and cheetah). In the desert hunt scenes the role of predator is commonly played by the hunting dog. The speed of the gazelle, up to 80 km an hour (Mendelssohn et al 1995: 4), is its primary strength when facing a predator. Its slender limbs are said to be an adaptation for “greater mobility and speed” (Kingdon 1997: 409). Only the cheetah, among the feline predators, can outrun it (Estes 1992: 70). Furthermore, the gazelle can change direction when running at full speed, which is not possible for the lion that has a wide turning circle. 23 The combination of stamina and being able to change direction swiftly works in the gazelle’s favour, increasing the odds for surviving an attack (Estes 1992: 70). When a predator catches up with the gazelle, it knocks down the fleeing animal by seizing its hind leg. This is frequently shown in the desert hunt scenes. Commonly, a hunting dog is depicted lunging at the gazelle’s hind leg, bringing it to a halt, and causing it to somersault, with the gazelle ending up on its back. In the tomb of Ibi (4.3.1/d.1 cf. below), the verb “to grasp, hold fast” (cf. Faulkner 1962: 145) is used to describe the downing of the gazelle. It is then killed by strangulation as the jaws of the predator grip its neck. This moment is transformed into an iconic motif. The gazelle uses both its sight and hearing to detect danger, with its sense of smell being of secondary importance. The gazelle is “exceptionally alert to both sound and movement” (Kingdon 1997: 409). It is however their vision that is especially important. Their eyes are “laterally placed with 23 Cf. the occurrence of a dog in the upper register in the tomb of Puimre, TT 39 (Davies 1922: Pl.VII) as an example of circling in the chase. 28 horizontally elongated pupils (providing good rear view)” (Estes 1992: 7). Their good vision may have developed in connection with a shift to a semi-desert habitat with its open landscape (Kingdon 1997: 410) and it is said that they can see a waving arm from one kilometre away (Mendelssohn et al 1995: 3). With such exceptional vision, turning the head to see the pursuing predator, is an effective strategy and explains the choice of the motif of the fleeing gazelle with its head turned back. Although this behaviour is not limited to the gazelle, it becomes a common image of that animal. The gazelle as a game animal pursued by a predator, produced four basic images that reoccur as standard motifs: 1) fleeing in high speed, 2) fleeing looking back, 3) being knocked down, caught by hind leg and 4) downed and choked by throat. These images reflect a realistic hunt sequence, with one exception. The gazelle is rarely portrayed as escaping its pursuer, whereas in reality its speed and agility gives it a fair chance to elude both the animal and human hunter. The motif of the hunting dog chasing a fleeing gazelle, first seen in the Predynastic Period, is used as an ‘abbreviated’ version of a desert hunting scene, embodying a sequence that resulted in the predetermined fate of the gazelle as prey. The iconic nature of this image is illustrated by its use in the love poetry of the New Kingdom. In the second group of poems from Papyrus Chester Beatty I (verso G 2, 1-5, stanza 3; cf. Mathieu 1996: 31-32, Pl. 6, and Lichtheim 1976: 186-187), the theme is the lover’s hurried pursuit of his beloved. He is compared first with a messenger, then a horse and finally a gazelle. Each stanza begins with the refrain “O that you might come to the sister quickly” ( ). The flight of the gazelle is described in the following terms. O, that you might come to the sister quickly Like a gazelle leaping in the desert ! " Its legs running though its limbs are weary # Terror enters its limbs A hunter is after him, and dogs are with him (Still) they do not see its dust Stanza 3 (2,1 - 2,5) 2.3.6 Natural behaviour - concluding remarks The natural behaviour of the gazelle, as observed by the Egyptian artist was analyzed into a number of key motifs. The variation displayed in the depictions of the gazelle suggests that its association with the desert hunt is 29 central, with the dog-attacking-gazelle surviving as one of the most durable images in ancient Egyptian iconography. The regeneration cycle, beginning with mating, followed by giving birth, is only exceptionally represented. The motif of the young gazelle is, on the other hand, frequently found, either nursing or hiding on the insert. The young gazelles in baskets functioned as a further extension of this focus on the fawn. Used in contexts other than the desert hunt, the motifs of nursing and hiding gazelle appear to carry specific connotations. 2.4 Domestication Although there may have been attempts to maintain captive gazelle herds during the Predynastic Period (Flores 1999: 37, 83-84), this did not result in true domestication, which is defined as not only the survival of the individual animals in captivity, but also breeding over several generations. There are several reasons why domestication would have been difficult. Among these is the structure of the herd in the wild, where it is divided into various groups, depending on season, gender and age, with the male and female being separated for most of the time (Estes 1992: 66, cf. 65, Table 5.1), a pattern which would have been difficult to achieve in captivity. Furthermore, with the Egyptians’ protein supply derived mainly from cattle, sheep and goats (Ikram 1995: 8-19), a domestication of the gazelle as a food animal was not necessary. As game, the animals, especially those injured or killed, would have been “dealt with on the spot” (Ikram 1995: 54). Slaughtering would also have taken place in the desert. Some of the desert hunt scenes feature a slaughtering scene where an animal hangs from a tree, being gutted by a butcher (e.g. Niuserre, von Bissing 1956: Pl. XI b). In the instances where the animals are captured for later use, the depictions show them being fattened prior to slaughter, after which they were either offered or eaten. Other than as food, individual gazelles may have been kept as “pets”, albeit infrequently. There is a depiction of possibly two gazelle pets on the eastern wall in the tomb of Meryre II at Amarna (Davies 1905: Pl. XXXVII). All six princesses stand behind (or next to) the seated pharaoh, who receives tribute. According to Davies, two of the six daughters of Akhenaton and Nefertiti are portrayed carrying a small animal: “Nefer-neferu-aten seems to be holding up a tiny gazelle, and her sister behind has a similar pet on her right arm… ” (Davies 1905: 39). Due to damage it is difficult to say anything about the first animal, while the second animal has its head turned back; a posture common for the gazelle. The identification of this second gazelle is 30 established in the drawing of Lepsius (LD III: Pl. 99b), where one can observe that the short tail is curled upward, in a manner typical for a gazelle (this is not visible in the drawing of Davies). The small size of the animals suggests that they were young. The posture of the second gazelle would further confirm the idea of a fawn. Private tomb iconography does not indicate a widespread habit of keeping gazelles as pets. The owners of the New Kingdom tombs have sometime included images of animals interpreted as pets, such as monkeys and cats, under their chairs (cf. e.g. Anen, TT 120, Malek 1993: 60, Fig. 34; Menkheperraseneb, TT 112, Davies 1933: Pl. XXIV; Ipuy, TT 217, Davies 1927: Pl. XXV). It is first in the Saite tombs of Pabasa (TT 279, Steindorff and Wolf 1936: Pl. 17) and Ibi (TT 36: MMA photo 965) at ‘Asâsîf, that a gazelle is found in this context, suggesting that it might have been kept as a pet of the tomb owners (Houlihan 1996: 108-111). Other evidence for the occurrence of the gazelle as a pet is found in two gazelle mummies, both belonging to female owners; i.e. Isetemkheb D and Ankhshepenwepet (Ikram 2003a: 79). Isetemkheb D (cf. Dodson and Hilton 2004: 206) was the wife of Pinudjem II, who was the high priest of Amun and ruled during the theocracy of the 21 st dynasty in Thebes. Among the objects found in the Deir el-Bahri cachette (Bab el-Gasus, TT 320, PM I/2: 663-664, no. 7) was a wooden coffin in the form of a ‘standing’ gazelle (Cairo, JE 26227). Only the horns place this identification in question (Maspero 1889: Pl. XXI B). While the curve of the horns is reminiscent of an ibex, the small size of the coffin is more appropriate for a gazelle. Inside the coffin was the mummy of a dorcas gazelle, embalmed in the same style as human mummies of this period (Ikram 2003a: 80). The second gazelle mummy is associated with a woman called Ankh-shepenwepet, a singer of Amun from the 23 rd dynasty (PM I/2: 628). A gazelle mummy was recovered from her Deir el-Bahari tomb (no. 56, cf. PM I/2: Plan VIII; Winlock 1924: 30, Fig. 35). The gazelle mummy had been buried at the foot of her coffin, alongside the canopic jars and two boxes of ushebtis (Winlock 1924: 30). These two examples of gazelle mummies buried together with their female owners would indicate a special status for these individual gazelles. 24 The examples of gazelle pets are few but distinctive. A common denominator is that the owners are female. The gazelle appears to have had 24 These two examples of gazelle ’pets’ may be compared to the baboon mummy (CG 61088a sic) associated with Maatkare (Ikram and Dodson 1998: 126, Fig. 132), also buried with its female owner. Again, the exact nature of this individual mummy is difficult to establish. 31 an iconographic association with women of subordinate rank during the New Kingdom (Troy 1986: 129), and the few occurrences of gazelles as pets may be examples of this association. These individual examples of gazelle pets are unique and the two burials give further indications of the importance ascribed to the gazelle. 2.5 The gazelle - concluding remarks The depiction of the gazelle indicates that its natural behaviour was well known to those who developed the imagery of ancient Egyptian art. The animal was important as desert game, as well as for being the object of later slaughter. Its meat may have been part of the diet of the elite, and as an offering it was food for the gods. The fawns could also be collected separately for the same purpose, and exceptionally to become pets. The natural behaviour of the gazelle, particularly in the context of the hunt, was analyzed in a series of motifs, such as the fleeing gazelle, the nursing gazelle and the recumbent fawn in hiding. These images take on an iconic character and are abstracted from the hunting scene and transferred to other contexts. The manner in which this occurred is described in the following chapters. 32 3 The Initial Images – Pre- and Early Dynastic Sources The Predynastic Period, and more specifically the Naqada Period (Naqada IA- IIIC1, c. 3900 – 3100 B.C., cf. Hendrickx 1996: 64) sees the development of a material culture that served as the foundation for the cultural identity of a unified Egypt. This unification, interpreted as the product of a southern cultural, and later political, incursion into the north (cf. e.g. Bard 2000: 62-63) was facilitated by the spread of images, artefacts and techniques (cf. Wengrow 2006: 72) from primarily Middle and Upper Egypt to the north. The images emanated from a limited number of narratives, two of which stand out in particular, the journey by water and the hunt. The former is represented in rock art by numerous depictions of boats, with similar images being found on ceramics. The hunt and the related activity of animal domestication have a broader decorative use, occurring on a large variety of surfaces and with individual motifs also sculpted in three-dimensional forms. The images of the hunt characteristically depict one or more hunters and the wild game found on the margins of the Nile Valley. This landscape, the hunt, and the game animals that were its primary targets, are characterized by the term “desert”, an area in sharp contrast to the fertile valley. Created by the gradual reduction of seasonal rain, the desert area found just beyond the margins of the valley had limited vegetation and water resources, bringing game closer in to the valley and the human settlements there (Roubet and el- Hadidi 1981: 462-463, Midant-Reynes 2000: 232). Al-though the population of the Predynastic Period was largely oriented towards agriculture and pastoralism, the proximity of this game encouraged hunting as a secondary subsistence strategy (Brewer 1991: 288). The gazelle became an important game animal, particularly because of its large population: “Les genres de vie pratiqués montrent une bonne adaption à un milieu plutôt favourable aux gazelles…” (Roubet and el-Hadidi 1981: 464). This land-scape and its animal life, including the gazelle, took on an iconic character in Egyptian art, with a special funerary association, particularly with regard to the depiction of the desert hunt. The representations of the gazelle vary greatly in terms of medium of expression. In rock art and on the surface of pottery, the images are two- dimensional. Gazelle and other animal motifs are also found in three- dimensions on objects such as combs and hairpins. Knife handles and ceremonial palettes, carved in raised relief, are covered with an abundance of 33 game animals, as if to stress an access to ‘herds’ of animals. Common for these different forms of depiction is the focus on desert game with the activities of the hunt only occasionally included as a theme. The desert landscape is implied by the representation of the characteristic animal life. 3.1 Rock drawings The hunt dominates the themes represented in rock drawings (cf. Muzzolini 1986: 80). The hunter in these scenes can be a dog or a lion, as well as a man. Animals belonging to the bovidae family, including the gazelle (cf. _________•__________„____#_„„_______ #_____„__Z#<__\__^_`_%__{|}~__|}__ Midant-Reynes 2000: 151), other animals, such as giraffes, ostriches, hippopotami and elephants are found less frequently. The most common depictio___<________________@__ _____ ___Z_____\__^_`_%__{|}~_€ __________‚__ 116, 124, 131, 134, 135, 136 and passim). Scenes in which a hunting dog ____#%______________Z_____\__^_`_%__{|}~__€ _____{____†•_______##____‰_ __ ____ motif that becomes standardized and established in dynastic art. The majority of rock drawings are found in what is today desert or border areas just beyond the cultivated land. In the Nile Valley, they are found from approximately Luxor south to Khartoum (Midant-Reynes 1994: 229, Wengrow 2006: 111-114, cf. also map in Muzzolini 1986: 22). This area is also known for traces of Predynastic settlements (cf. Friedman 1994, Wengrow 2006: 75). It is not possible to classify the rock drawings as belonging to either a domestic or ritual context. The boat motif (Berger 1992: 107) can be found, however, with standing human figures with upraised hands, commonly interpreted as mourners, dancers or as in positions of adoration (Berger 1992: 116, Midant-Reynes 1994: 230), implying religious significance. The dating of rock drawings is notoriously difficult (cf. e.g. Midant- Reynes 2000: 151, Muzzolini 1986: 24). The patina of the rock has been used as a tentative criterion for the chronology of the rock drawings (Wengrow 2006: 111). This is regarded as haphazard, with a sequential date treated as more ‘accurate’ (Muzzolini 1986: 23). Attempts to date these representations by comparing them with those on Predynastic pottery (C- and D-ware) have also been made. This is difficult however as the same range of motifs is not found in both rock art and on ceramics (Midant-Reynes 1994: 230, 232). The similarity of the motifs on C- and D-ware (cf. below 3.2) to those in rock drawings does suggest a chronological correlation (Midant-Reynes 1994: 234), indicating that at least some the rock drawings are of Predynastic date. 34 3.2 Ceramics Two categories of funerary ceramics of the Naqada Periods I and II 25 (c. 3900- 3300 B.C.) are commonly decorated. These are known as C-ware and D-ware. The term C-ware is used for the earlier (Naqada I) red polished ware with white crossed-lined decoration (Petrie 1901: 14, Gaballa 1976: 9). The D-ware (“decorated ware”, Naqada II) has the reverse colouring, with the marl clay giving a cream coloured background on which dark red paint is used (e.g. Petrie 1901: 15, Pls XIV-XVI; Friedman 1994: 195). The C-ware is mainly decorated with geometrical designs, such as zigzags, wavy lines and so forth, possibly imitating basketry (Gaballa 1976: 10, Needler 1984: 183). The motif of the hunt, as well as images of individual animals, occurs only sporadically on the C-ware and thus it is difficult to treat these images as representing separate categories (Wengrow 2006: 103-104). It is the D-ware, (Nagada II, c. 3650-3300 B.C., cf. Hendrickx 1996: 64) that has a fixed, and easily recognizable thematic decoration. A common motif is the boat with multiple oars, human figures with upraised arms (Gaballa 1976: 11, Wengrow 2006: 109). These scenes are similar to those found as rock drawings. 26 The gazelle, along with other animals classified as desert game, are also found in these scenes. The choice of animals for the D-ware scenes indicates a conscious reference to the desert landscape, although the hunting theme is notably absent. With the boat as one of the central images (cf. Monnet Saleh 1983: 275), the animal imagery, that includes the gazelle, provokes a number of possible interpretations. A pragmatic interpretation sees these animals as food for the dead (Wengrow 2006: 107, cf. also Friedman 1994: 250). It should however be pointed out that these artefacts originate from a farming and pastoral culture, with domesticates rather than desert game serving as the primary food animals (cf. Friedman 1994: 861, McArdle 1992: 56, Ikram 1995: 5-39 and Brewer 2002). A more cosmologi- 25 Nagada I – IIB dates approximately to 3900 – 3650 B.C., while Nagada IIC-IID2 is tentatively dated to 3650 – 3300 B.C. (Hendrickx 1996: 64, cf. also Wengrow 2006: 93). 26 Needler (1984: 202) writes “The far greater number of “D” vessels that have survived might misleadingly suggest greater diversity of pictorial motifs than the “C” ware exhibits; actually, the “D” vessels appear to have had a comparatively limited repertory, and even in the case of human figures, which like the boats show some variation in disposition and detail there seems to have been little incentive to improvise”. Cf. also Friedman 1994: 860. 35 Figure 12. Desert game on D-ware cal perspective sees the desert as a region apart from an ordered world that is perhaps represented by the boat on the Nile (cf. e.g. Berger 1982: 64). With the absence of the hunting motif, the animals depicted on the vessels can also be interpreted as primarily an environmental element, seen either in relationship to the boat or as part of the topography of a landscape that may be intended as the destination of the immortal dead. 27 The gazelle in this context is best described as an indicator of desert topography. 3.3 Knife handles Decorated handles, carved in bone or ivory, are fitted on flint knives and occur as funerary gifts during the Naqada II-III Periods (c. 3650-2900 B.C., Midant-Reynes 1987: 212, Whitehouse 2002: 425, Wengrow 2006: 184). The representations found on the knife handles are almost entirely of game animals. These are often arranged in registers, as a series of identical striding figures. Prominent examples of this composition are found on the Brooklyn knife handle, (no. 09.889.118, Needler 1984: Pl. 68; Asselberghs 1961: Pls XXIX-XXX) and the Carnarvon knife handle (MMA 26.7.1281, Bénédite 1918: Pls 1-2; Asselberghs 1961: Pl. XXXII). The gazelle occurs sporadically among those animals represented. A striding gazelle is distinguishable on the knife handle from the Pitt-Rivers’ collection (Petrie and Quibell 1896: 51, Pl. 77; Asselberghs 1961: Pl. XXXI), while the Gebel el-Arak handle (Louvre E11517, Asselberghs 1961: Pls XXXVIII-XXXIX) and the Gebel Tarif handle (Cairo 14265, Asselberghs 1961: Pl. XXXIII) have antelopes that might be gazelles. The majority of published handles do not, however, include a gazelle in their decoration. This may be attributed to the emphasis on what might be interpreted as a herd motif. 3.3.1 The Petrie Museum Knife handle (UC 16295, Petrie 1920: Pl. XLVIII, 6) There are, however, some examples that display the hunt motif, such as the knife handle found in the Petrie Museum, depicting a canine 28 attacking a 27 Friedman 1994: 251 writes “Not only may the funerary function differ from the original purpose of the vessel because the vessel is simply being reused, but also the funerary ritual may dictate its own specific shapes for specific funerary functions”. 28 Although it is difficult to definitely identity the attacking animal as more than a “canine”, given the most common version of this motif, it may be safe to say that the hunter is a dog (cf. 36 gazelle. The gazelle is shown with its head turned back, a pose that will be frequently used in the later tomb art (cf. 2.3.5 and 4.1.2, Fig. 18), with this being a very early example of this motif. The reverse side of the handle has another version of the hunt that includes a figure that is similar to that of the goddess Taweret, depicted as a pregnant woman with the tail of a crocodile along her back (Petrie 1920: 13, Pl. XLVIII, 5). The image of a crocodile is also found. 29 These two elements suggest an abbreviated marsh hunt scene, another theme that has an early expression here. This interpretation of the knife handle’s decoration sees the desert hunt on one side with the marsh hunt on the other, providing an early version of the combination of these complementary landscapes. The decoration on the knife handles seems to have concentrated on the animals of the desert as the main theme (Wengrow 2006: 181. Cf. also Whitehouse 2002: 444-445, Tables I-II; Midant-Reynes 1987: 209). They also display an unusually uniform choice of motif, excluding other contemporary themes such as boats or human figures (Whitehouse 2002: 432). The rather limited number of motifs is possibly the result of the lack of space (cf. the discussion of scarabs in 6.8 below). It may also be noted that the images on these ivory pieces are in raised relief, indicating that considerable effort was devoted to the decoration of these handles, thus suggesting the significance of the decoration. The function of the knife in slaughtering and the cutting of meat may have influenced the choice of themes, while ensuring that the knife, as a funerary gift, would come to such ‘use’ in the next life, even though many of them “had been systematically deconstructed before deposition” (Whitehouse 2002: 432). 3.4 Combs and hairpins Combs and hairpins are also often of bone or ivory and decorated with zoomorphic motifs (e.g. Petrie 1920: Pls VIII, XXIX; Martín Del Río Álvarez and Almenara 2004: 881-889). Although infrequent, a few examples Osborn 1998: 59 who cites it as a “saluki”). The dorcas gazelle is on the other hand clearly the intended animal. 29 Cf. Stockholm palette EM 6000, discussed below, with representations of both hippopotamus and gazelle. 37 Figure 13. Petrie Museum knife handle of the gazelle as part of a comb handle can be found (Ashmolean Museum 1895.943, from Naqada grave no. 1687 and no. 1895.935 from Naqada grave 1497, cf. Wengrow 2006: 100, Fig. 5.1, second from right). Hair pins are most commonly decorated with the bird motif (Petrie 1920: 30). Again, however, a few examples featuring the gazelle can be identified (Petrie 1920: Pl. VIII, 1, cf. UC 15459 unpublished). In contrast to the other Predynastic sources discussed above, the decoration of combs and hair pins, rather than relating to the hunt, consists of simple single representations. 3.5 Palettes The cosmetic palette provided the surface on which eye paint could be ground (Davis 1992: 74-75, O’Connor 2002: 8). It is found as a common part of the elite burial equipment of the Naqada culture. It is also found in a temple context where it appears to have had a ceremonial function. Both groups of palettes, funerary and those related to temple ceremonies, are relevant to this discussion. The majority of palettes are funerary objects. These palettes have either a geometric form, with the rhomboid shape being most prominent and the rectangle as its last expression, or are in the shape of animals, primarily fish, birds and turtles but also rams and dogs (cf. e.g. Petrie 1921: Pls LII-LIX, Asselberghs 1961: Pls XLIV-XCI). The top of a palette fragment now in the British Museum (BM 32074, Asselberghs 1961: Pls LXVIII-LXIX) has, unusually, the shape of a reclined gazelle. The surface of this type of palette rarely has more than a simple decoration, often related to its shape. The ‘ceremonial’ or possibly ‘votive’ palettes have elaborate, iconographic compositions carved in raised relief (O’Connor 2002: 5, 9). Even though it is unlikely that these palettes were intended for practical use, many have a circular indented grinding surface, some of which are incorporated into the decoration of the surface. Palettes decorated with raised relief were, according to Spencer (1993: 51), “never destined for funerary use but were votive objects kept in the temples” (cf. also Millet 1990: 53). Both of the ceremonial palettes found in situ, the Narmer Palette and the Two Dogs Palette, come from the temple at Hierakonpolis (Quibell and Green 1902: Pl. XXVIII, Kemp 2006: 84, 94). The gazelle is found among the animals included in detailed raised reliefs of “ceremonial” palettes that depict the hunt of wild game. Once again 38 Figure 14. Predynastic comb a preference for desert animals can be observed. In addition, mythological creatures such as griffins and serpopards are also found. Human figures are only exceptionally depicted. The identification of the different species of animals seldom poses any difficulty. On the contrary, the artists appear to have put great effort into the anatomically distinctive details of each individual animal. 3.5.1 The Hunters Palette (BM 20790, BM 20792; Louvre E 11254; Asselberghs 1961: Pls LXV - LXVII) The palette known as the Hunters Palette (also called the Lion Hunt Palette 30 ), is broken into pieces, currently divided between the British Museum and the Louvre. Shaped like an elongated triangle with rounded corners, there is a round recess for grinding eye paint in the centre. The hunters, 16 in all on the preserved pieces, are found standing along the two edges of the palette, with a wounded lion, arrows protruding from the shoulder and head, found at either end. The inner space, between the two lines of hunters, is filled with other fleeing animals. Two gazelles can be distinguished in this group that also include a fox, fallow deer, hartebeest, ostrich and a hare. The pose of the animal identified as a fox by Osborn (1998: 3), is that of the hunting dog (or lion), as it seizes a fleeing animal by the hind leg, here a fallow deer. The gazelle is represented by the image of an adult female and its fawn (cf. Osborn 1998: 3), a relationship that is frequently emphasized during later periods. Both the adult and the young gazelle are shown with their heads turned back, yet another feature characteristic of later dynastic iconography. With the gazelle pair, this palette introduces a variation of the “gazelle as prey” motif into the hunting narrative. The elaborate composition of the relief on this palette has encouraged Tefnin (1979: 218-244) to discuss what he sees as the highly intentional arrangement of figures. He proposes a division of the palette into a ‘spatial’ and ‘mental’ perspective; both showing a pattern of “d’opposition binaire” (Tefnin 1979: 229) and creating themes that are “au plan cosmique et 30 There is a large variety of names for the palettes. The palette here labelled as the Hunters Palette is referred to as the ‘Lion Hunt Palette’ in other publications (e.g. Osborn 1998: 2, Tefnin 1979: 221). The palette labelled here as the ‘Two Dogs Palette’ (discussed below) has also several different names: ‘Votive palette in Oxford’, ‘Big Animals Palette’, ‘Hierakonpolis Palette’, ‘Wild Dogs Palette’ (Asselberghs 1961, Osborn 1998). According to Osborn (1998: 2) the most correct labelling for this palette would be ‘Hyena Dogs Palette’ even though he refers to it later on the same page as the ‘Hierakonpolis Palette’. 39 constituer déjà un système de significations symboliques.” He concludes that the palette relief does not narrate a specific event but is composed of images of the opposing themes of life and death (chased/captured versus living). 3.5.2 The ‘Two Dogs Palette’ (Oxford, Ashmolean Museum, E.3924; Asselbergs 1961: Pls LXX, LXXI) The ‘Two Dogs Palette’ has approximately the same shape as the Hunters Palette. Both sides are decorated with hunting scenes, one of which is less realistic than the other. Two dogs frame the upper part of the palette. On one side the oryx, goat and hartebeest are attacked by a serpopard (a combination of serpent and leopard), a leopard and a griffin. A hyena is also seen in this group, with its head turned back rather than being in an attacking ‘mode’. Beneath them are a wildebeest 31 (Osborn 1998: 2), ibex, giraffe and a donkey- headed man playing a flute. On the upper part of the palette, two lions are nose to nose with two gazelles. On the other side, the serpent-like necks of the serpopards stretch along either side of the central grinding surface. A group of three hunting dogs, wearing collars, attack the same combination of animals on the lower part of the palette (oryx, ibex, gazelle and hartebeest). On the upper part, three dogs, of a different breed (‘hyena dog’), are distributed on either side and under the grinding surface. The opposing serpopards lick the gazelle found between them. Above the gazelle is a large bird, possibly an ostrich. There are a number of features that stand out in the composition of these scenes. The combination of gazelle, ibex, oryx and hartebeest found here will later become a frequent grouping in hunt scenes (Asselberghs 1961: Pls LXX - LXXI). The four species are distinctly portrayed with specific anatomical features. The consistency with which the different species are used suggests an intentional differentiation with regard to these animals, indicating that these artistic distinctions were established as early as the Predynastic Period. The animals cast in the role of hunter (dog, leopard, lion, griffin and serpopard) are as diverse as the animals found as prey. Three of the figures in one of the scenes, the griffin, the serpopard and the donkey-headed flute player, are imaginary, categorizing the scene as “mythical”. 31 According to Osborn (1998: 173), this is the only example of a wildebeest in ancient Egyptian art (also called “brindled gnu” Connochaetes taurinus, Kingdon 1997: 431). 40 Figure 15. The Two Dogs Palette 41 Finally, there is a focus on the gazelle on both sides of the palette. On one side, two gazelles are placed in opposition to two lions, creating two opposing pairs and providing an early example of this compositional form. On the other, the gazelle is a central figure, being licked by the two serpopards. It is thus part of a “triad” schema, as it is flanked by the mythical beasts. Both of these scenes are found on the upper part of the palette, crowning the other hunting sequences, suggesting a relationship between what may be the contrasting roles of the lions and the serpopards. The two lion and gazelle pairs are set up as complimentary elements, perhaps in the roles of hunter and prey. In contrast, the triad of the two serpopards and the gazelle has a “generative” quality, comparable to a family triad. This theme is also suggested by the licking of the gazelle, recalling later references to licking as part of the bond between a cow and her calf (Ritner 1993: 93). This cursory interpretation suggests that while one side emphasizes the confrontation between hunter and prey, resulting in the death of the gazelle, the other bears an early expression of regeneration. There have been other attempts at analysing these scenes. At one extreme there is Emery (1961: 167) who dismisses these complex compositions as a “confused mass of natural life”. At the other extreme, the full import of the solar myth is called upon, as Westendorf (1968: 18- 19) interprets the two serpopards as feline guardians of the sun, represented by the cosmetic grinding circle. The antelopes are then the enemies that are “attacked”, all of this implying the existence of a well- developed solar mythology as early as the late Predynastic Period. 3.5.3 The Stockholm Palette (Stockholm, Medelhavsmuseet, EM 6000; Asselberghs 1961: Pl. XLVI) Another highly interesting palette is found in Stockholm. Rhomboid in form, it has two crudely incised scenes. One of them shows a male figure standing in a boat, harpooning a hippopotamus. This is an early version of the well known “hippopotamus hunt” (cf. Säve-Söderbergh 1953), documented as part of a royal festival as early as the reign of the first dynasty king Den (Dreyer et al 1998: 163, Pl. 12d) and surviving as a motif of the marsh hunt, well documented in private tombs, such as those of Ti of the Old Kingdom (Steindorff 1913: Pl. 113) and Intef of the New Kingdom (TT 155, Säve-Söderbergh 1957: Pls XIV-XV). The second group on the palette consists of a canine (dog or hyena) attacking a dorcas gazelle. The dog-attacking-gazelle composition appears to have achieved iconic status early on, appearing in several variations, as seen 42 in the discussion above. A third figure, another hippopotamus, is found positioned vertically on the opposite end of the palette’s surface. The combination of the hippopotamus hunt and the dog attacking a gazelle juxtaposes two hunter-prey compositions commonly placed in contrasting marsh and desert environments. Found together here, a topographic complementarity is created. Another example of the combination of gazelle and hippopotamus is described above in the discussion of the knife handle in the collection of the Petrie Museum (cf. 3.3.1, describing UC 16295, Petrie 1920: Pl. XLVIII, 5-6). Figure 16. The Stockholm palette The two hunter-prey pairs, man-hippopotamus and canine-gazelle, may thus represent two variations of the theme of the defeat of “wild” forces by “order”, with the gazelle and the hippopotamus both referring to uncontrolled natural forces, one found in the desert and the other in the marsh (cf. Säve- Söderbergh 1953 for this interpretation of the hippopotamus hunt). 3.5.4 The Gazelle Palette (BM 32074, PM V: 105; Asselberghs 1961: Pls LXVIII-LXIX) Another palette places the gazelle in a primary position. The top of a palette fragment displays a recumbent gazelle. Beneath it is the circular grinding space. The lower section of the palette has two opposing birds (suggested to be geese by Petrie 1953: 10-11, Pl. C, 10-11; cf. Asselberghs 1961: 329, for a commentary). The reverse lacks raised relief decoration, with only traces of animals, thus tentatively forming a pair of opposing figures, parallel to the figures of the birds. There are no hunters, and the pose of the gazelle is that of repose. Although the head of this reclining animal is missing, the anatomical details that have been preserved (shape of legs, length of tail) supports the identification as a gazelle. The recumbent position, almost exclusively reserved for the gazelle during the Old Kingdom, also contributes to the identification. This could then be an early example of the recumbent gazelle, a familiar image in later Pharaonic representations. 43 3.6 Hierakonpolis Tomb 100 The earliest known example of the desert hunt scene in a tomb was found on the walls of the well known Hierakonpolis tomb no. 100, dated to Naqada IIC (c. 3650 – 3300 B.C., Wengrow 2006: 38, 114). This tomb is also the earliest known decorated tomb (Adams 1996: 1) and the only one among the 150 that were excavated at this site to have painted walls. The reproduction used for the study of this tomb shows the fragmentary condition of the wall painting, with some sections missing. This has led to hypothetical reconstructions of the scenes (Asselberghs 1961: Pl. XXV). A number of the details preserved indicate however that the wall painting represents an important precursor to later tomb art. Among the early occurrences of later elements is a so-called insert, a subordinate scene, with its own ground line ‘inserted’ into the main scene. Four ibexes are shown reclined on a straight ground line that is elevated above that of the main action, indicating that this miniature scene is part of the background of the depicted event. The use of the insert is found primarily in the hunting scenes of Old Kingdom tombs (see below 4.1.4). In this tomb, the hunting scene consists of a group of bowmen and dogs chasing various antelopes, found in the upper right hand section. The gazelle is found in a few different contexts. An unusual depiction is the ‘animal trap’ scene (Asselberghs 1961: 273). Otherwise there are some scattered images of antelopes, of which only one above the animal trap can be identified with certainty as a gazelle. The narrative that included these ‘fragmented’ motifs is difficult to reconstruct. That the animals are within the enclosure presuppose however the hunt and their capture. Even though the gazelle motif is of a very general character in this tomb, it is worth noting its inclusion in this unique composition. The scene depicting a man slaying three kneeling enemies contributes to an understanding of the larger composition. It is often discussed as the predecessor of the traditional smiting the enemy motif (e.g. Asselberghs 1961: 273, Swan Hall 1986: 4, Midant-Reynes 2000: 208, Wengrow 2006: 115). During Pharaonic times this depiction represented royal protection of the country against its enemies. The motifs of “conquest” and “domination” have been interpreted as reflecting “kingship” (cf. Hassan 1992: 316). Given the uniqueness of this tomb, this proposal may be close to the truth as the tomb owner was most likely a person with a high status (Kemp 2006: 81). The meaning of the Hierakonpolis tomb scenes might never be fully understood, it is worth noting the choice of subjects to decorate the walls. The motifs of both the hunt and the boat journey continued to be a part of the funeral iconography until the demise of the ancient Egyptian tomb decoration, and the gazelle was a part of this tradition. 44 3.7 The Early Dynastic Period and Hemaka’s disc The Early Dynastic Period (c. 3000 - 2686 B.C., dynasties 1 – 2) is one of social and political change as the central state takes form. There is little evidence of the gazelle motif from this period, possibly reflecting the poor survival of grave goods, as well as a shift in the media of expression from e.g. small objects and ceramics to pictorial representations that appear mainly on temple and tomb walls in the surviving material (Wengrow 2006: 140-141, 151-154). One theme familiar from earlier objects is found on a black steatite disc (Cairo JE 70104) from the Saqqara tomb of the 1 st dynasty high official Hemaka (Mastaba S 3035, PM III/2: 440; Emery 1938; frontispiece and Pl. 12b). The raised relief scene features -dogs (Osborn 1998: 60) chasing and attacking gazelles. The composition consists of two pairs, with one consisting of a light coloured dog chasing a gazelle and the other a black dog attacking a second gazelle by biting its throat. The two combinations of dog and gazelle may represent a sequence of events. Several other discs were found in this tomb and some of them, like the one here, have a hole in the centre. This has led to the hypothesis that they were gaming discs that could be spun by placing a stick through the hole (Emery 1938: 28). Whatever its function, this object represents a link between the Predynastic Period and the Old Kingdom in terms of the motif of the gazelle. An interesting contrast to the desert hunting motif of dog-attacking- gazelle is found on another of the discs from the tomb of Hemaka, depicting two birds trapped in a hexagonal net (JE 70165, Emery 1938: Pl. 12c). This image demonstrates the use of such nets to hunt birds (Henein 2001). Depictions of this net can be observed on tomb walls, where clap-nets with entrapped birds are seen in lakes or basins (cf. Houlihan 1986 for extensive pictorial references of the use of clap-net). This disc of Hemaka may represent one of the earliest versions of the theme of fowling in the marsh, otherwise well attested in the dynastic art (e.g. Harpur 1987: 140-144, 176-204; Decker and Herb 1994: 382-532, Pls CCVII-CCC). The ‘relationship’ between the themes of these two discs, while being difficult to establish, does include the combination of the contrasting landscapes of desert and marsh. 45 Figure 17. Disc of Hemaka 3.8 Initial images - concluding remarks The motif of the gazelle in material from the Pre- and Early Dynastic Periods focuses mainly on the image of dog/lion-attacking-gazelle, while offering some interesting compositions, such as the lion-gazelle combinations found on the Two Dogs palette. The composition of the dog- gazelle motif became canonical and does not alter to any great extent during succeeding millennia. The fixed style of the motif and the narrative setting, i.e. ‘hunt in desert’ as it appeared later on, suggests that the connotations of the composition may have carried over to the Old Kingdom and later, with elaborations and additional associations being added. The stability of the form given the gazelle suggests that it conveyed a specific “message” that carried significance over time. The dog-attacking-gazelle is one of the most enduring motifs featuring the gazelle. The Predynastic material appears to have provided a foundation from which further iconographic expressions developed. “The key to understanding formal Egyptian visual culture – architecture as well as art – and its remarkable homogeneity through three thousand years lies in the concept of the ideal type” (Kemp 2006: 135). 46 4 The Desert Hunt The desert hunt scene is found in private tombs and to a certain degree in royal temples, of the Old, Middle and New Kingdoms. The scene also occurs on a small number of New Kingdom royal objects and in a few Saite private tombs. It depicts the hunter, human or animal, subduing the multitude of creatures that inhabit the desert landscape. 32 On one level these scenes relate to life on earth, with these animals providing food for the living, and on another to life in the next world, as they become offering gifts that contribute to the hunter’s immortality. The gazelle, one of the primary prey in the hunt narrative in Predynastic art, reoccurs in the later hunt scenes. This chapter begins by outlining the normative elements of the desert hunt and then continues by tracing the occurrence of the various forms of, and themes conveyed by, the gazelle motif in selected examples of the hunt scene, from the Old Kingdom to the Saite Period. 4.1 The components of the desert hunt The desert hunt scene is characterized by a combination of standardized components and individualized compositions. 4.1.1 Desert topography The desert in the iconography of the Old Kingdom and later is represented using topographical details such as an undulating ground line with hills and small mounds and by including the wild species that characterize life in this habitat. In addition, sandy hills, small bushes and branches are used to suggest desert. These topographical details identify the landscape and provide a background for the combination of hunter and prey. 4.1.2 The hunters The hunter is either a man or men or animal, dog or lion. Human hunters can be equipped with either bows and arrows or lassos. These are not innovations of the Old Kingdom, being represented in the Predynastic material in the scene from the so-called Hunters Palette (cf. above 3.5.1). The detail of the 32 A parallel, in a complementary landscape, is the marsh hunt, often found juxtaposed with the desert hunt. There is however no clear relationship between the marsh hunt and offering gifts. 47 presence of a human hunter differs from period to period and site to site. Even when absent, the hunter can be indicated by hunting dogs (cf. Davis 1992: 81-83, 91) that often wear collars, emphasising the connection to the present or absent hunter (e.g. desert scene of Mereruka, bottom register, Duell 1938: Pls 24-25). In some cases, the hunter is seen at the edge of the scene observing rather than participating (e.g. top register in desert scene of Raemka, Hayes 1953: 99, Fig. 56). The dog is the most common animal depicted in the role of hunter and the composition in which a hunting dog attacks a gazelle is one of the oldest and most durable motifs (cf. Chapter 3). The collared hunting dog is generally depicted running loose but there are examples of dogs held on leashes, controlled by a hunter (cf. e.g. Nefermaat, Petrie 1892: Pl. XXVII; Ptahhotep [II], Davies 1900: Pl. XXII; Kapi, Roth 1995, Fig. 189; Niankhkhnum and Khnumhotep, Moussa and Altenmüller 1977: Pl. 40). The dog is commonly shown chasing various game animals, such as the gazelle, ibex and oryx. When attacking, it can bite the hind leg of the fleeing animal. Another variation shows the dog holding the neck of the animal in its mouth, choking it. In contrast to the hunting dog, the lion is depicted as a wild animal, hunting on its own behalf and not for a human owner. 33 The lion is more selective in its prey than the dog and is found attacking either a gazelle (e.g. Thefu, Hassan 1975b: Pl. LXXXVI, C; Meryteti, Smith 1949: 239, Fig. 92b) or an aurochs (e.g. Mereruka, Duell 1938: Pl. 25; Seshemnefer, Junker 1953, Fig. 63). When seizing a gazelle, the lion, like the dog, is shown biting the neck, which is typical behaviour for a lion killing its prey. It is however the dog that is depicted most frequently attacking the gazelle. 4.1.3 The prey The gazelle, ibex and oryx are the most common prey in the desert hunt 33 On the Golden Shrine from the tomb of Tutankhamun (JE 61481, Eaton-Krauss and Graefe 1985: Pl. XV), a lion cub accompanies him in a marsh scene. The seated pharaoh shoots fowl, assisted by his wife, while the lion cub is stands next to him. The animal has a collar around its neck, indicating that it belonged to the king rather than being wild, yet it does not seem to be an “active hunter” in the fowling scene. 48 Dog grasping a gazelle’s hind leg Figure 18. scenes, followed by the hartebeest. Occasionally the addax, and the fallow deer make their way into the desert scene as well (e.g. Djehutihotep, Newberry 1895: Pl. VII; Intefiker, TT 60, Davies and Gardiner 1920: Pl. VI). Smaller animals, such as the hedgehog and the hare can also be included among the game animals (e.g. Rekhmire, TT 100, Davies 1943: Pl. XLIII; Ankhtifi, Vandier 1950: 95, Fig. 46. Cf. above 2.1.1-2.1.4). The greatest variety of desert animals can be observed in the sources from the Old Kingdom. The Middle and New Kingdom scenes show a stricter and more conservative selection and combination. The gazelle, ibex, oryx and hartebeest are retained as prominent game animals, with fewer examples of various felines (see Khnumhotep III at Beni Hassan that includes caracal and serval, cf. Osborn 1998: 14; also Pehenuka where a “jungle cat” is found, cited in Osborn 1998: 53), red foxes (Vulpes vulpes, family Canidae) or jerboas (desert rats, Jaculus jaculus of the Dipodidae family) occurring in the later examples of the desert hunt. Individualized motifs that characterize each species are used. These can be combined in different ways with almost no duplication of the same combination of elements. 34 The standardised motifs indicate the specific wounds caused by the hunters. The hunting dog kills its prey by grasping the neck, thereby choking the animal to death (e.g. Mereruka, Duell 1938: Pls 24- 25). The human hunter uses the bow and arrow to kill its target; the arrow either piercing the neck, the eye or the body (e.g. Intef, TT 386, Jaroš-Deckert 1984: Pl. 21). A combination of these two killing ‘methods’ could also be used, i.e. a hunting dog choking an animal that already is pierced by an arrow (e.g. Puimre, TT 39, Davies 1922: Pl. VII). The desert hunt scene, although including naturalistic details, is not a photographic representation. Species from different habitats that would never be together in real life are combined in the same landscape (cf. Osborn 1998: 11). True desert animals, such as oryx and gazelle (Estes 1992: 128, 64) are found together with those from semi-arid and savannah environments, such as hartebeest and aurochs (Kingdon 1997: 429, Estes 1992: 193). The presence of a species with an association with the desert functions however to identify the landscape. 34 There is at least one exception to this, the desert hunt scene of Ibi in TT 36, dated to the 26th dynasty (4.3.4/a) that is strikingly similar to, and perhaps a copy of, that of another Ibi found in his tomb in Deir el-Gebrawi and dated to the 6th dynasty (4.3.1/d.1). 49 4.1.4 Hiding from the predator: the insert A special compositional element was created to depict animals in the background of the main action of the hunt, hiding in the vegetation. This miniature scene is called an insert 35 and is typical for the desert hunt scenes of the Old Kingdom. It is characterized by a short ground line, placed within a register, creating a separate scene above the main depiction of the hunt. Its use dates back to the late Predynastic Period when it can be found in the scene from Hierakonpolis tomb no. 100 (Decker and Herb 1994: Pl. CXXXI and above 3.6). In that scene, a minimum of four recumbent ibexes are found above one of the central boat images. This small scene appears to be an extension of the hunt episode depicted to the right of it. Most inserts include environmental details such as bushes, branches, small trees and hills that locate them in the desert landscape. Gazelles, hares and hedgehogs are all found in these abbreviated, registers. 36 The pictorial elements and the range of animals depicted in these inserts are limited and the selection gives the impression that the inserts are only used for ‘small’ burrow- living animals such as the hare, the hedgehog and the jerboa (Osborn 1998: 52). Although the gazelle, in comparison, is not as ‘small’ in size (nor does it live in a burrow), those found in the inserts are most likely fawns and not adults, despite the almost ever-present horns that may have served to identify the animal as a gazelle. The animals in the inserts are generally portrayed as if hiding in the bushes, next to or behind a hill. Young gazelles hide in the vegetation away from the mother as a protective strategy (cf. above 2.3.4) and it is that the insert most likely depicts (cf. Estes 1992: 17). The gazelle is always recum-bent, often with the head turned back. The animals found in the inserts are not actively pursued rather they seem to function as a counterpoint to the chaotic atmosphere in the hunting registers. The decline in the occurrence of inserts in the hunting scenes during 35 The term “insert” has been taken from Osborn (1998: 61, 70, 103 and passim, cf. above 2.3.4), and is used here in a descriptive sense. 36 E.g. the OK tombs of Fetekta (PM III/1: 351 (6), Seshemnefer (PM III/1: 224 (6)), Raemka (PM III/2: 487 (3)), Pehenuka (PM III/2: 491 (4)), Mereruka (PM III/2: 528 (18)), Ptahhotep (PM III/2: 601 (17)), Niankhkhnum and Khnumhotep (PM III/2: 642 (10)). 50 Figure 19. Recumbent gazelle in an insert both Middle and New Kingdoms 37 suggests that this was a narrative and not an aesthetic component. 4.1.5 The hunt and its implications The desert hunt scene depicts a hunter (or hunters) pursuing and eventually killing prey. The funerary context for this scene indicates a relationship with the tomb as a place where life after death is maintained. This implies that the death of the animals is in some way connected with the continued life of the hunter. On one level this relationship is found when seeing the realm of the desert as a correlate to the “chaos” brought about by death and the hunt as an expression of the control and defeat of this chaos. That the hunt belongs to the chaos-order paradigm is seen in the way desert game and foreign enemies are treated as parallel in New Kingdom material (see below 4.2.3/a.3). On another level, the game animals are also clearly represented as potential food, to be slaughtered for meat on the spot or captured and later presented as live offerings (cf. below Chapter 5). This in turn indicates that their death is not only an assertion of “control” over the chaos of the desert, but also contributes to the life of the hunter and to the cult that sustains his immortality. 4.2 The royal desert hunt Royal hunting scenes, that include the gazelle as prey, are preserved from the Old, Middle and New Kingdoms. The scene from Sahure’s mortuary temple from the 5 th dynasty (c. 2487-2475 B.C., cf. below 4.2.1/a) is the oldest known royal example, postdating by about 100 years however the earliest known private tomb examples of the scene (cf. below. 4.3.1/a). The possi-bility that older royal examples existed and provided the source for the desert hunt composition later found in private tombs, remains, particularly considering the paucity of surviving royal reliefs from this time. 38 The 37 There are, as always, a few exceptions, such as the hunting scene of Khnumhotep III at Beni Hassan (BH 3, PM IV: 145; Newberry 1893: Pl. XXX) where an insert can be observed on the third row. Another exception is the desert scene in the New Kingdom tomb of Rekhmire (TT 100, PM I/1: 210 (11); Davies 1943: Pl. XLIII) where a genet (Osborn 1998: 91) and a hare hide in bush-like inserts. 38 The earliest known relief fragments have only survived as reused blocks, far from their origin. Cf. e.g. the blocks from Khufu’s mortuary temple found in Lisht, depicting the titulary of Khufu, bringing offerings from the estates and traces of a papyrus boat (Goedicke 1971: 11-23), however there are some blocks with gazelles, unfortunately the origin of these fragments cannot be established (Goedicke 1971: 135). Cf. the blocks found in Bubastis inscribed with 51 surviving images from the Painted Tomb from Hierakonpolis (cf. above 3.6) certainly supports this possibility. 4.2.1 The royal desert hunt: Old Kingdom (c. 2686-2125 B.C.) The desert hunt belongs to the general category of scenes of everyday life. 39 These are more common in private tomb contexts than in the surviving evidence for royal monuments. It is first with the 5 th dynasty that pictorial reliefs have been preserved to any great extent from an Old Kingdom royal context. Some of the preserved reliefs and blocks do however display detailed images of the desert hunt. There is a distinct relationship between the Old Kingdom royal desert hunt scenes and those found in private tombs. The royal scenes stand out however with the expansion of the motif catalogue of the hunt narrative to include birth-giving motifs. These do not find their way into the private tomb scenes until the Middle Kingdom (cf. below, with e.g. Khnumhotep III, foaling gazelle, Newberry 1893: Pl. XXX and Intefiker, TT 60, foaling oryx, Davies and Gardiner 1920: Pl. VI and New Kingdom, Montuherkepeshef, TT 20, foaling wild ass, Davies 1913: Pl. XII). a. Mortuary temple of Sahure (South passage), Abusir, 5 th dyn. (c. 2487- 2475 B.C.) (South wall, Berlin 21783; PM III/1: 327 (5); Borchardt 1913: Pl. 17) The desert hunt scene is found in the mortuary temple of Sahure’s pyramid complex (PM III/1: 326-335) in the passage surrounding the columned hall. It is on the south wall in the south passage. On the other side of the hall, in the north passage, is a marsh scene depicting the king fowling and spearing fish from a canoe (PM III/1: 328 (9-10), Borchardt 1913: Pl. 16). The Sahure scene is the oldest known royal example of the desert hunt and has been treated as a ‘prototype’ (e.g. Schweitzer 1948: 53, Vandier 1964: 791, Altenmüller, 1967: 13, Hoffmeier 1975: 8) for later private versions, in its use of several distinctive details. The most easily recognized is the hyena with the arrow in its muzzle, a detail that is used through to the New Kingdom (discussion in Ikram 2003b: 141-147). Similarly, some of the gazelle motifs, such as arrow through neck, the pair of gazelles and the recumbent gazelle hiding in insert, common in later desert scenes, are first the names of Khufu and Khaefre (Naville 1891: 5, Pls VIII, XXXII, A (Khufu), XXXII, B (Khaefre)). 39 Cf. however Harpur (1987: 175) where the desert hunt is not included among that author’s eight basic themes in Old Kingdom private tombs. 52 found in the Sahure composition. The reconstruction of the Sahure hunt scene extends over as many as four registers. Next to the depiction of the desert landscape, stands the king, before the registers 40 (Borchardt 1913: Pl. 17, here Fig. 20) wearing the ceremonial beard and an unidentifiable crown. His ka is behind him. Sahure is the main hunter and the only one equipped with a bow and arrows. He is aided by hunting dogs and three men with lassos and one with a stick at the far right, outside the enclosure (excluded in Fig. 20). There is a large variety of prey animals: gazelle, oryx, fallow deer, aurochs, barbary goat, addax, hyena, hartebeest and ibex. Most of the wild animals depicted in the three surviving registers have at least one arrow piercing their bodies. There are several gazelles in this scene. Four are found in the upper register. To the far left, one is seen attacked by a hunting dog, who wears a collar. The gazelle is pierced by an arrow and the dog goes in for the kill by seizing it by the neck. Next to this stands another gazelle, body facing right but head turned to the left, facing the dog. Its front legs are lifted off of the ground as if it is fleeing. It too has an arrow through its neck. To the right, on the same register, in front of a fallow deer and two oryx, all with arrows in their bodies, stand a pair of unharmed gazelles facing left, observing the flight of the other animals that are wounded and running (?) in their direction. An insert in the register below shows a reclining gazelle, its head turned back. In the bottom register, a dorcas gazelle and a Soemmerring’s gazelle are pierced by multiple arrows. They are facing left, away from the king. The Sahure scene provides the earliest known example of a gazelle wounded by an arrow, here in the animal’s neck, an area that seems to be the hunter’s preferred target, with regard to the gazelle. This can be compared to the two examples of the oryx (upper and lower registers) with arrows piercing their eyes, a placement that may relate to the Egyptian name of this animal “seeing white” (cf. above 2.1.3). The hyena, by contrast has an arrow in its muzzle (cf. Ikram 2003b). This, like the depiction of the hunting dog seizing the gazelle by its neck (cf. e.g. 3.3 above), is an iconic motif. 40 The large-scale tomb owner with bow and arrow that flanks the hunting scenes in private tombs is more frequently preserved in Middle Kingdom contexts (but cf. Pepy-nakht Hekaib at Qubbet el-Hawa from the late 6th dynasty - FIP, Decker and Herb 1994: 313-314, Pl. CXLII (J 48) ), e.g. Ukhhotep, Senbi, Khnumhotep etc., suggesting a popularising of royal motifs. The problem of survival however makes this conclusion tenuous. The occurrence of “hunting from a chariot” in the tomb of Userhat (TT 56, PM I/1: 113 (13-15)), a contemporary of Amenhotep II predates the royal version also found on the painted chest of Tutankhamun (below 4.2.3/a.2). The discovery, however, of a previously unknown royal chariot scene dated to Amosis at Abydos (Harvey 2001: 52-55) illustrates how tentative these conclusions are. 53 54 Typical for the gazelle during the Old Kingdom is also the recumbent animal in an insert with its head turned back. The other inserts are taken up by a hedgehog, jerboa and badger (cf. Osborn 1998: 85 on identifying the species as a ‘ratel’ or honey badger 41 ), all small animals that live hidden away. Another feature worth noting is the occurrence of gazelles two by two. As noted above (cf. 2.2), female gazelles pair up, rather than living in larger groups, when resources are restricted. This grouping may reflect an observation. However, given that one of the pairs consists of dorcas and a Soemmerring’s gazelle, it also indicates that there is interest in depicting pairs of gazelles, 42 and there is a greater general tendency for gazelles to appear in pairs than for other animals. Oryx, hartebeest and aurochs are found with equal frequency alone, in pairs or in larger groups. The grouping of gazelles into pairs is repeated in both royal and private desert hunt scenes. The Sahure desert scene is flanked by fencing, suggesting that the hunt took place within an enclosure, with the animals inside and the king outside. 43 This implies that the animals were collected to facilitate the hunt. The depiction of the hunt within a fenced area is a variation found from the Middle Kingdom and onward in private tombs (e.g. Amenemhat at Beni Hassan, Newberry 1893: Pl. XIII; Djehutihotep at el-Bersheh, Newberry 1895: Pl. VII; Amenemhat, TT 53, Decker and Herb 1994: Pl. CLXII (J 97)). On the wall opposite the desert hunt, there is a series of offering processions (cf. Chapter 5). The fattened animals in the offering rows suggest that they were captured then kept alive for some time, perhaps within such enclosures, before slaughtering. 44 41 A ratel or honey badger (Mellivora capensis) belongs to the Mustelidae family, i.e. the same as weasel and otter (Estes 1992: 419, Kingdon 1997: 228, 232-233). 42 One of the pair consisted of a dorcas gazelle and a Soemmerring’s gazelle ( ). This ‘combination’ is common during the Old Kingdom, cf. Idut (Macramallah 1935: Pl. XX), Fetekta (LD II: Pl. 96), Nimaatre (Roth 1995: Fig. 189), and also Niuserre (von Bissing 1956: Pl. XI a) and Unas (Hassan 1938: Pl. XCVII A). 43 Reference to the earliest use of an enclosure could be in the Painted Tomb at Hierakonpolis, if the animal trap is interpreted as an enclosure. The Narmer macehead has a motif that can be interpreted with greater certainty as animals within an enclosure, in front of the Heb Sed booth (Quibell 1900: Pl. XXVI, B). 44 Cf. the use of the word or , “enclosure”, from “to entrap” (Faulkner 1962: 46) in tomb of Rahotep (Petrie 1892: Pl. IX). 55 b. Sun Temple of Niuserre (Room of Seasons), Abu Ghurob, 5 th dyn. (c. 2445-2421 B.C.) (Harvest, west wall, Berlin 20036; PM III/1: 319; von Bissing 1956: Pl. XI a-b) The original location of the naturalistic reliefs that include a hunt scene was the Room of Seasons, on the west wall, in the section understood as the harvest episode ( ) (Smith 1965a: xxi). On the opposite east wall were representations of the inundation ( , PM III/1: 321), with birds hovering over the marshes, a scene depicting the harvesting of honey and an array of domesticate animals mating (Smith 1965a: Fig. 178b). The scene is fragmentary with several sections missing, making a complete reconstruction impossible. Yet, the motif of the gazelle can be distinguished several times from the remaining blocks of the harvest episode. Two of the Niuserre blocks provide a striking contrast in their choice of motifs to that of Sahure with its focus on the hunt itself. The Niuserre blocks are decorated with a desert landscape that includes depictions of birth-giving scenes (von Bissing 1956: Pl. XI a-b). Nevertheless, two hunting dogs can be distinguished, stalking their prey on the far right on one of the blocks (von Bissing 1956: Pl. XI a). These dogs provide a certain contextual frame, possibly functioning both as a reminder of the vulnerability of the animal in giving birth, as well setting up an opposition to that event. Unfortunately the block breaks off here, making any further reading of the scene impossible. Some of the other, even more fragmentary, pieces do indicate however that the hunting motif was originally included in the iconography of the Niuserre sun temple walls (von Bissing 1956: Pls XXI, XXIII; contra Vandier 1964: 788). These blocks are too damaged to present a comprehensive picture of the wall decoration, other than to indicate that the opposing themes, the birth of the young and the death-bringing hunt, seem to have originally been a part of the composition. Depictions of foaling wild game are found on both blocks (Edel and Wenig 1974: Pl. 14, Z. 250-252). The first block (von Bissing 1956: Pl. XI a, Edel and Wenig 1974: Pl. 14, Z. 251-252) preserves fragments of three registers. Mullets swimming in the river are shown on the uppermost register (excluded in Fig. 21 below). The middle register consists of an array of animals, all facing right: these include (from right to left) the remains of an ostrich, followed by an addax, a foaling oryx, a gazelle and two Soemmerring’s gazelles. The bottom row is composed of (from right to left), a dorcas gazelle nibbling on a bush, a dorcas and Soemmerring’s gazelle giving birth side by side, a recumbent gazelle 56 (facing left) hiding behind a tree, 45 two oryx, two hunting dogs wearing a collar and a gazelle in a basket. The variety of motifs that include the gazelle is notable, perhaps suggesting its position as desirable prey. Figure 21. Blocks from Niuserre’s sun temple The second block also has three registers (von Bissing 1956: Pl. XI b, Edel and Wenig 1974: Pl. 14, Z. 250), with the top row depicting water (without fish, not shown in Fig. 21). The second register, from right to left, shows an aurochs, addax and gazelle, all giving birth. On the far left, remains of another gazelle can be observed. The bottom register continued the motif of giving birth, with a lioness and a panther, followed by an oryx looking back (facing left). The foaling animals are identified with a text; above the gazelle it reads . One would have expected the feminine form for the foaling female gazelle, although the label perhaps refers to a male fawn. The inscriptions above the other birth-giving animals are also somewhat inconsistent with regard to gender, with the only feminine form found referring to the panther. 45 The recumbent gazelle in a ‘traditional’ insert is present on one of the fragments from this temple (von Bissing 1956: Pl. XXIII b). A ratel and a hare are also included, corresponding to Sahure’s choice of species in this particular motif. 57 Another inscription written in a vertical column to the right of this second block, extending over two registers reads , ‘setting out (for) the hill country, giving birth, renewing all (things)’. 46 This line confirms birth-giving as an integral theme in the desert narrative. The Niuserre blocks are unique in the diversity of wild animals giving birth, as well as in the inclusion of such specific descriptions. There are several gazelle motifs on the Niuserre blocks. Apart from introducing that of a birth-giving gazelle, it may also be noted that the combination of a dorcas and Soemmerring’s gazelle appears here as well as in the Sahure scene (von Bissing 1956: Pl. XI a), although here both are giving birth. This is the only example in this material of two foaling animals seen directly side by side, creating a ‘double’ birth that contrasts with the other foaling animals that are portrayed individually. Another new feature is the gazelle nibbling on a bush. The motif of the bush-eating gazelle develops into a composition involving two opposing gazelles eating from a bush/palmette (cf. e.g. a jar stand in Field Museum of Natural History in Chicago (no. 30177), EGA: 119-120, cat. no. 106, and the chests of Perpaouty, below as 6.4.1). In the example of Niuserre, the grazing gazelle is found together with the recumbent gazelle and the foaling pair, suggesting that these images of the gazelle could all be considered as ‘naturalistic’. This variation in poses appears to be exclusive for the gazelle. Some of the other animals are similarly depicted, but no other is found with the same range of variation. A ‘new’ motif specifically related to the gazelle, is the use of a basket as a carrier (cf. below 5.2.2/c.1). To the far left in the same register, there are traces of what can be interpreted as a basket containing gazelles. Although broken off here, parallels from private tombs 47 suggest that this would have been hanging from a yoke. Additionally the version found on the Niuserre block was most likely that where the two gazelles appear with head and neck protruding from either side of a basket, forming a pair (cf. Hetepherakhti, Mohr 1943: 41, Fig. 9). 46 Von Bissing 1956: 329: “Marcher dans le désert en donnant naissance, renouvelant tout”. 47 Cf. e.g. Ptahhotep (PM III/2: 602 (18), Davies 1900: Pl. XXI), Niankhkhnum and Khnumhotep (PM III/2: 642 (9)), Moussa and Altenmüller 1977: Pl. 34), Meryteti (PM III/2: 536 (112)), Decker and Herb 1994: Pl. CXL, J 40), Idut (PM III/2: 619 (13)), Macramallah 135: Pl. X). 58 c. Pyramid complex of Unas (Causeway 48 ), Saqqara 5 th dyn. (c. 2375-2345 B.C.) (Harvest sequence, north wall; PM III/2: 419; Hassan 1938: Pl. XCVII A) The desert hunt scene of Unas was originally found on the north wall of the causeway leading to his pyramid complex. The blocks decorated with desert scenes are part of the harvest season similar to the context for the same scene on the Niuserre blocks. The motif of netting fowl was located on adjoining blocks (PM III/2: 419). Once again multiple loose blocks make a complete reconstruction of the original layout of the desert hunt scenes impossible. The publication of Labrousse and Moussa (2002: 147-152, Figs 42-59) gives an idea however of the extent of the representation of game on these blocks On the single block published by Hassan (1938: Pl. XCVII A, Labrousse and Moussa 2002: 151, Fig. 57, Doc. 43), several gazelle motifs can be observed. The register contains (from right to left) an oryx licking its young and a gazelle being attacked by a hunting dog that grasps its hind leg. The gazelle turns its head back, facing left. This group is followed by a foaling oryx and a hartebeest. The heads of a dorcas gazelle and a Soemmerring’s gazelle at the end of the block are discernable before the block breaks off. Two inserts are also included; the one to the left contains a hare and a jerboa, while other one features a recumbent gazelle with its head turned back. This insert is located above the dog-attacking-gazelle motif. This single register combines the themes of birth-giving and the hunt. The insert with a single recumbent gazelle with head turned back is similar to that from Sahure, as is the dog-attacking-gazelle motif (albeit expressed slightly differently). Its positioning among birth-giving animals creates a contrast as well as a balance in the hunting theme. The use of foaling animals can be traced to the Niuserre blocks that had the same imagery, including the presence of hunting dogs, although there they appear as implicit threats, without actually attacking. One of many blocks with the desert motif contains a nursing scene (Labrousse and Moussa 2002: 151, Fig. 55, Doc. 41); unfortunately the upper part of the mother is missing making it impossible to definitely identify the species. However, the remaining anatomical details suggests that it was a gazelle nursing its fawn, especially when compared to the example in the contemporary tomb of Ptahhotep (Davies 1900: Pl. XXI), where the young is also depicted standing on its hind legs, forelegs off of the ground in order to reach the mother’s teats (“… se dresse sur ses pattes de derrière pour téter les mamelles de sa mère”; Labrousse and Moussa 2002: 45). 48 This part of the Unas’ pyramid and temple complex was called the “valley temple” in PM III/2: 417. 59 From the Unas block fragments published by Labrousse and Moussa (2002: 148-152, Figs 45, 52, 54, 59), it is evident that the motif of mating animals is common. An example of copulating gazelles may be among these animal pairs. This is, however, speculative as only the hind part of the animals remains (Labrousse and Moussa 2002: 150, Fig. 52 (Doc. 38)). The frequent use of inserts and recumbent animals, among them the gazelle, is also a dominating feature of the Unas blocks (Labrousse and Moussa 2002: Figs 42, 47, 48, 53, 54, 56). Finally, it may be pointed out that the motif of striding gazelles, two by two, is also found on a few of these blocks (Labrousse and Moussa 2002: 149, Fig. 51 (Doc. 37), 148, Fig. 47, (Doc. 33, Soemmerring’s gazelle)). Several of the blocks show traces of men with lassoes, a hunting technique depicted on the Sahure relief (e.g. Labrousse and Moussa 2002: 150, Fig. 54 (Doc. 40 A), also 152, Fig. 58 (Doc. 44)). A hunting dog with a collar is also found (Labrousse and Moussa 2002: 151, Fig. 57 (Doc. 43)). There are no animals shown pierced by arrows however, suggesting that this might be a variation of the desert hunt in which the king did not participate with bow and arrow. d. Mortuary Temple of Pepi II (Vestibule), Saqqara, 6 th dyn. (c. 2278- 2184 B.C.) (North wall, PM III/2: 427 (27); Jéquier 1938: Pls 41-43) The blocks from the temple of Pepi II come from the vestibule of his mortuary temple. The desert scene was located on the north wall and a fowling scene was located on the same wall, but on the other side of the doorway in this vestibule (PM III/2: 427 (26)). The remains of the desert relief consist of a single fragmentary register (Jéquier 1938: Pls 41-43). The composition shows a group of striding animals, some of them facing left, some of them right. No particular activity can be distinguished within this row. There are no hunting, copulating or birth giving motifs preserved. The motif of striding animals is not per se out of place, yet the lack of more specific activity is slightly surprising, especially when compared to the earlier royal hunting and desert scenes, which seem to have been particularly dynamic. The gazelle motif is however included in the scene from Pepi II’s temple. A pair of striding dorcas gazelles, facing right, comprises the third ‘group’ from the left. Other striding animals included oryx (four adults, two young), two ibexes (facing left), followed by two foxes, a Barbary goat, a hyena with young and two hartebeests with young (cf. Osborn 1998: 70 for identification of the various species). In the far upper right of the register, a 60 recumbent young animal can be observed, possibly a gazelle, although its identification is uncertain. Osborn (1998: 70) suggests that this is a gazelle eating from the small bush in front of it. The scene above the desert register is to a large extent missing; the front hooves of an unspecified antelope can nonetheless be distinguished. This fragment led Jéquier to suggest that the motif was of the pharaoh, i.e. Pepi II, smiting an oryx with a mace head (1938: Pl. 41; “Reconstruction de l’ensemble”). This corresponds to the “smiting the enemy” iconography, familiar for the king (cf. e.g. Swan Hall 1986). There are some reasons for scepticism with regard to this reconstruction. In later examples where an animal is found in this type of scene, a knife is used to slaughter it, rather than the animal being clubbed by a macehead (e.g. Derchain 1962: 9, Fig. 1, type II, Pl. I, type I). More importantly, the king is accompanied by his ka in this example (seen to the left, Jéquier 1938: Pls 41-42), a feature corresponding to the inclusion of the ka that accompanies Sahure on his desert hunt. It also indicates that the royal cult is the setting for this motif. Beyond the actual remains from this scene, further description would be speculative. What may be noted however is the omission on the surviving blocks of the distinctive hunting and life-giving themes. The motif of the gazelle appears as a recumbent young animal, familiar as the form used for the insert, and as a striding pair. The striding animals, as well as the inclusion of the (reconstructed) smiting scene above this register, makes it an unusual example of the desert scene. e. The royal desert hunt: Old Kingdom – concluding remarks The gazelle occurs in the royal desert hunt in numerous forms. As prey, it is depicted pierced with arrows and attacked by the hunting dog. The young animal is found recumbent in the insert, possibly hiding from attack. The gazelle also occurs within the framework of life-giving imagery, including possible copulation, giving birth and nursing. The gazelle at rest, eating from a bush is found as well as being carried in a basket. Furthermore, the gazelle is often shown two and two, especially when striding or fleeing from the hunters, forming a pair. The animal landscape of the hunt is used to convey the ideas of death and life as two intertwined processes. The reoccurring use of pairs is suggestive of the Egyptian interest in this constellation found in other contexts. It is a composition seen in the Predynastic material as well, on the palettes in particular (Davis 1992: 80, 84-85, cf. above 3.5). The comparatively few surviving examples of the royal hunt scene differ from one another in their internal composition. The focus on the hunt is evident in the Sahure reliefs, while the surviving blocks dating to Niuserre 61 and Unas illustrate the theme of regeneration as they appear within the context of the harvest season. The narrative of Pepi II remains enigmatically static, lacking, in the surviving representations, the narrative elements of both the hunt and life-giving activities. Two aspects of these scenes do however stand out. The first of these is the inclusion of the king’s ka, either in the desert scene (Sahure, accompanying the king as archer) or adjacent to it (Pepi II, accompanying the king as the possible smiter of the oryx). This suggests that the hunt in some way benefited the king’s ka, and thus had an element of ritual. The other aspect is the association of the live-giving motifs (copulation, birth, nursing) with the harvest (Niuserre, Unas), indicating a parallelism between the events. It is also worth noting that the original location of the desert hunt suggests an element of juxtaposition with the marsh scenes, possibly reflecting a theme carried over from the Predynastic (cf. above 3.2, 3.3 and 3.7) combining the two landscapes as complementary. 4.2.2 The royal desert hunt: Middle Kingdom (c. 2055–1773 B.C.) Documentation for the royal desert hunt in the Middle Kingdom is limited to the temple of Mentuhotep II (c. 2055 – 2004 B.C.) at Deir el-Bahari. Although, the remaining relief is very fragmentary, there are some details that confirm the continuation of the royal use of the hunt scene. a. Mortuary temple of Mentuhotep II (Upper colonnade), Deir el-Bahari, 11 th dyn. (Hall, south wall(?), Brussels Musée Royaux E.4989; PM II: 385; Naville, Hall and Ayrton 1907: Pl. XVI) The temple itself no longer stands; however, some of the published fragments indicate that its decoration included reliefs devoted to hunting in both the desert and the marshes (Naville, Hall and Ayrton 1907: Pl. XVI). The exact location and internal relationship between the fragments cannot be reconstructed. Commenting on original location of these blocks, the excavators write: “…These were found in the Southern Court, into which they must have fallen from the platform above. They therefore probably belong to the south wall of the ambulatory surrounding the pyramid” (Naville et al 1907: 69). 49 49 This statement included the fragments of marsh related motifs as well, i.e. both the desert and marsh hunting scenes could have been located on the same wall or direction. 62 Deir el-Bahari: hunted gazelle Figure 22. Three of these fragments depict gazelles, and furthermore, three of the four gazelles had their head turned back (cf. Naville et al 1907: Pl. XVI C, F, H) which is a common pose for the attacked and fleeing gazelle. One of the gazelles has an arrow piercing its neck (Naville et al 1907: Pl. XVI F), and is an almost exact copy of the wounded gazelle from the Sahure reliefs. This suggests that Mentuhotep II was included in the composition as the hunter and, in parallel with Sahure, he may have been depicted oversized outside the hunting area, possibly accompanied by his ka. In addition, one of the fragments shows the head of an aurochs (Naville et al 1907: Pl. XVI E), while four of the slabs show motifs associated with marsh iconography (Naville et al 1907: Pl. XVI A, B, D, G). Although lacking the internal composition of the desert scene, the remaining fragments indicate that both the desert and marsh scenes followed the model of the Old Kingdom. It is worth noting that the image of the gazelle dominates the preserved depictions. This combined with the position given the gazelle in the royal hunt scenes from the Old Kingdom, 50 makes it likely that the gazelle had a similar prominence in the imagery from the temple of Mentuhotep II. b. The royal desert hunt: Middle Kingdom - concluding remarks The evidence suggests that the desert hunt scene in the temple of Mentuhotep II was similar in content and composition to those from an Old Kingdom royal context and to contemporary, private, hunting scenes (cf. below 4.3.2). 4.2.3 The royal desert hunt: New Kingdom (c. 1550-1069 B.C.) Images of the pharaoh hunting in the desert dating to the New Kingdom are relatively scarce (Hoffmeier 1980: 199). None are known to have survived from the earlier 18 th dynasty, rather it is the textual material that deals with this theme. The royal hunt is combined with the king’s military activities as part of the presentation of his role. Biographical accounts of his officials refer to the king’s hunting exploits. Amenemheb (TT 85) refers for example to the capture of 120 elephants by Tuthmosis III in Syria (Urk. IV: 893, 14-15). The Armant stela describes the same king killing seven lions and 12 aurochs with arrows (Urk. IV: 1245, 14-15). The well-known commemorative scarab texts of Amenhotep III record “wild bull” (aurochs) and lion hunts (Urk. IV: 1739- 50 Note that all of the royal desert scenes of the Old Kingdom are fragmentary, making a reconstruction in all its details impossible, as well as determining the exact numbers of the species involved. The gazelle however is well represented in all the surviving examples, in- dicating that it had a significance presence in the original scenes. 63 1740). The hunts were spectacularly successful with 102 lions reported as the result (Altenmüller 1967: 10). These hunts do not have the character of a ‘leisure’ activity but were rather of a ritual nature, with the pharaoh demonstrating his power and thus fitness to rule. Although the textual narrative of the king as hunter appears to have had a significant place in the presentation of the role of the king, the earliest known surviving examples of the pictorial version date to the late 18 th dynasty. a. Tomb of Tutankhamun, KV 62, Thebes, 18 th dyn. (c. 1336-1327 B.C.) Four objects from the Valley of the Kings tomb of Tutankhamun display variations on the royal desert hunt theme that include the gazelle: a bow case, a painted chest, an embroidered tunic and an unguent jar. The bow case and the painted chest have scenes that include the king in an explicit desert hunt context, while the embroidered tunic omits the king, yet presenting the hunting motif with images of attacking dogs and lions. The tunic with its embroidered panels is unique in its juxtaposition of hunting and life-giving motifs. The unguent jar, with a lion decorating its lid, bearing the cartouche of the king, implies an identity between the animal and royal hunter. a.1 Bow case, KV 62 (Treasury) (Cairo JE 61502, PM I/2: 581; McLeod 1982: Pls VI-XVI) The bow case is made of “thin light wood” covered with a tripartite scene depicting the desert hunt (McLeod 1982: 26). Two scenes with identical animals being hunted are found on the lid and base, fitted into the frame of the elongated triangle of the bow case (cf. McLeod 1982: 45-48 for the list of wild animals on bow case). On the lid, in the centre, the king is shown in a chariot, shooting an arrow at two fleeing animals, an oryx and a hartebeest. Two dogs, one at the side of the chariot and the other biting at the hartebeest from beneath its belly, are also included in the scene. This image is flanked by two scenes depicting the game of the desert. To the right, in front of the king, a hartebeest is shown in a twisted position, followed by a hartebeest and an ibex that face each other, with a hare found crouched at the narrow end of the panel. All of the animals, with the exception of the hare, are pierced with arrows. To the left, behind the king, four antelopes are lined up according to size (‘somersaulting’ hartebeest, oryx, ibex and a dorcas gazelle) facing away from the king, towards a hyena. These too are pierced with arrows, with that of the hyena found in its muzzle, like that found in the Sahure scene. The tips 64 of the panel have additional scenes, to the right the king is depicted as a lion trampling an African foe and to the left he has the same guise and is trampling both an Asian and an African enemy. The base of the case (McLeod 1982: Pl. XV) differs in the inclusion of a single grazing gazelle, reminiscent of the motif from the Niuserre block. It stands out, as it does not seem to be either fleeing or wounded. Although these are hunt scenes, the military subtext is found both in the images of the king as a lion destroying foreigners and in the accompanying text (McLeod 1982: 28-38) that contains references to trampling the foreigners ( ) and to shooting with a “victorious” bow ( ) (McLeod 1982: Pl. XXVIII). There is a coherence between the scene and the bow case itself, intended to contain the bow referred to in the text. Many of the elements found here are known from earlier contexts, with only the chariot representing a “modernization” of the scene. The gazelle appears to play a specific role in its appearance on the reverse version of the scene, occurring as the only animal at ease, as opposed to the main theme of fleeing and wounded animals. 51 a.2 Painted chest, KV 62 (Antechamber) (Cairo, JE 61467; PM I/2: 577; Decker and Herb 1994: Pl. CLXXV) The painted chest was found in the tomb’s antechamber and is referred to as “one of the greatest artistic treasures of the tomb” (Carter and Mace 1923: 110, Pls XXI, L-LIV). It is decorated with four different scenes, all depicting the king shooting from his chariot. On the two long sides of the box, the “prey” is comprised of the enemies of the king, African on one side and Asian on the other. The two scenes found on the vaulted lid of the box show the king hunting lions on one side, and on the other a mixed group of desert prey: gazelle, bubals and wild ass, each species distinctively grouped. The ends of the box are decorated with the image of the king as a lion trampling the enemy, with two figures flanking a cartouche. The combination of hunting and military themes, understated in the bow case, is explicit here, as the two groups of prey, foreign enemies and desert animals, are interchangeable. There are several characteristic traits in the scenes of Medinet Habu (cf. 4.2.3/b), among them the grouping of antelopes and lions. 51 Cf. similar images in tombs of e.g. Ptahhotep (4.3.1/b.3, Davies 1900: Pl. XXI), Senbi (4.3.2/b.1, Blackman 1914: Pl. VI) and Montherkhepeshef (4.3.3/a, Davies 1913: Pl. XII). 65 a.3 Embroidered tunic, KV 62 (Annex 52 ) (Tunic 367j, Cairo, JE 62626; PM I/2: 582; Crowfoot and Davies 1941: Pl. XXII) The embroidered tunic found in the annex is “a sleeved robe of fine plain linen decorated with applied bands” (Crowfoot and Davies 1941: 115). The embroidered panels are sewn on the lower edge of this garment, while woven bands with ‘geometric’ design are on the side borders. The front band has 12 panels, while there are eight panels in the back band. The front panels differs from those on the back, with both sharing elements of the desert hunt. The theme of the desert hunt occurs on five of the 12 front panels (front panels 4, 6, 7, 9, 10, 12, Crowfoot and Davies 1941: Pl. XX) where dogs hunt wild game. Of the eight back panels, six have representations of dogs and lions chasing desert game (back panels 1, 3, 4, 5, 6, 8, Crowfoot and Davies 1941: Pl. XXII). These scenes are punctuated by panels decorated with elaborate palmettes. In the front panels winged female sphinxes and griffins are also part of the decoration. Front panels 1, 2 and 3 form a group of two female winged sphinxes facing an elaborate palmette, of the kind that decorates the neck of the tunic. An additional grouping of this kind is integrated into a hunt scene on front panels seven, eight and nine. An additional triad is formed with panels 10, 11 and 12 where a palmette separates two opposing lions. Another unusual feature consists of the two opposing griffins that occupy the lower part of panel six. Palmettes are also found bordering hunt scenes on the back panels, found on panels two and seven. The hunt scenes found on the front panels are incorporated with the decorative palmettes, female sphinx and griffin. There are two possible examples of the gazelle chased by a hunting dog, in panels seven and nine. The back panels however provide more varied gazelle motifs. BACK PANEL 1 The first back panel, to the left, includes a combination of hunting and nursing motifs. The upper part of the panel shows a dog chasing two calves and a lion running in the opposite direction. The bottom section of this panel is decorated with a gazelle nursing a young; there is another young gazelle 52 The annex is referred to as “the store-room of the tomb” by Crowfoot and Davies (1941: 114). 66 nursing and fleeing gazelles Figure 23. Back panel 1: prancing in front of this mother-fawn group. Behind the suckling gazelle two other individuals can be discerned, one of them is probably yet another young gazelle as the animal seen in the left bottom corner is running, with its head turned back, facing right. Interspersed among all these animals are six circles intersected with a cross. This design can be identified as a stylized flower by comparing it to a similar one on the front panels. The nursing gazelle can be compared to that from the Unas blocks (cf. 4.2.1/c). BACK PANELS 3 – 6 The back panels 3, 4 and 5 are treated as one by Crowfoot and Davies (1941: 130), as the squares originally made up a single piece of cloth. Back panel 6 differs in colouring but not in motif. To the left we have once again a fleeing gazelle with its head turned back. A greater part of the panel was devoted to a nursing animal, surrounded by two other young animals. The nursing motif as such, the length of tail and the shape of horns would all indicate an Figure 24. Back panels 3-6 identification as gazelle, although the size of body, the shape and length of neck do not support this identification. Another gazelle, this time recumbent, is located in the upper section of this panel. The positioning of the motif above the ‘chaos’ correlates with earlier examples of recumbent gazelles in desert hunt scenes, as seen in the Old Kingdom reliefs of Sahure, Niuserre, Unas and Pepi II (cf. above 4.2.1). The stylized circular flowers are repeated here as well. The differentiation between back panels 3 and 4 is not clear cut, nor is the transition from panel 4 to 5. In panels 4 and 5, the hunting theme continues with a fleeing aurochs in the upper part and a hunting dog running in the opposite direction, possibly to catch the animal’s leg. The lower sections of back panels 4 and 5 appear to show another aurochs downed by a hunting dog. In the centre of back panel 5 a gazelle is attacked by a hunting dog grasping its neck while another hunting dog confronts this group. A fleeing ibex fills the space below the attacked gazelle. 67 Back panel 6 continues the hunting motif. The upper pair consists of a lion attacking a gazelle by grasping a hind leg and the lower part of the square contained the motif of a hunting dog attacking an ibex. The last back panel 8 to the far right is only partially preserved with a hunting dog chasing an unidentified animal and a lion (?) attacking an aurochs. In the scenes from the back panels, the gazelle representations are varied, being shown fleeing and attacked as well as nursing and in a recumbent pose. It is worth noting that the nursing motif is only found with the gazelle as in other desert hunt scenes. In treating the tunic, Crowfoot and Davies note several traits that they found to be “Syrian” or inspired by Syrian influences, among them the bands that edged the tunic and in the panels, the use of the winged female sphinx, the griffins and the palmette. They also found the composition of the hunt scenes unconventional describing the motifs on the back panels as follows: “The cantering legs of the ibex, the frequent appearance of the lion and his violent action, the unreal position of the tail between the legs in attack, the interspersed flowers without stem or leaf, the alternation of excerpts from the hunt with the palmette design, and the absence of any hunter, though his dogs, slipped from the leash (as the collars show), are so prominent, are all un-Egyptian” (Crowfoot and Davies 1941: 127). They also see a “latent symbolism of victory” referring to it as a feature of Mesopotamian art. Although this particular use of the hunt scene may invite some Syrian interpretation, the scenes are derived from a tradition that can be traced back to the Predynastic Period. Found on a piece of clothing intended to be used by an Egyptian pharaoh, the role of hunter is given the lion and the collared dogs. By wearing this tunic, Tutankhamun would, in a sense, have become the royal hunter, outside the scene. a.4 Unguent jar, KV 62 (Burial chamber) (Inside great outer shrine, facing door, Jar 211, Cairo JE 62119; PM I/2: 580; Carter 1927: Pls L, LI) A number of calcite cosmetic jars, crafted in various elaborate shapes, were found in the tomb of Tutankhamun. One of the unguent jars features the desert hunt on a cylinder shaped body. The lid is formed as a recumbent lion and the jar is flanked by two papyrus columns, each surmounted by a Bes head. The vessel stands on four bound foreigners (two Nubians, two Western Asians). Upon discovery, the jar still contained some kind of cosmetic substance (Carter 1927: 35), most likely a mixture of animal fat and 68 unidentified resin or balsam (Scott 1927: 210). The height of the container is reported to be 26.8 cm (Reeves 1990: 198f), which is fairly tall for this kind of object. The unguent jar was found in the eastern end of the burial chamber, between the first and second shrines enclosing the sarcophagi with the mummified body of the pharaoh (Reeves 1990: 84f). The hunt scene covers the body of the cylinder and is divided into two sections. The front scene, under the facing reclined lion, includes an aurochs attacked by a lion and a dog. To the left, an ibex is attacked by two dogs. Branches referring to the desert environment are interspersed between these two groups. The back of the unguent jar has a similar scene, although here a gazelle is included. An aurochs is attacked by a lion and a hunting dog chases a fleeing gazelle, with its head turned back. This back section is even more densely decorated with desert vegetation. Branches, a small desert bush and a palmette like composition are found below the gazelle, as if to stress the desert landscape. While the motif of the gazelle repeated a pattern that can be traced back to the Predynastic Period, the context of the hunt scene is unusual. The gazelle alone is however connected to other cosmetic containers, albeit without the hunting reference (cf. 6.7). Even though the king is missing in the hunting scene, his presence is represented by the lion on the lid; the cartouche of Tutankhamun is inscribed on the shoulder of the lion. Therefore it could be interpreted that the lions in the hunt scene attacking the aurochs are in fact the king (cf. Ritner 1993: 129). b. Temple of Ramses III (First Pylon), Medinet Habu, 20 th dyn. (c. 1184 - 1153 B.C. (Outer face, PM II: 516 (185); Epigraphic Survey 1932: Pls 116-117) Ramses III is depicted hunting from his chariot on the south wall of the first pylon at Medinet Habu. The fleeing desert game are divided into several registers, grouped according to species including gazelles, oryx, hartebeests, as well as wild asses and hares on the upper level of the pylon. Aurochs are found on the lower half as part of a separate hunting sequence. The group of fleeing gazelles is separated into the two top registers while the other species are found apart on individual rows as well. This separation of the different species is also found in the scene from Tutankhamun’s painted chest (above 4.2.3/a.2) and in some of the private tombs in the Theban necropolis as well (cf. e.g. Userhat, TT 56, Wreszinski 1923: Pl. 26; Mentu-iwiw, TT 172, Wreszinski 1923: Pl. 353). The sole hunter in this scene is the pharaoh. This contrasts with the Tutankhamun scene, where a hunting party is depicted in side registers. The 69 weapon used is the bow and arrow. This scene appears to fall into the category “pharaoh hunts from the chariot”. c. The royal desert hunt: New Kingdom – concluding remarks The New Kingdom documentation of the royal desert hunt is very sparse, undoubtedly representing only the smallest fragment of what may have once existed, particularly on royal objects, given its occurrence among the items from Tutankhamun’s tomb. As it stands, it is the textual material that confirms the desert hunt theme as one of importance in royal iconography. In the surviving pictorial material, the chariot, a New Kingdom innovation, is incorporated into the representation of the hunt, enabling easy parallels to be drawn with military activity. This is exploited in the compositions on the Tutankhamun bow case and box where clear parallels are drawn between hunting desert ( ) game and defeating foreign ( ) enemies. Another paradigm appears to be set up with contrasting scenes where the game includes aurochs and lions (cf. Tutankhamun’s painted chest, and the scene from Medinet Habu described above), possibly with these two animals representing a higher order of enemy, as they have a close relationship to the king’s own iconography. These animals are “big game”, with the aurochs (“wild bull”) in particular having an aggressive nature that makes it a dangerous animal to hunt, sometimes turning to attack the hunter (Otto 1950: 170, however, cf. Ramses II at Abydos, Mariette 1869: Pl. 53). This may also explain why they were sometimes depicted separately, even in private tombs (e.g. Djehutihotep at el-Bersheh, Newberry 1895: Pl. VII). The distinction made between the hunt of lions and aurochs and that of the gazelle, oryx and ibex suggests that the two groups had different associations. The gazelle is represented in this material by the motifs that relate to the hunt: fleeing, hiding in wait, as well as nursing. These images became codified representations of this animal in the hunt context, indicating the long tradition that lay behind the transmission of the components that make up the desert hunt scene. 4.2.4 The royal desert hunt - concluding remarks The earliest known example of the royal desert hunt scene is from the 5 th dynasty mortuary temple of Sahure and the latest example in this corpus, is from the 20 th dynasty funerary temple of Ramses III at Medinet Habu. These two share a number of attributes. The king is depicted as the central figure, and distinguished by his superior size. He hunts with bow and arrow and the fleeing gazelle is among the many species that is the target of the hunt. The 5 th dynasty material also depicts the gazelle in various life 70 generating motifs. These are specific for the gazelle, with no other wild species used with such variety. The fragmentary early Middle Kingdom example dated to Mentuhotep II merely confirms the notion of the central position of the motif of the gazelle being hunted by bow and arrow in the desert. The New Kingdom adds the chariot to the hunt of desert game. The desert hunt scenes from the objects found in Tutankhamun’s tomb include both a version where the hunt itself is the focus (the painted chest, the unguent jar) and one where life affirming motifs such as the grazing gazelle (the bow case) and the nursing gazelle and the reclined gazelle (the embroidered tunic) occur. The gazelle motif in the royal desert hunt scenes refer to both the death of the animal and its regeneration, a combination that is more notable during the Old Kingdom, but that is still reflected in e.g. the Tutankhamun objects. With the desert hunt being an important element of private tomb decor, the similarities between royal and private trends confirm the view that the differentiation between the pharaoh and the private man can be partially bridged over when it comes to funerary iconography. “… Dieser Zusammmenstoß zweier Sphären 53 , die in der Natur des Königtums begründet liegen, spiegelt sich auch im Bereich der Privatgräber, wenngleich dort die Akzentuierung etwas anders gelagert ist. Während beim König die beiden Konstanten in seiner Natur eingebettet liegen und dadurch simultan sind, treten sie beim Privatmann in einer Aufeinanderfolge ein, da erst durch den Tod der Eintritt in die transzendente Sphäre gegeben ist. In der Grabdekoration spiegelt sich dieser Umstand in der Tatscahe, daß den rein herrscherlichen Szenen die des Totenkultes entsprechen” (Goedicke 1957: 63). 4.3 The desert hunt in private tombs There are numerous private tombs that contain a desert hunt scene. Those examined here come primarily from the classic cemetery sites of the Old, Middle and New Kingdoms. They are chosen as representative of the trends in the image of the gazelle in the desert hunt of the private tomb. 53 I.e. the “irdischen” and the “transzendenten” (Goedicke 1957: 62). 71 4.3.1 The desert hunt in Old Kingdom private tombs The Old Kingdom was a period in which a variety of themes represented “daily life” in private tomb decoration. Harpur (1987: 175) 54 identifies “eight basic themes” for this period. While the marsh hunt was common enough to constitute as a ‘basic theme’, the desert hunt is not included in this list. Still, in the Memphite necropolis, where a majority of the preserved private tombs of the period are found, the desert hunt is well represented, with some 25 examples, covering the 3 rd to the 6 th dynasties (see Appendix II). 55 The desert hunt scene of Sahure has been treated as a ‘prototype’ for this type of scene (Schweitzer 1948: 53, Vandier 1964: 791, Altenmüller 1967: 13, Ikram 2003b: 143). This composition is not however the invention of the 5 th dynasty. The Predynastic material displays a number of variations on the theme of the wild game hunt and some of the gazelle motifs can be traced back to that period. In addition there are a few examples from private tombs that antedate the scene from Sahure’s temple. The fragmentary character of the material from both royal and private contexts makes the issue of the original source(s) for the Old Kingdom desert hunt scene an open question. a. Meidum, 3 rd and 4 th dyn. (c. 2686-2494 B.C.) The earliest documented private desert hunt scenes come from the Meidum double mastaba of Nefermaat and Atet and the mastaba of Rahotep (Petrie 1892). These tombs have been dated to the transition between 3 rd and 4 th dynasties, narrowed down to the reigns of Huni and Sneferu (Huni, c. 2637- 2613 B.C., Sneferu c. 2613-2589 B.C.). Both Nefermaat and Rahotep were said to be princes (Nefermaat was , eldest son and Rahotep was , king’s son of his body) but the inscriptions do not include the name of the pharaoh (Harpur 2001: 26-27). The tomb walls were fragmentary when published by Petrie in 1892 and since that time several wall sections have been spread to various museums (e.g. fragments in the Ashmolean Museum in Oxford, no. 1910.635 and in Ny Carlsbergs Glyptotek, Copenhagen, ÆIN 1133; cf. Harpur 2001: Pls 1-80 for the list of the current locations of these fragments). The Meidum scenes provide a link between the Pre- and Early Dynastic material and the later Old Kingdom representations. 54 These eight basic themes are “marsh pursuits, agriculture, pastoral activities, horticulture, workshop pursuits, banqueting, the funerary meal, and the funeral ceremonies of the deceased, including his ‘journey to the West’” (Harpur 1987: 175). 55 The discussion of accessibility to the royal funerary temple complexes is not dealt with here. Some motifs indicate a mutual use in both royal and private context (cf. Ikram 2003b: 141). 72 a.1 Mastaba of Nefermaat and Atet (Hall), no. 16a-b, 3 rd -4 th dyn. (North wall, Cairo 43809 (Nefermaat); Pennsylvania University Museum E.16141 (Atet); PM IV: 93-94, Petrie 1892: Pls XVII; XXVII) There are only glimpses of the desert hunt scene in this mastaba. The scene in Nefermaat’s part of the tomb probably extended over several registers, involving the usual hunting dogs and various antelopes (Petrie 1892: Pl. XVII). On the opposite south wall of the hall was an unusual scene of boat building (PM IV: 94, Petrie 1892: Pl. XXV), with fishing and fowling found on the lintel of the side of the façade (PM IV: 93, Petrie 1892: Pl. XXIV). In Atet’s section (no. 16 b) the desert hunt took up three registers (PM IV: 94, Petrie 1892: Pl. XXVII). Nefermaat is shown oversized holding a leash in his hand, which is attached to the hunting dogs in two of the registers, Atet stands next to her husband, considerably smaller in size. The top register shows a hunting dog grasping a large hare by its neck. The middle register consists of two striding animals, facing right, an ibex and a fallow deer (?). 56 The third register features another hunting dog on a leash grasping the hind leg of a gazelle. Immediately below this scene, the bringing of desert game (cf. Chapter 5) can be observed, all facing left. This image of a dog attacking a gazelle, familiar from earlier source material, is the earliest known from a private tomb. a.2 Mastaba of Rahotep (Passage), no. 6, 3 rd -4 th dynasty (South wall, Cairo T19.11.24.3G; PM IV: 91, Petrie 1892: Pl. IX) The desert hunt of Rahotep is divided into two registers on the south wall in the passage. Remains of fowling and fishing scenes are located on the opposite north side (PM IV: 91, Petrie 1892: Pl. X). The scene breaks off on the left side. The upper row has five striding foxes, all facing right. The fox to the far left is shown under attack by a hunting dog that 56 This tentative suggestion is based on the white muzzle and the white area around the eyes, which is found on the fallow deer (cf. colour drawing in Kingdon 1997: 338). Further, a fallow deer (with antlers) is shown on the bottom register, as a part of bringing offerings. Cf. Harpur 2001: 89 “brown antelope”. 73 Figure 25. Rahotep: Gazelle head turned grasps the tail in its mouth. 57 The lower register shows, from right to left, an ibex, followed by two gazelles. One of the gazelles has both front hooves off the ground, with its head turned back, apparently vigilant and fleeing. The gazelle behind it is represented by a head upside down. The original image most likely was that of an attack by a hunting dog, parallel to the one in the register above. The ibex, in contrast, is shown striding. A badger is found on an insert above the gazelle. Its identification is unsure, with Osborn (1998: 84) suggesting an African badger Mellivora capensis. A discreet reference to the desert environment can also be noted with the small undulating hill. To the right of these two registers, the laconic inscription read , ‘inspecting the catch’. The tomb owner stands to the right of these registers, looking at the desert game. Rahotep is shown oversized, holding a staff and a scepter. He is followed by his wife Nofret, who is considerably smaller in size. The two motifs of the downed and fleeing gazelle, head turned in vigilance, are two fundamental images familiar from earlier material and later included in the Sahure desert hunting scene. b. Saqqara, 4 th – 6 th dyn. (c. 2613 – 2181 B.C.) A large number of the hunt scenes dating to the Old Kingdom are located in mastabas at Saqqara. The published material gives one example dated to the 4 th dynasty, c. nine from the 5 th dynasty and six from the 6 th dynasty (cf. Appendix II). The 4 th dynasty example represents a continuation of earlier compositions, displaying examples of hunting dogs grasping the hind leg of fleeing animals (Methen, Smith 1949: 152, Fig. 60). The composition of the 5 th dynasty scenes is more varied and has greater individuality in their layout. Yet it is clear that the gazelle motif is treated as canonical, as the images are restricted to a few poses: the dog/lion attacking gazelle, the fleeing gazelle, with head turned, the nursing gazelle, gazelle on inserts and in addition the combination of two gazelles. The use of specific motifs for the gazelle, as well as for other species, indicates that the elements that made up the composition of the hunting scenes had become standardised. 57 An almost identical scene is seen in the tomb of Nefermaat as well (Petrie 1892: Pl. XVII). A hunting dog was grasping the tail of a red fox (Osborn 1998: 69) among a group of three. 74 b.1 Mastaba of Raemka (Chapel), no. 80 (D3, S 903), 5 th dyn. (South wall, (D3, S 903); PM III/2: 487 (3) = MMA 1908.201.1, Hayes 1953: 99, Fig. 56) On the blocks that once made up the south wall of the chapel of Raemka, at least two registers are devoted to the desert hunt. The upper register focuses on the gazelle and the lower row on the ibex. From the left to right, in the upper register, a man leans on a staff watching dogs attack desert game. The man is labelled , ‘hunter’ (Faulkner 1962: 127), even if not active in the hunt. In front of him, a hunting dog ( ) attacks a red fox by biting its neck (Osborn 1998: 70). In the middle of the row another grasps the hind leg of a gazelle, which has its head turned back to the left toward its attacker. The register ends with a pair of striding gazelles ( ). Two inserts are included, the left one containing a crouching hare and the second insert a recumbent gazelle. This animal has also been provided with a caption reading . The animals on this upper register are facing right, away from the man on the far left. Figure 26. Blocks of Raemka The lower register, featuring ibexes as the game, includes two hunters ( ) using lassoes. There is a group of three ibex (two adults, one young), identified as , ‘ibex’. At the lower right, an ibex has been caught, with the heading reading , ‘lassoing ibex by hunter’. An insert with a hedgehog is found on the top left section of the row. The separation of the gazelle and ibex into two different registers exemplifies the intentional use of the different species as a compositional device that is otherwise rather unusual (cf. above e.g. Tutankhamun 4.2.3/a.2). It is notable that it is the dog that hunts the gazelle and fox, while 75 the ibexes are captured by men using a lasso. In the desert hunt scenes of private tombs, the gazelle is rarely seized by a human hunter, but more generally by a dog or lion (e.g. Thefu, Hassan 1975b: Pl. LXXXVI, C). The differentiation between species in the separate registers is further stressed by the direction of the animals, with the gazelles facing left to right and the ibexes right to left. All three motifs featuring the gazelle are typical: the gazelle attacked by dog, the pair of animals and the recumbent gazelle in an insert. b.2 Mastaba of Pehenuka (Room I), D 70 (LS 15), mid 5 th dyn. or later (West wall, Berlin 1132; PM III/2: 491 (4), Harpur 1987: 530, Fig. 188) Figure 27. Pehenuka: gazelle nursing within desert hunt The desert hunt scene, preserved on a block now in Berlin, was accompanied by a fowling and fishing scene on the lower section of the same wall. The desert hunt scene is fragmentary, with the documentation of Lepsius (LD II: Pl. 46, reproduced as Harpur 1987: 530, Fig. 188) indicating that it originally included at least two registers. The lower and better preserved register has typical desert hunt elements. To the left a man controls an ibex by grasping its foreleg and horns. This is accompanied by a nursing gazelle to the right. Next to this group is a fleeing oryx with its head turned back. The remains of two hunting dogs, face to face, can be distinguished on the right end of the block, one is attacking a leopard 58 and the second bites the neck of a fox (Osborn 1998: 53). The motif of the gazelle mother suckling her fawn is found in the midst of the hunting. It provides a contrast to the hunt of the desert animals. The species that can be identified in the fragmentary inserts are from left to right, hare, two hedgehogs, gazelle (?), porcupine and jungle cat (cf. Osborn 1998: 53). 58 This is a tentative identification as there are no characteristic spots; the suggestion is based on the position of the head: “Leopards are usually shown with their heads lowered…” (Osborn 1998: 119). 76 The inclusion of a nursing gazelle, with its implication of birth giving, can be observed in the approximately contemporary scenes from the monuments of Niuserre and Unas (cf. above 4.2.1/b-c). The fragmentary state of the Pehenuka scene makes it is impossible to establish if it included a gazelle attacked by dog. b.3 Mastaba of Ptahhotep [II] (Offering room), D 64b, late 5 th dyn. (East wall, PM III/2: 601 (17) IV; Davies 1900: Pl. XXI) The desert hunt scene in the tomb of Ptahhotep is located on the eastern wall of the offering room. The netting of fowl is found on the same wall, a few registers down (PM III/2: 601 (17) IV). The scene extends over two registers, and despite the limited space, there is a generous variety of motifs, including not only the hunt of wild game but also images of mating and nursing animals (Davies 1900: Pl. XXI). Figure 28. Desert hunt of Ptahhotep The upper register contains the motif of a nursing gazelle among the hunting action. To the left an oryx is bitten on the throat by a dog and to the right a hunting dog tugs at the hind leg of an ibex. This creates an interesting “triad”, with the nursing gazelle between an oryx and ibex, both attacked by dogs. The placement of a suckling gazelle in the middle of the hunting activity is similar to the arrangement of elements in the tomb of Pehenuka discussed above. To the far right in the upper register, two pairs of leopards and red foxes (Osborn 1998: 61) mate. In the lower register a kneeling hunter holds two hunting dogs on leashes, pointing at the many animals in the scene, including a lion confronting an aurochs and a hunting dog downing a gazelle by biting the neck, the gazelle has its head turned (cf. above Nefermaat). This is followed by another oryx attacked by a hunting dog and at the right end of the scene is a man with lasso, capturing two aurochs and a hartebeest. Four inserts are included (from left to right), one with a recumbent gazelle, facing left, followed by an ichneumon (Osborn 1998: 61), jerboa and two hedgehogs. 77 The gazelle occurs in three contexts, as prey downed by the hunting dog, nursing its young, and in the insert, as a young animal, hiding from the hunters. b.4 Mastaba of Niankhkhnum and Khnumhotep (Vestibule), 5 th dyn. (Above doorway, west wall; PM III/2: 642 (10, III-V); Moussa and Altenmüller 1977: Pls 38, 40) The desert hunt scene in the joint tomb of Niankhkhnum and Khnumhotep is fairly detailed and extensive, distributed over three registers (Moussa and Altenmüller 1977: Pl. 40). The fishing and fowling scene is located in two different places in the tomb; on the south wall of the forecourt (PM III/2: 642 (4) a-b) and on the south wall of the vestibule (PM III/2: 642 (9)). The tomb has been dated to the reign of Niuserre (Moussa and Altenmüller 1977: 44). The horizontal edges of the blocks are damaged, breaking up parts of the reliefs. The desert scene contains some unexpected elements. Fences flank the registers depicting the hunt, possibly one of the earliest uses of this feature in a private tomb. Also, there is an unusually large number and diversity of species in the inserts, including, uncommonly, young hartebeest and addax. The gazelle can be identified with certainty, using the shape of the horns as the criterion, three times, while the other antelope young are found in the inserts, lacking horns, they are designated as ‘kid’ ( ) confirming that this space could be used for young animals, hiding from danger. 59 No actively hunted gazelle is found. This is an anomaly, as in this rich variation of motifs, a ‘hunting dog attacking gazelle’ would be expected. In the midst of the hunting activity is however a gazelle nursing its young (upper register, left section), a feature which corresponded to the components of the scenes from Pehenuka and Ptahhotep, discussed above. b.5 Mastaba of Meryteti (Room I), Tomb C, 6 th dyn. (Above doorway, west wall; PM III/2: 536 (112), Decker and Herb 1994: Pl. CXL) The documentation of more or less complete desert hunt scenes from the 6 th dynasty in the Saqqara necropolis appears to be limited to those of Mereruka and his son Meryteti in their large family mastaba complex. The larger part of the mastaba belongs to Mereruka, while his wife and son each have a smaller section (for the plan see PM III/2: Pl. LVI). Of the two desert hunt 59 An unusually frequent use of inserts can be discerned, containing the ‘traditional’ animals such as hedgehog (4 times) and hare (once). The colour photograph in Moussa and Altenmüller (1977: ‘frontispiece’) suggests an identification of some of the fawns as addax (white-grey) and hartebeest (yellowish); the colour of the one gazelle in insert is red-brown. 78 scenes found in this complex, that of Meryteti is the more interesting with its large variety of animals and choice of more complex motifs. Meryteti’s desert hunt scene is located on the west wall above the doorway leading to the first room (Decker and Herb 1994: Pl. CXL). It differs from a similar scene found in his father’s section of the mastaba. 60 There are no marsh scenes in the Meryteti’s section of the mastaba. Five registers are allotted to Meryteti’s desert hunt scene. There are no ‘anomalies’ in its composition. The gazelle is found in traditional motifs; both striding and attacked by a lion and a hunting dog. There is an extensive use of inserts, which include not only the traditional gazelle, hedgehog and hare, but also two ibex and one oryx. 61 The gazelle is found most frequently of the animals with at least six examples that can be identified with certainty. The unusually large number of young gazelles in the inserts suggests that the collection of young gazelles is a significant component of the scene’s composition. This observation is strengthened with the inclusion in this desert hunt scene of a man carrying baskets from a yoke, containing young animals (the photograph is too grainy to determine species, other than an ibex). The man stands among the desert game (centre of the upper row) suggesting that here is a “man collecting desert young” (cf. Osborn 1998: 176). A similar depiction is found on the Niuserre blocks (cf. above 4.2.1/b). The ‘gazelle in basket’ motif is discussed below (5.1.1/b.3). c. Giza, 4 th – 6 th dyn. (c. 2613 – 2181 B.C.) Only four examples of desert hunt scenes have been documented at Giza (cf. Appendix II). The tombs of Seshemnefer (IV) (LG 53, PM III/1: 224 (6)) and Nimaatre 62 (G 2097, PM III/1: 70) include examples of a rather unique motif for the gazelle. c.1 Mastaba of Nimaatre (Chapel), G 2097, late 5 th dyn. (East wall, PM III/1: 70; Roth 1995: Fig. 189) The mastaba of Nimaatre has been tentatively dated to the late 5 th dynasty 60 With one common motif; a wild animal being torn apart by several dogs. The composition of this motif is unique as the prey is depicted as if seen from above, and the hunting dogs are gathered around, reaching from two separate registers. 61 The register with ibex and oryx is carved larger in proportion to the ‘true’ inserts. The other inserts on the tomb wall of Meryteti are of conventional size. 62 Ikram. (1991: 52) refers to the tomb owner as ‘Isesimernetjer’ and Roth (1995: 127-134) uses the name ‘Nimaatre’ 79 reign of Unas (Roth 1995: 129). The hunt is located on the east wall, while the marsh scene is on the north (Roth 1995: 130-132). Agricultural activities are next to the desert hunt (‘harvest’) (Roth 1995: 133). The desert hunt scene in the tomb of Nimaatre is divided into three registers, with two of the rows showing traditional hunt motifs. In the lower register “an astonishing variety of animals are engaged in copulation” (Roth 1995: 132, Fig. 189). This entire register is a long sequence of mating animals; at least twelve different species can be identified, including wild asses, ichneumons and foxes. 63 With an unusually intense focus on the mating motif, this version of the desert hunt is reminiscent of the earlier royal scenes of Niuserre and Unas, where a special attention was given to foaling and mating, rather than to hunting and the capture of wild game .64 Despite the poor condition of the reliefs, two pairs of mating gazelles can be observed. One is an unusual example of the mating of dorcas gazelles, while the other is the single known example of mating Soemmerring’s gazelles. 65 The side by side depiction of these two gazelle species is a parallel to the composition found in the royal desert hunting scenes. 66 c.2 Mastaba of Seshemnefer [IV] (Vestibule), LG 53, late 5 th - early 6 th dyn. (West wall, PM III/1: 224 (6), Junker 1953: 152-153, Fig. 63) While the registers with the desert hunt scene are located on the west wall of the vestibule, the deceased spearing fish from a canoe is on the north wall of the forecourt (PM III/1: 224 (5)). The tomb wall is decorated with three registers of ‘traditional’ desert hunt motifs. There are numerous participants in the hunt, ranging from men 63 Cf. Ikram 1991: Table 1. 64 The mastaba of Nimaatre is the only Old Kingdom private tomb where the ostrich occurs. There is an interesting comparison with the Niuserre reliefs in that there too the ostrich is found together with life giving motifs (cf. 4.2.1/b above), suggesting that this composition may have been influenced by a royal model. 65 Roth (1995: 132) incorrectly identifies the mating Soemmerring’s gazelles as “bubalis”. 66 Sahure (Borchardt 1913: Pl. 17), Niuserre (von Bissing 1956: Pls XI, XII) and Unas (Hassan 1938: Pl. XCVII A). 80 Soemmerring’s gazelles Figure 29. Nimaatre: mating dorcas and with lassoes to hunting dogs and a lion. The gazelle is notable in the middle and lower registers. In the centre row, the familiar motif of a recumbent gazelle in an insert is found. At the far right on the same register another gazelle is being held by a man with a rope. On the lower register is yet another insert featuring a recumbent Figure 30. Seshemnefer: mating gazelles in desert hunt gazelle, next to two bushes. Here, only the gazelle is found in the inserts. To the left various species have been grouped together, these include (from right to left) the gazelle, two hartebeests, an oryx and an addax (facing left). The gazelle is shown with its head turned back, facing left and its front feet off of the ground. To the right of this group an ibex is seized by a hunter, followed by a pair of mating gazelles. To the far right an oryx is seized by another hunter holding the lasso tightly. These examples from two Giza mastaba, represent the earliest known examples of mating gazelles. d. Deir el-Gebrawi, 6 th dyn. (c. 2345-2181 B.C.) Deir el-Gebrawi is located on the eastern bank in middle Egypt, between Amarna and Assiut, a considerable distance from the Memphite necropolis. Some 15 rock cut tombs dated to the Old Kingdom are found here. Two of 81 these tombs feature a desert hunt scene: Ibi (Davies 1902a: Pl. XI) and Djau (not strictly a desert hunt scene, tomb no. 12, Davies 1902b: Pl. IX). That belonging to Ibi is discussed below. d.1 Rock-cut tomb of Ibi (Hall), no. 8, 6 th dyn. (North wall, PM IV: 244 (11); Davies 1902a: Pl. XI) The desert hunt scene of Ibi is located on the north wall in the hall, and on the opposite south wall the marsh scene is found (PM IV: 244 (3)-(4)). A harvest scene is found next to the hunt (Davies 1902a: Pls II, XII). The desert scene in the tomb of Ibi is divided into two registers; unfortunately its condition is very fragmentary (Davies 1902a: Pl. XI). Figure 31. Ibi: desert hunt scene The upper register is devoted to the hunt of desert game; to the right are some faint traces of a pair of hunters. One man kneels and holds a bow and arrow, the other has a hunting dog, ready to stalk its prey. This is one of a few examples of a hunter with bow and arrow in an Old Kingdom private tomb. 67 Unfortunately the condition of the scene does not allow further description of the upper register. In contrast to the upper register, the lower depicts the daily life of the desert game. To the far left, a lion downs a 67 One of two examples of the use of bow and arrow in a private tomb dating to the Old Kingdom. The second example is from the tomb of Pepy-nakht Hekaib at Qubbet el-Hawa, that is broadly dated between the 6th dynasty and the Middle Kingdom (Decker and Herb 1994: 313, Pl. CXLII (J 49)). 82 gazelle. This is accompanied by an inscription reading ! " ! " , ‘catching a gazelle by a wild lion’. 68 Next to this image is a group of gazelles striding in different directions. The inscription once again provides additional information, reading and i.e. female gazelle and male gazelle. This kind of distinction between female and male gazelle is unusual, while indicating that specific terminology for the male and female was current. The Ibi example is the only known desert hunt scene to be copied and used in another tomb. The upper register of this scene is found in the tomb of another Ibi, dated to the 26th dynasty, located at Sheikh Abd el-Gurna (TT 36, PM I/1: 67 (20), cf. 4.3.4). Some of the individual components of this scene are found in the Middle Kingdom tombs at Beni Hassan. The hieroglyphic inscription referring to the attack of a lion, the distinction between male and female gazelle and the group of gazelles with animals striding in opposite direction are found in the Middle Kingdom tombs of Baqt [III] and Khety (Newberry 1894: Pls IV, XIII, below 4.3.2/a.2). e. Old Kingdom private tombs – concluding remarks Evidence points to a relationship between private tomb iconography and that found in the royal examples of the desert hunt scenes. The narrative of the hunt was enhanced by adding the nursing and mating gazelle in the repertoire of desert hunt scenes. Thus motifs representing the entire life cycle of the gazelle are represented: the mating gazelle (private), the foaling gazelle (royal), the nursing gazelle (royal, private), gazelle fawns in inserts (royal, private), the grazing gazelle (royal, private) and finally the attacked gazelle (royal, private). The motifs found in the funerary iconography of the Middle and New Kingdoms are more limited, with the use of the gazelle motifs on tomb walls decreasing, without however ever disappearing completely. Even though the Middle and New Kingdom private desert hunt scenes are almost as numerous as those from the Old Kingdom, their composition is less varied. 4.3.2 The desert hunt in Middle Kingdom private tombs The images of the gazelle used during the Middle Kingdom are found in the 68 Cf. Wb III: 161 for translation of as ‘wild lion’. Two of the Middle Kingdom tombs at Beni Hassan have the same motif and narrative; i.e. a wild lion seizing an animal, where the verb was spelled instead of ! " , thus translated as “grasp, hold fast, catch” in Faulkner 1962: 145. 83 same contexts as in the Old Kingdom, mainly in the hunting and offering scenes (cf. Chapter 5) on the walls of private tombs. The motifs used are however restricted almost solely to the hunt, with life generating images being found in only a few examples. In contrast to the older scenes, which are concentrated to the tombs of the Memphite necropolis, the Middle Kingdom examples are found spread along the Nile Valley: el-Bersheh, Beni Hassan, Meir, Thebes, Qubbet el- Hawa, el-Mo’alla, el-Kab, Hawawish, el-Saff etc. (cf. Appendix II). The composition of the scenes found on the tomb walls varies from site to site. The hunt scene however represents earlier traditions. Since there is a limited variation in the use of the gazelle motifs in these scenes, only a small selection is discussed below, with a focus on the continuity from the Old Kingdom and noting the importance given the hunter during this period. a. Beni Hassan, 11 th – 12 th dyn. (c. 2055 – 1773 B.C.) The necropolis of Beni Hassan lies on the eastern bank in Middle Egypt. This site served as the provincial cemetery for the nomarchs of the 16 th Upper Egypt nome during the Middle Kingdom. Although Beni Hassan provides good examples of local art, the themes chosen for the tombs correspond to the standard selection. Typical for Beni Hassan is the use of a single register for the desert hunt, in contrast to other older and contemporary compositions that tended to occupy two or more registers. Desert hunt scenes are present in several of the rock cut tombs. Few however have survived completely intact. a.1 Tomb of Khnumhotep [III] (Hall), BH 3, 12 th dyn., Sesostris II (North wall, PM IV: 145 (7)-(11); Newberry 1893: Pl. XXX) The hunt scene in the tomb of Khnumhotep III is located on the north wall of the hall, while marsh scenes are found on the east wall (PM IV: 147 (12)-(14)). Harvesting and ploughing took place on the west wall (PM IV: 145 (6)). The depiction of the desert hunt is divided between two main registers instead of the one usually found in other tombs at this necropolis. Each of these includes a longer insert, corresponding to those found in Old Kingdom scenes, with the addition of unusually detailed representations of different feline species, such as caracal, serval, lynx and cheetah/leopard (Osborn 1998: 14) not seen elsewhere in ancient Egyptian art. Khnumhotep is portrayed oversized, assisted by four bowmen and several hunting dogs. These hunters are positioned at the left of the desert hunt scene. The use of bow and arrows is extensive, which is consistent with the Old Kingdom royal material and the reliefs of Mentuhotep II at Deir el- 84 Bahari, indicating that this manner of hunting is also appropriate for non- royal high-ranking individuals, such as the nomarch. Khumnhotep, found to the left of the scene drawing his bow, is positioned where the tomb owner is normally found overseeing agricultural activities. His active participation as an oversized hunter in that position is noteworthy. Figure 32. Khnumhotep desert hunt, with foaling gazelle The top register features, from right to left, a group of three gazelles, one of them has its head turned back facing left. An arrow is penetrating one of the hind legs. The next animal is an aurochs facing the arrows shot from the left. Otto (1950: 170) has remarked that the aurochs is the only animal that faces its attacker, the other animals are generally seen fleeing. Facing the aurochs in this scene is a lion that also appears to be a prey animal here as two arrows are aimed at it. Behind the aurochs is a group of hartebeest, two adults and one young. A hunting dog grasps the hind leg of the young. One of the assisting hunters is close to the dog. Behind him, a second aurochs confronts another bowman, who is also accompanied by a hunting dog. The top register ends with a third aurochs. All three aurochs are facing left, while the other animals on this row flee in the opposite direction. The long insert includes from right to left, a hare, a serval, a jerboa, a winged chimera, a hedgehog, a cheetah/leopard, a fox (?) and finally a genet (cf. Osborn 1998: 14 for comments on the discrepancies in identifications). All of these animals are facing right, i.e. same direction as the hunted animals. The inclusion of a mythical animal emphasizes the funerary character of this scene. The bottom register (from right to left) includes two scribes, one of them is guiding an oryx. They seem to stand on a straight ground line and are therefore probably not a part of the desert hunt scene proper. A foaling oryx follows. A fox sniffs the young as it is about to be born. This life giving motif is contrasted by that to the left, where two ibexes are standing side by side, one of them has its head turned back, looking at the hunting dog tugging at its hind leg. The same fate is in store for the oryx behind them who is also attacked by a dog. A third man has drawn his bow to shoot at the animals in front of him. Behind him, yet another two oryxes were under the attack from 85 arrows shot by the fourth bowman. This register also ends with an aurochs, larger than those on the upper row. It seems that Khnumhotep himself is responsible for shooting the arrow that penetrates the aurochs. The insert in the lower register includes (from right to left), a genet (?), a hedgehog, a foaling gazelle, a fox (?) 69 and two lynxes (Osborn 1998: 14). The gazelle gives birth in a reclined position, with its head turned back facing left. This composition differs from those seen on the royal temple reliefs of the Old Kingdom, where foaling takes place standing and on the main ground line. This is the only example, in this documentation, of a foaling gazelle in a private tomb. a.2 Tomb of Khety (Hall), BH 17, 11 th dyn. (North wall, PM IV: 155 (2-3), 156 (5); Newberry 1894: Pl. XIII) There are two desert hunt scenes on separate registers on the north wall in the hall of Khety’s tomb, a feature that is not found elsewhere. The scene located on the western half of the wall, typical for Beni Hassan, shows various striding animals (Newberry 1894: Pl. XIII). This can be divided into two narratives; the left part focuses on the wild life while the right emphasises the hunt. The wild life motifs include hartebeests mating, a lion knocking down an ibex, described with the heading “grasping an ibex (by) a lion”. This is a comment similar to that found in the Old Kingdom tomb of Ibi discussed above (4.3.1/d.1). The gazelle to the left of this group is identified as , while another individual further to the right on the row was labelled with the feminine form . Furthermore, another short comment reads , “jackal grasps gazelle”. The similarity in both compositions, as well as the similarity to the hieroglyphic inscriptions of the tomb of Ibi at Deir el-Gebrawi, strongly suggests a common source. Figure 33. Khety: hunting aurochs and gazelles The second desert scene is more concise in its composition. The use 69 Osborn (1998: 14) tentatively suggests either “fox or genet (?)”. 86 of fences to trap the prey can be observed, with the hunters being found within the enclosure. Aurochs and gazelles are pursued by the hunters. Both bow and arrow and the lasso are employed to capture the aurochs. Of the four gazelles, one is caught by the lasso, while another looks back at the hunter. Two hunting dogs seize the other gazelles, with one on its back while being choked, and the other trying to escape the dog that is tugging at its hind leg. 70 These two desert hunt scenes have analysed the hunt as consisting of scenes in the wild and of the containment of the prey, perhaps referring to a two-step process that reflects the chaos and order paradigm. The life-giving motifs have been excluded in the second scene. b. Meir, 12 th dyn. (c. 1985-1773 B.C.) Meir is situated on the western bank, some 60 km south of Beni Hassan. The cemetery there contains the tombs of the nomarchs of the 14 th Upper Egyptian nome. There are only two desert hunt scenes found in the Middle Kingdom tombs of that cemetery. One is in the tomb of Senbi and the other is found in the tomb of Ukhhotep, son of Senbi. b.1 Tomb of Senbi (Hall), B 1, 12 th dyn., Amenemhet I (East wall, PM IV: 249 (1); Blackman 1914: Pl. VI) The hunt scene in the chapel of Senbi is located on the east wall, next to the entrance. A marsh scene is situated on the lower section of the north wall. The composition of Senbi’s desert hunt is reminiscent of that of Sahure as it includes a fenced off area, with Senbi standing outside, oversized and ready to shoot an arrow. He is followed by a smaller figure, standing behind him, in the place where in the royal scene the king’s ka is found. Even though there are no formal registers, the original layout seems to have been divided into three ‘main rows’, with additional undulating lines forming their individual space. It is difficult to ascertain the intended division. A hyena, in the middle of the lower row, with one arrow piercing its muzzle and another in its lower abdomen is that found in the Sahure reliefs (Ikram 2003b: 143). The gazelle is depicted in three different motifs. A hunting dog grasping the neck of a fleeing gazelle is to the far left on the middle ‘row’. On the opposite side, in the upper right section of the scene, a nursing gazelle can be spotted. The mother is eating from the bush. Included behind this 70 The choice of aurochs and gazelles to illustrate a desert hunt scene is reminiscent of the scene in the tomb of Djau at Deir el-Gebrawi (Davies 1902b: Pl. IX), where these two specific species represent wild game. Furthermore, the captions in the other desert scene of Khety are similar to those found in the tomb of Ibi, also at Deir el-Gebrawi. 87 88 group is a pair of mating leopards, and above them a wild ass is foaling (Osborn 1998: 62). These three life affirming motifs appear to form a group separate from the hunt, even though they are located within the enclosure. This differs from other desert hunt scenes that prefer to position the enclosure within the chaos of the hunt. The insert-like motif in the middle of the uppermost ‘row’ is also worth noting. There are three reclining gazelles with two of the animals tail to tail, facing in opposite directions, while the central gazelle has its head turned back. This variation indicates an awareness of composition that extends beyond naturalistic representation. b.2 Tomb of Ukhhotep (Hall), B 2, 12 th dyn., Sesostris I (South wall, PM IV: 250 (2)-(3); Blackman 1915a: Pls VII-VIII) The hunting scene of Ukhhotep ( , son of Senbi) is located on the south wall of the hall. There are no scenes depicting the marsh hunt in this tomb. The desert hunt composition is uncharacteristically spread out, functioning as individual images separated by open spaces (Blackman 1915a: Pl. VII). There are no details of the desert environment. The deceased, shown oversized to the left of the scene, participates in the hunt. He is assisted by a man, similar to the one seen in his father Senbi’s tomb. There are no fences defining an enclosed hunting area. Each of the prey animals is pierced with arrows and seized by dogs, illustrating the two hunting methods used. The prey includes gazelle, ibex, oryx and hare. The mating motif found in the composition features a pair of lions, oryxes and gazelles. The regenerative Figure 35. Ukhhotep: circle is completed with birth-giving gazelle seized by dogs scenes featuring a monkey and wild and pierced by arrow ass (Blackman 1915a: Pls VII, VIII). 4.3.2/c Thebes, 11 th – 12 th dyn. (c. 2055 – 1773 B.C.) There are five examples of desert hunt scenes that can be dated to the Middle Kingdom in the Theban necropolis. These are found in the tombs of Intefiker (TT 60), Dagi (TT 103), Khety (TT 311), Djar (TT 366) and Intef (TT 386). The general condition of these scenes is poor. Their remains conform to the general composition of the Middle Kingdom desert scenes. The layout of these painted reliefs is typical for the Theban tombs of the New Kingdom. 89 c.1 Tomb of Intefiker (Passage), TT 60, 12 th dyn., Sesostris I (North wall, PM I/1: 122 (9); Davies and Gardiner 1920: Pl. VI) The hunt scene of Intefiker is situated on the north wall of the passage, next to the fishing and fowling scene found on the same wall (including a sub-scene with “ploughing, sowing and hacking”; PM I/1: 122 (8)). The Intefiker tomb wall was in poor condition when it was documented. Still a general impression of the scenes is possible (Davies and Gardiner 1920: Pl. VI). The desert hunt scene is divided into five registers, with fences flanking either side. Intefiker stands outside the enclosure, to the left. He is shown oversized, holding bow and arrow. Behind him stands an assistant, similar to those seen in Meir tombs. These details can be traced back to the Sahure prototype. In the top register, to the far right, the standard motif of hunting dog attacking gazelle, grasping its neck, is included. The gazelle is lying on its back. In the register below, the main focus for the hunt, the aurochs, is located. It has two arrows piercing its body and a hunting dog tugging at its hind leg. Another aurochs and its calf are fleeing in the opposite direction. Figure 36. Desert hunt of Intefiker (TT 60) 90 The third register from the top featured, yet again, gazelles fleeing facing right. Underneath the belly of the one of the gazelles is a hare, the second is confronted by a dog and the third gazelle at right end of the register has its head turned back, facing left. A foaling oryx has been included on the left end as well, standing on its knees (forelegs) and being attacked by a greyhound (Osborn 1998: 64). On the fourth register down, in the centre, the motif of hyena 71 with arrow in muzzle can be spotted, another detail that can be traced back to the Sahure prototype (Ikram 2003b: 143). The other species featured on this row are, from right to left, two hares, a wild cat, hedgehog (?), red fox and jackal (Osborn 1998: 64). The bottom register consists of two Barbary goats trying to escape a hunting dog. At the right end of the row yet another oryx is foaling. The gazelles found in this scene are hunted and seized by the dog. The life giving aspect is represented by the oryx giving birth. d. El-Saff, 11 th dyn. (c. 2055-1985 B.C.) El-Saff is located on the east bank, across from Lisht, approximately 50 km south from Memphis. The location is best known for a cluster of Predynastic burials of the Maadi culture (Habachi and Kaiser 1985: 43-46). The 11 th dynasty tomb of Ip was only published by chance. Fischer had purchased a set of photographs from an unknown tomb. He showed them to Habachi who identified the tomb as that of Ip at el-Saff; Habachi had cleared the tomb of Ip in 1936 (Fischer 1996: 1). d.1 Tomb of Ip (South (?) 72 ), 11 th dyn., Mentuhotep (II?) (Right wall, left end; Fischer 1996: Pl. A, 3a) A rather damaged desert hunt scene is found in the tomb of Ip (Fischer 1996: Pls A, D; 3a). It is located next to or above a marsh hunt scene that has far more space devoted to it. The remains of the desert hunt include the motif of opposing gazelles with most of the upper register devoted to this image. They are separated by a small hill and bush. The animal to the right is clearly identifiable as a dorcas gazelle, while the one to the left is most likely a Soemmerring’s gazelle ( , 71 Osborn (1998: 64) suggests an identification as a “jackal (?)”. Considering the earlier compositions, the tradition and appropriation, it is more likely to be a hyena (cf. Ikram 2003b). 72 Fischer’s publication of this tomb does not provide a plan or layout of the tomb, which is divided into left, right and rear wall, leading to the burial chamber. The suggestion made by Fischer (1996: 5) compares it with contemporary tombs at Beni Hassan: “This may be the most opportune place to note that the right-hand (presumably southern) wall….”. 91 cf. e.g. the Soemmerring’s gazelle in the tomb of Ptahhotep, Davies 1900: Pl. XXII). Fischer (1996: 14) suggests that the two are male and a female. The slightly larger size of the left gazelle and the indication of a scrotum indicate that Fischer’s observation is most likely correct. The combination of the dorcas and Soemmerring’s can be traced back to the Old Kingdom when it is found in the royal desert hunt scenes as well as in private tombs (Sahure, Borchardt 1913: Pl. 17; Niuserre, von Bissing 1956: Pl. XI a; Unas, Hassan 1938: Pl. XCVII A). An added element here is the hunting dog tugging at the hind leg of the Soemmerring’s gazelle. The rest of the scene was in poor condition when documented. The motif of opposing gazelles, sometimes separated by vegetation (palmette), is also found in contexts other than the hunt scene in the New Kingdom. This motif has been interpreted (Montet 1937: 144-145, Crowfoot and Davies 1941: 127-128, Kozloff 1992: 286) as reflecting influences from Western Asia, as the majority of the examples come from a period when the contacts between Egypt and its neighbours are intense. The occurrence of this motif in the tomb of Ip, dated to the 11 th dynasty (Fischer 1996: 29-32), suggests that this is not necessarily the case. Furthermore, the motif of gazelle eating from a bush can also be traced back to the 5 th dynasty, in both royal and private desert hunt scenes (i.e. Niuserre, Niankhnum and Khnumhotep and Pehenuka). Although the tomb of Ip provides the earliest documentation of the opposing gazelles separated by vegetation, it becomes a more common motif on objects later on (cf. below 6.4). e. Middle Kingdom private tombs – concluding remarks The geographical diversity of the Middle Kingdom private tombs decorated with desert hunt scenes does not appear to have affected the choice of gazelle motifs. They instead reflect those developed during the Old Kingdom, and found in the mastabas of the Memphite necropoli. There is however some narrowing of focus, as there is an emphasis on the hunt, found in several variations, dogs, arrows, lassos, with a minimizing of life giving motifs (mating, giving birth, nursing). 4.3.3 The desert hunt in New Kingdom private tombs Desert hunt scenes from New Kingdom private tombs are found in the Theban necropolis. The composition of the New Kingdom scenes appears to be related to that of similar scenes in the Middle Kingdom tombs nearby (e.g. Intefiker, TT 60, Davies and Gardiner 1920: Pl. VI; Intef, TT 386, Jaroš-Deckert 1984: Pl. 21). The tendency to limit or exclude life affirming motifs, 92 found in the Middle Kingdom, continues in the New Kingdom versions of the desert hunt. There are as always exceptions where life affirming motifs occur, albeit strikingly few. 73 Twenty-seven examples of the desert hunt scene from New Kingdom tombs of the Theban necropolis have been included (cf. Appendix II). The condition of most of these is poor. There is little variation with regard to narrative features, yet no two are identical. All of the New Kingdom examples from private tombs are dated to the middle of the 18 th dynasty (Manniche 1988: 38-39), coinciding with the reigns of Hatshepsut-Thutmosis III and Amenhotep II (c. 1479-1400 BC). This corresponds to the period of interest in the royal hunt as an aspect of kingship and predates the survival of royal hunt scenes (cf. above 4.2.3). The decoration of the 19 th dynasty tombs in the same necropolis changes direction, replacing scenes of “daily life” with motifs featuring deities (Robins 1997: 192, 200). Although the desert hunt was no longer a standard element, the gazelle continues to be depicted in these tombs as part of the offering theme (cf. Chapter 5), but not to same extent, or with the same variation, as during the Old and Middle Kingdoms. The focus on the pursuit of wild game continued in the New Kingdom scenes, with the composition giving an even greater impression of chaos. The deceased is generally seen outside the fenced off area, oversized and equipped with bow and arrows. One specific detail is worthy of mention: the fleeing gazelles are generally depicted two by two. 74 Many of these scenes are reminiscent of the later painted chest of Tutankhamun (cf. above 4.2.3/a.2), indicating there is a convergence of private and royal use of these motifs. a. Tomb of Montuherkhepeshef (Passage), TT 20, Dra' Abû el-Naga', 18 th dyn, Tuthmosis III (?), (East wall, PM I/1: 35 (7); Davies 1913: Pl. XII) The fragmentary desert hunt scene in the tomb of Montuherkhepeshef is found on the east wall in the passage. There are no marsh scenes or agricultural activities indicated by the remains. 73 Two exceptions: suckling gazelle in the tomb of Montuherkhepeshef and suckling fallow deer in the tomb of Puimre, see discussion below. No mating scenes preserved. A wild ass giving birth in the tomb of Montuherkhepeshef can be distinguished (Davies 1913: Pl. XII); the motif of nursing gazelle and foaling ass on the same tomb wall is probably intentional. 74 Cf. e.g. Amenipet, TT 276 (PM I/1: 353 (11), Wilkinson 1878: 92, Fig. 357); Rekhmire, TT 100 (PM I/1: 210 (11), Davies 1943: Pl. XLIII); Mentuiwiw, TT 172 (PM I/1: 280 (7), Decker and Herb 1994: Pl. CLXVIII); Userhat, TT 56 (PM I/1: 113 (13)- (15), Decker and Herb 1994: Pl. CLXIX ). 93 It can be concluded from the fragments that the scene originally consisted of at least four registers, flanked by fences. The tomb owner is seen hunting with bow and arrow, standing outside the enclosure and accompanied by assistants. These details correspond well to the earlier material. In the upper right section, a nursing gazelle, now fragmentary, has been added among the chaos of fleeing wild game (Davies 1913: Pl. XII). This represents one of the three New Kingdom examples of the nursing gazelle in a private tomb. 75 A wild ass gives birth. Although limited in number, it appears that the desert hunt in the New Kingdom can also include life affirming motifs (i.e. mating, foaling, and nursing). Remains of three fleeing gazelles, depicted with three superimposed profiles, can be distinguished in the lower register. b. Tomb of Amenipet (Inner room) TT 276, Qurnet Mura'i, 18 th dyn., Tuthmosis IV (North wall, (PM I/1: 353 (11); Wilkinson 1878: 92, Fig. 357) The desert hunt scene of Amenipet is located on the northern wall of the inner room. There are traces of a scene with the netting of fowl on the western wall of the hall (PM I/1: 353 (8)), but there are no reported marsh hunt or agricultural scenes. The deceased hunts desert game, shooting from a chariot. Again, the prey is within an enclosure. The fragmentary scene gives the impression of an intense chase, divided into three registers. There is a chaos of fleeing animals, running from left to right, with no sign of either mating or birthing motifs. This scene provides good examples of the pairing of fleeing gazelles. This combination is found in each of the registers, but in particular in the upper, with three pairs. One of these gazelles is running with its head turned back, facing left, confirming a continual use of the turned head as an attribute of the gazelle (also on the bottom row). The other animals include hyena, ibex, ostrich, oryx and hartebeest (Osborn 1998: 11). This depiction of two gazelles side by side can be traced back to the Sahure hunt scene. It is explicit in most of the New Kingdom private tombs, suggesting that there is an interest in presenting the gazelle in pairs (cf. Chapter 6 below). 75 Another example of a nursing wild animal is found in the tomb of Puimre (TT 39, PM I/1: 72 (10); Davies 1922: Pl. VII), where a fallow deer suckles its young. This motif is identical in its composition and context as that for the gazelle among the fleeing game. A second example of a nursing gazelle can be identified in tomb of Neferhotep (Ramesside), however, it is not a desert hunt scene (TT 216, PM I/1: 313 (6)). Cf. also the tunic of Tutankhamun, above 4.2.3/a.3 and Appendix III. 94 Figure 37. Gazelle nursing in desert. Montuherkepeshef (TT 20) Figure 38. Desert hunt, Amenipet (TT 276) 95 c. New Kingdom private tombs – concluding remarks Despite the individuality of the desert hunt scenes, the New Kingdom material does not offer any innovation in the gazelle motifs in a hunting context. With few exceptions, the narrative is focused on the hunt itself, with the life affirming motifs of mating, nursing and giving birth generally minimized or lacking. This is the same pattern found in the royal iconography. This trend is also seen in the Middle Kingdom material. The New Kingdom material displays continuity in motif that can be traced back to the Old Kingdom when the basic patterns are established. 4.3.4 Final examples of the desert hunt in private tombs There are two examples of desert hunt scenes dating to the Saite period (664-525 B.C.). One is found in the Theban tomb of Ibi and the other on a block from the Saqqara tomb of Nesu-su-djehuty. 76 The “revival” of the desert hunt scene as private tomb decoration is in line with the tendency of this period to copy earlier traditions (Schäfer 1974: 67-68), particularly those visible in nearby monuments. Figure 39. Ibi: desert hunt from Saite Period a. Tomb of Ibi (Court), TT 36, ‘Asâsîf, 26 th dyn., Psamtek I (East wall, PM I/1: 67 (20); Scheil 1894: 647, Fig. 8) The desert hunt scene from the tomb of Ibi is located on the east wall of the court. The marsh scene is not included in the tomb decoration. Agricultural scenes are however found next to the desert hunt register (PM I/1: 67 (20) II). This desert hunt scene is interesting as it appears to be a copy of an older 76 The block of Nesu-su-djehuty (also dated to Psamtek I) was found in the chapel (PM III/2: 669; currently in Egyptian Museum, no. 17.6.24.11). The original composition of the desert hunt scene is lost, however the remaining motifs include a pair of gazelles, a hedgehog and most likely a hunting dog (Quibell 1912: Pl. LXII,1). The motif of two gazelles continues to be used. Note that Quibell cites the block as 17.6.26.11, not found in PM III/2: 669 that refers to 17.6.24.11. 96 scene, displaying remarkable similarity to that of Ibi at Deir el- Gebrawi from the 6 th dynasty (cf. above 4.3.1/d.1). The kneeling bowman who aims in the direction of a lion attacking a gazelle and another gazelle fleeing from the hunting dog appear to have been inspired by the older tomb decoration located c. 200 km to the north. The name similarity may have encouraged this ambitious borrowing. This example does not contribute to a further understanding of the gazelle motif, but perhaps to a more general appreciation of the value of the desert scene. Disappearing rather abruptly sometime toward the end of the 18 th dynasty, its reappearance in the 26 th dynasty pairs it with an equally traditional agricultural scene. These two themes, the agriculture of the valley and the hunt of the desert have both contrasting and comparable elements. Regeneration and food production can be seen as a common thread. In the desert hunt scene this is represented by both life affirming motifs (mating, nursing, birth giving) and the fleeing and dying animals, all placed in the “chaos” of the desert (Ikram 1991: 57). 4.4 The desert hunt scenes – concluding remarks Examples of the desert hunt scene are found on the walls of royal temples and in private tombs during the Old, Middle and New Kingdoms. The gazelle motifs featured in the desert hunt scenes were well established and integrated into this narrative early on in the development of dynastic iconography. The forms given the different motifs are consistent and chronologically durable. This is also true of the depiction of other desert animals. A combination of these well- established motifs provides the core of the scene’s composition, with some variation available primarily in choice of motif. A study of the gazelle motif in this context reveals a pattern of use and provides the opportunity for a further understanding of its value. The Old Kingdom desert hunt scenes present the most variation in composition, a tendency that can be observed in both the royal and private material. The scene of the 5 th dynasty temple of Sahure has been treated as the model used for later compositions (e.g. Hoffmeier 1975: 8, Ikram 2003b: 143). Although the Sahure scene was fragmentary when documented by Borchardt (1913: Pl. 17), four different gazelle motifs can be discerned, all of which are continually repeated in the later material and some of which can be traced back to the Predynastic material as well. The oldest and most frequently used motif is that of a dog/lion attacking a fleeing gazelle, either grasping the gazelle’s hind leg or using its powerful jaws to choke the gazelle. The form given this motif in the 97 Predynastic Period, although not significantly altered in later examples, does occur in new combinations, such as in the triad of two opposing hunting dogs attacking a gazelle as a central figure (e.g. Ukhhotep, cf. above 4.3.2/b.2; Tutankhamun’s tunic, cf. above 4.2.3/a.3; Puimre, TT 39, Davies 1922: Pl. VII). It was, in many ways, the most succinct of the hunting images, representing the hunt in its quintessence, the successful hunter versus the defeated prey. With the gazelle by far the most common animal found in this composition, it could include other animals as well. The pose in which the gazelle looks back is frequently found with the fleeing gazelle, the striding gazelle and the recumbent gazelle in an insert. This particular position of the head is found in images from the Predynastic Period and onward. Suggesting vigilance and perhaps fear, this focus on the vision of the gazelle corresponds to its situation in the wild where that sense is its most important warning mechanism (Kingdon 1997: 409-410, Estes 1992: 66). Here too the gazelle is the most common animal to be depicted with this pose, but not the only one. Another feature typical for the gazelle in the desert hunt scenes is the grouping into pairs. The two-gazelle motif can be located in both the royal and private material. This composition is first found in the mortuary temple of Sahure (above 4.2.1/a), and occurs on a regular basis in the private tombs from the 5 th dynasty onward (cf. above 4.3.1/b.1, tomb of Raemka). It is found in a number of variations. Mating gazelles form one kind of pair, as do the mother nursing her fawn. 77 The pairing is sometimes implied by spacing, when ‘combining’ the motifs of an attacked gazelle and a young hiding in an insert. The Middle Kingdom desert hunt scenes contain few examples of the two-gazelle motif, while in the New Kingdom examples, the motif of pairs of fleeing gazelles is common (cf. 4.3.3/b, Amenipet), more or less excluding all the other variations. Another typical pairing entails combining the dorcas and Soemmerring’s gazelle, as shown in both the royal (above 4.2.1/a-c, Sahure, Niuserre and Unas) and private material (e.g. 4.3.1/c.2, Nimaatre or 4.3.2/d.1, Ip). The idea of the dual gazelles appears to be basic and reoccurs in other contexts as well (cf. 6.1.2, 6.2, 6.4 and 7.2 below). The gazelle was hunted by a variety of means. The bow and arrow is the primary weapon. It is originally seen on the Predynastic ceremonial palette (cf. 3.5). It is found in the Sahure desert hunt scene (cf. 4.2.1/a) and is used by the overlarge owner of the private tomb, with Senbi as an example 77 Cf. 3.5.1, the Hunters Palette where a mother and her fawn are fleeing. These, however, are shown as part of a group rather than as a pair. 98 (above 4.3.2/b.1, Montuherkepeshef, above 4.3.3/a) as well as by hunters integrated into the scene (especially observable in Beni Hassan, e.g. Baqt [III], Newberry 1894: Pl. IV). The successful shot is represented by the many arrows depicted piercing the wounded animals. For the gazelle, these arrows are most commonly found lodged in the neck (e.g. Sahure, above 4.2.1/a; Mentuhotep II, above 4.2.2/a), but also in the belly (e.g. Ukhhotep, above 4.3.2/b.2). The object of the hunt was not always to kill the animal during the chase. The lasso is not commonly used to capture the gazelle, there are however a few examples of its use (e.g. Seshemnefer, above 4.3.1/c.1 and Khety, above 4.3.2/a.2). The image of the enclosure, within which the animals were kept as easy targets, reoccurs. The young, hiding in bushes, represented in inserts (e.g. Sahure, above 4.2.1/a; Unas, above 4.2.1/c; Raemka, above 4.3.1/b.1; Seshemnefer, above 4.3.1/c.1), were also collected, as is indicated in the image of a gazelle in a basket (Niuserre, above 4.2.1/b; Niankhkhnum and Khnumhotep, above 4.3.1/b.4; Meryteti, above 4.3.1/b.5). The insert occurs primarily during the Old Kingdom and is used to represent a number of small animals, ranging from the hedgehog to hare to jerboas, as additional features of the desert landscape. The gazelle, always represented in a recumbent position, often with the head turned back, is by far the most common of the antelopes to be found in an insert where it sometimes can be found nibbling on a bush. The recumbent gazelle is a common motif also on objects (cf. 6.6.1, 6.6.2 and 6.6.3). The mating, birth giving and nursing motifs provide the life affirming element of the desert hunt, while also implying a continual replenishment of the animals killed in the hunt. The mating motif (cf. Ikram 1991), involving a gazelle pair, is represented by four examples (Seshemnefer, Junker 1953, Fig. 63; Nimaatre, Roth 1995: Pl. 95b; Ukhhotep, Blackman 1915a, Pl. VII; silver jar (CG 53262/JE 39867), Edgar 1925: Pl. I, Fig.1). Similarly there are a few surviving examples of depictions of foaling gazelles (Niuserre, von Bissing 1956: Pls XI-XII; Khnumhotep, Newberry 1893: Pl. XXX). The most important of the life affirming motifs is the nursing gazelle. The role of nursing mother is only found for the gazelle among the desert animals and can be traced throughout dynastic iconography. These life affirming motifs suggests that the image of the gazelle is integrated into the notion of regeneration, emphasized in the images of pairs, and of mother and young. The imagery of the gazelle is incorporated into different aspects of the desert hunt scene. It conveyed the defeat of the inhabitants of a landscape of chaos. This is explicit in the comparison between wild game and enemies 99 in the hunt/battle scene found on the painted chest of Tutankhamun (above 4.2.3/a.2). It also expressed the creative potential of that landscape with mating, giving birth and nursing its young. The funerary framework of these scenes transformed the collected, captured and slaughtered animal into an eternal source of food for the tomb owner. 100 5 The Gazelle as Offering The representation of offering is central to ancient Egyptian iconography and is found in varying forms on most objects relating to the funerary cult (Vandier 1964: 114). The items offered reconstituted the living existence of the deceased, with an emphasis on the meal as sustenance for the ka, the life force (Junker 1938: 98, Spencer 1982: 60, 63). There is a link between the desert hunt scenes and the offering scenes, both in terms of location and theme. In private tombs the desert hunt scene is often found together with an offering procession, suggesting that the two, desert hunt and offering, represent a narrative sequence. The desert game pursued in the hunt scenes by the tomb owner in his role of hunter is largely the same found as living animals in the procession of offering bearers. The gazelle, as one of these animals, facilitates the immortality of the tomb owner. Confirmation of the role of the gazelle as an offering gift is found in offering lists (5.2 below) and in the early compilation of offerings on the offering tables depicted on false doors and stelae (5.3 below). The images of the hunt, together with the offering procession, bring together the natural world and ritual (cf. Robins 1990: 48, Boessneck 1988: 8). The iconography of the tomb aligns the real world with the needs of the next (Ikram 1995: 42). 5.1 Offering scenes The procession of offerings is the standard form given offering scenes. The procession can be represented by a single figure or it can extend to multiple registers with numerous figures. Male and/or female offering bearers bring forth food items and other goods. The figures can represent the estates 78 supplying the offerings, otherwise the offering bearers are often unnamed but on occasion they can be identified as a member of the tomb owner’s family or as someone of clerical rank, traditionally the funerary priest known as the . 79 Live domesticated and wild animals can be found among the offerings, with the understanding that they will provide nourishment for the deceased’s ka. 78 For the role of the estates with references, see Moreno García 2008. 79 Cf. e.g. Tjetu/Kaninesut G 2001, where the brother participates (Simpson 1980: Pl. XXVIIb) and Neb-kau-her (Hassan 1975a: 49, Fig. 20) and Ankhmahor (Badawy 1978: Fig. 35) where funerary priests are found. 101 The gazelle is a common offering in the procession and can be found in the 4 th dynasty tombs at Meidum (Nefermaat, Petrie 1892: Pl XXVII) and Saqqara (Methen, LD II: Pl. 4) as well as in the Late Period tomb of Petosiris (Lefevbre 1924: Pls XX, XXXV, XLVI). There is no clear differentiation in the composition of these scenes, or in the gazelle motifs occurring in them, either geographically or chronologically. This suggests that the motifs were well established, with little interest in changing or developing them. One trend however is clear and that is towards less diversity in motif choice. This is the same pattern seen in the desert hunt scenes. Offering processions are by far more common in private tombs than in royal contexts (Klebs 1915: 119-121). The earliest known royal example is found in the temple of the 4 th dynasty king Sneferu (Fakhry 1961: Pls XIII-XV). Some of the reused Khufu blocks from Lisht (Goedicke 1971: 13-19) also show offerings from the estates. This puts a natural emphasis on the private material. The gazelle is found in an offering context in close to 100 different private tombs during the Old Kingdom alone. 80 In contrast to the hunt scenes, the tombs with offering scenes are evenly distributed between the two main Old Kingdom cemeteries of Giza and Saqqara, as well as being found in other contemporary cemetery sites. The offering scene is an important feature of the tomb and is found not only on tomb walls but also on stelae 81 and false doors (e.g. Iteti, PM III/1: 193 (1); Curto 1963: Pl. VII). The number of offering processions featuring a gazelle is far greater than the number of desert hunt scenes. The inclusion of desert animals in the offering procession may have functioned as an allusion the hunt. 82 In a smaller tomb, this would have saved space (Ikram 1991: 60). In contrast to the desert hunt scenes 83 or the marsh fowling scenes, the deceased is passive as the recipient of offerings. Analogous to the desert hunt scenes, the deceased is portrayed as oversized when receiving the gifts, signalling the status of the tomb owner. 80 This is the number of tombs in which the gazelle occurs, it can however be found several times in the offering rows of a single tomb. Given that many tombs are still unpublished, this number is of course, tentative. Cf. the list in Vandier 1969: 2-5. 81 Most of the stelae date to the FIP and the MK, e.g. Meru (N 3737), Dunham 1937: Pl. XIV and Amenemhat-Nebwia (Garstang 1901: Pl. VI). 82 Some interpretations of these scenes have drawn a sharp distinction between the “daily life” character of the hunt and the ritual aspect of the offering procession (e.g. Klebs 1915: 68, 119; Vandier 1964: 787, but cf. Altenmüller 1977: 231, Decker and Herb 1994: 265). 83 The deceased does not appear to have taken an active part in the desert hunt scenes of the Old Kingdom, in comparison to the Middle and New Kingdom examples where he is an ‘acteur’. The fowling scenes, on the other hand, featured the deceased and his family in the Old Kingdom examples. Cf. Vandier’s use of the terms ‘acteur’ and ‘spectateur’(1964: 58). 102 Three distinctive groups of animals can be noted in the offering scenes: birds, cattle (including bull, oxen, cow and calf) and wild game (Klebs 1915: 120). Although there is the implication that the animals will be killed, there are only a few scenes that show a gazelle about to be slaughtered (Sema-ankh, Hassan 1951: 168, Fig. 161; Sabu, Borchardt 1937: 229 (no. 1530), Pl. 46; Hesi, Kanawti and Abder-Raziq 1999: Pl. 58). It is the slaughter of cattle 84 (including the aurochs or “wild bull”) that is the most common. This most likely relates to the role of the -foreleg in funerary ritual (Ikram 1995: 43, Vandier 1964: 110, Otto 1950: 164-165). The question of whether the animals were collected as young and raised for later slaughter is brought up by the occurrence of a heading using the term or combined with the name of the animal, such as found as a description of a walking gazelle, in the mastaba of Nefer-seshem- ptah (Capart 1907: Pl. LXXX, also Idut, Macramallah 1935: Pl. XX and Ankhmahor, Badway 1978: Fig. 35, discussed below). The alphabetic spellings and seem to be used interchangeably, indicating that they represent the same word. One way to resolve this ambiguity is to see this as a genitive construction in which the second is the genitival adjective (Gardiner 1957: 66, §85B, also 77, §95), so that it can read + the genitive ! ". Otherwise, there are two distinct solutions to how ! " should be understood. In one case the translation “young one” (cf. Faulkner 1962: 150) has been chosen, so that the phrase ! " , would read “young one of the gazelle” (e.g. Simpson 1980: 3, Badawy 1978: 27, Moussa and Altenmüller 1977: 161) ignoring the related images of fat, and apparently adult, animals. If instead is read as the verb “to nurture, raise, bring up” (cf. Faulkner 1962: 150), the phrase can be read as “the nurtured one of the gazelle”. This has been interpreted to mean “fattening” (Boessneck 1988: 44) for slaughter. This reading does not however ‘fit’ the context of the small gazelle being brought forth in an offering procession. In the one example where the force feeding of gazelles is depicted, from the Old Kingdom (Djaty, LD II: Pl. 102b), the heading reads with the term understood as “to fatten” (Faulkner 1962: 70). From the same scene, the heading , “fattening the young of the oryx….” is found, indicating that if the meaning “fattening” had been intended, there was an alternative word to chose. Different authors have opted for one or the other translation without any further discussion (cf. discussion in Osborn 1998: 8). Although, not entirely satisfactory, ! " is translated as “fattened” here and treated as a description 84 The ancient Egyptians seem to have preferred ox meat (Ikram 1995: 44). 103 of the animal as suitable of offering, so that ! " is read as “fattened gazelle”. In the offering procession scenes, the gazelle is depicted using variations of specific motifs, some of which correspond to those found in the desert hunt scenes. This suggests a standardisation similar to that found in the motifs of the desert hunt. 5.1.1 A typology of gazelle images There are a vast number of examples of the gazelle in offering procession scenes. As the gazelle motif is the focus of this study, a typological approach has been chosen to provide an overview of the variation in presentation. A distinction has been made between two types of procession, that in which the estates are personified by female offering bearers and that where the offering bearers are primarily male, representing the immediate family and associates of the deceased. The tombs used as examples in this discussion are primarily from the cemeteries of Giza and Saqqara, dated to the Old Kingdom. This reflects the diversity of imagery during this period as well as the Old Kingdom origin of the motifs found in later tombs. A short description of comparative material from Middle and New Kingdom tombs highlights the stability of form for this type of scene. a. Bringing the gazelle from the estates One version of the offering procession consists of female offering bearers who are personifications of the estates. They carry baskets filled with a variety of food stuffs on their heads. The basket is held in place by one hand, while the other carries birds or calves and young gazelles, or holds a leash. They can also carry flowers. The name of the estate is found either in front of the woman or above her. The oldest known example of bringing offerings from the estates is from the 4 th dynasty temple of Snefru at Dahshur (van de Walle 1957: 290, Fakhry 1961: Pls XIII-XV, Harpur 1987: 82-83). The procession of the estates continues in its use as a tomb scene throughout the Old Kingdom, but is not found in later periods (Vandier 1964: 134-135). A majority of the estates represented in these scenes are linked to a funerary cult, with both royal and private estates being represented, and to the related economic institutions (Jacquet-Gordon 1962: 1). When found in private tombs, it has been suggested that this was yet another motif appropriated from the royal funerary temples of the Old Kingdom (van de 104 Walle 1957: 296, Vandier 1964: 129). 85 The presence of the so- called ‘défilés des domaines’ demonstrated the social rank of the deceased as well as affirming the wealth he would enjoy in the Netherworld (Jacquet-Gordon 1962: 14-15). a.1 Gazelle on leash Tomb of Seshemnefer [IV] (Outer hall), LG 53, Giza, late 5 th – early 6 th dyn. (East wall, Berlin 1128; PM III/1: 225 (15); Junker 1953: 197, Fig. 76) The procession of the estates fills two lower registers in the outer hall in the tomb of Seshemnefer. Among the 18 female offering bearers, seven have an animal on a leash; four calves, one oryx and one gazelle. Female offering bearers leading this series of animals on leashes is a standard feature in the procession of the estates. The animals are depicted striding in front of the offering bearer rather than being pulled. The leash itself could be depicted as either strained or loose. The animals are often drawn in smaller than correct proportions in relation to the women holding the leash. According to Harpur (1987: 83), this is “to make way for the estate names.” The offering bearer leading the gazelle in this scene carries a full basket on her head, secured by her left hand. The right hand grasps a bird by its wings as well as holding the leash, with the end looped. The gazelle strides in front of her, the leash is somewhat taut. This example is close but not identical to Posture 2 of Vandier’s (1964: 130, Fig. 39) analysis of the offerings from the estates. The motif of gazelle on leash continued to be used during the later periods as well, however not as a part of the procession of the estates but in the standard offering scene, even though the composition of male and female offering bearers is reminiscent of that of the estates (Vandier 1964: 135). 85 Compare with the contemporary private tombs in Meidum (PM IV: 90, 92), where the procession of the estates is included as an offering scene, without however the gazelle (e.g. Petrie 1892: Pls XI, XII, XV, XIX, XXI). 105 Gazelle on leash Figure 40. Tomb of Kemsit (Burial chamber), TT 308, Deir el-Bahari, 11 th dyn. (North wall, PM I/1: 386 (2); Naville and Hall 1913: Pl. II) In the tomb of Kemsit, a gazelle is held on a leash by a female offering bearer. She also holds a bird in the same hand. The other hand grasps what seems to be some kind of vegetable (?). Above this group the caption reads , “for your ka”. The composition is reminiscent of the Old Kingdom versions of bringing offerings from the estates. The gazelle is the only game animal to be offered. The tomb walls are otherwise dominated by the motif of cow and calf and other prepared food stuffs. A gazelle head can be discerned among the offerings on one of the offering tables as well. Tomb of Amenemhat (Inner room) TT 82, Sheikh Abd el-Gurna, 18 th dyn. (North-east wall, PMI/1: 166 (17); Davies and Gardiner 1915: Pl. XXII) Although not a formal procession of the estates, images parallel to those found in that context appear in the NK tomb of Amenemhet. A female offering bearer with a gazelle on a leash can be distinguished in the tomb of Amenemhat. The gazelle is portrayed in natural, rather than diminished, size. The offering row is fragmentary, making it difficult to discern details. Still, it is possible to note that the gazelle is the only game animal included among the offerings that otherwise consist of grapes, pomegranates and other fruits and food stuffs. The male and female offering bearers are shown mixed, in contrast to earlier periods when the division was rather distinct. A stylistic oddity is that the horns are in profile for one and frontal for another. The motif of gazelle on leash, presented by an offering bearer is most common during the Old Kingdom (estates), only to decrease in number during the Middle and New Kingdoms. 106 Gazelle on leash Figure 41. a.2 Gazelle on leash, nursing Tomb of Kagemni (Room IV), LS 10, Saqqara, 6 th dyn., Teti (South wall, PM III/2: 523 (19); von Bissing 1905: Pl. VII, 2) One of the more unusual examples of a gazelle in the procession of the estates is from the tomb of Kagemni. There are numerous examples of female offering bearers leading a gazelle on a leash in this tomb. One of the gazelles nurses a fawn (von Bissing 1905: Pl. VII, 2). The gazelle mother has her head turned back, facing left, a feature familiar from the desert hunt scenes where it is found with fleeing gazelles and recumbent gazelles in inserts. This is the only known example of a nursing gazelle combined with the procession of the estates, nor is there an example of any other nursing animal in this context. a.3 Gazelle carried Tomb of Akhethotep (Hall), D 64a, Saqqara, 5 th dyn., Isesi-Unas (East wall, PM III/2: 599 (5)-(6); Davies 1901: Pls XIII, XIV) There are several examples of the procession of the estates featuring female offering bearers in the tomb of Akhethotep. Several of these women carry gazelles. This is a pose common for the male offering bearers (cf. below 5.1.1/b.2) that are also found in this tomb (Davies 1901: Pls XVII, XXII). The woman carries the gazelle next to the chest with one arm under the belly of the animal. This posture is also found with the domesticated calf and some large birds (geese?). Similar depictions are found in the east hall 86 of this tomb on both left and right sides (PM III/2: 599 (5)-(6), Davies 1901: Pls XIII, XIV; cf. Harpur 1987: 83). 87 This appears to be the preferred gazelle motif in this tomb with numerous examples showing female and male offering bearers carrying a gazelle next to the chest (Davies 1901: Pls X, XVI, XVII), with the female examples outnumbering the male. 86 This part of the mastaba was called the “hall” in the PM publication, while Davies (1901: 9) labels it “chapel” 87 The second gazelle is more “embraced” than held, still belonging however to this type. 107 Carrying the gazelle Figure 42. a.4 Procession of the estates – concluding remarks There is little variation in the composition of the procession of estates (Vandier 1964: 131). Given the rigid form, the options for depicting the gazelle are restricted. The gazelle is either led on a leash or carried. The disproportionately small size of the animals on leash, as well as the ease with which they were held to the chest suggests that these are young animals. The example of a suckling gazelle on a leash in the tomb of Kagemni would further suggest that there is a deliberate allusion to reproduction. The procession of the estates displays a more limited variation in gazelle motifs than found in other offering processions. b. Procession of offering bearers The procession of offering bearers consists primarily of men who carry various goods as well as leading forth both domesticated and game animals. Brought separately one by one (Vandier 1969: 1), these animals take up considerable space in this composition. In contrast to the procession of the estates, the gazelles seen in the procession of offering bearers are commonly depicted as large and thus not suitable for being carried. The difference in the size of the animals may reflect a deliberate reference to the gender of the offering bearer (small – female, large – male). Junker (1938: 69, Fig. 7) referred to the animals being led forth by guiding or pulling the horns as stubborn creatures (“störrischen Tieren”), an interpretation that may extend to include the motif of both pulling by the horns and pushing forth from behind. A thorough examination of the variations of the offering procession was published by Vandier (1969: 1-58), where he defined such scenes as ‘les défiles’, referring to the array of animals. Further, he interpreted the animals found in these scenes as domesticated (“élévage des animaux” 1969: 6) and fattened before being slaughtered (cf. discussion above). b.1 Gazelle walking There are numerous variations in the gazelle motif in the processions of bringing offerings. Some of them are only found for the gazelle, others are more generally used. The most common shows the gazelle walking while being guided by the horns or both pulled and pushed by the offering bringers. Some examples include a tight leash. This variation often includes a small text reading , read here as “fattened gazelle” (Cf. e.g. Nefer-seshem-ptah, Capart 1907: Pl. LXXX; Idut, Macramallah 1935: Pl. XX; Ankhmahor, Badway 1978: Fig. 35, discussed below). In some examples, the gazelle is a part of the procession of 108 offerings, generally depicted as a row of striding animals, but without intervention or force. b.1_____ _____________________________ Tomb of Shetui ( ) (Chapel), Giza, end of 5 th – early 6 th dyn. (East wall, PM III/1: 106 (2); Junker 1950: 187, Fig. 86) A gazelle is pulled forth by a male offering bringer on the east wall in the tomb of Shetui. He holds the muzzle in one hand while the other grips the gazelle’s horns. The inscription above the gazelle reads . This motif is located in the middle register of an offering scene in front of a standing oversized tomb owner. The gazelle is a part of an offering procession where the oryx in front and the addax behind are being pulled (and pushed) in similar fashion. The upper row contains four oxen being led forth on leashes and the bottom register appears to have had representations of kneeling female offering bearers with goods from the estates. The animals, including the gazelle, are portrayed as rather large, reaching up to the chests and shoulders of the male offering bringers. This hardly reflects real life, as the average height of an adult gazelle was c. 60 cm (see Chapter 2 above and Kingdon 1997: 410). The other species may however be correctly drawn regarding the shoulder height (Kingdon 1997: 439 (oryx), 442 (addax)). Both the oryx and the gazelle are identified with a label, while the addax was further described as “fattened” ( ). Tomb of Khnumhotep [III] (Hall), BH 3, Beni Hassan, 12 th dyn. (South wall, PM IV: 147, (15)-(19); Newberry 1893: Pl. XXXV) In the Middle Kingdom tomb of Khnumhotep, a fattened gazelle is being guided forth by its horns by a male offering bringer. The inscription above this composition reads “fattened gazelle” another detail that can be traced back to the Old Kingdom version of this motif. However, it seems that such captions were primarily in use during the Old Kingdom, only to more or less disappear during the succeeding periods. The gazelle here is far from the oversized examples seen in the earlier period. This gazelle is seen in an 109 Figure 43. Guiding the gazelle offering row that mixes game with domesticate animals, rather than strictly dividing the two groups. The Middle Kingdom offering rows display a shift in the items brought forth as offerings. All of the live animals, wild and domesticated, continue to appear side by side, however, in addition to food stuffs, various objects and furniture, i.e. ‘manufactured objects’, become more common in the offering rows, as part of burial equipment necessarily for the deceased. This pattern can be observed in several of the other Middle Kingdom necropli, such as el-Bersheh, Meir and Thebes. This trend is found in the New Kingdom examples of this scene as well. Tomb of User (Passage), TT 21, Sheikh Abd el-Gurna, 18 th dyn. (North wall, PM I/1: 36 (10); Davies 1913: Pl. XXII) The offering rows continued to be an important part of tomb decoration during the New Kingdom. As the majority of the private tombs from the New Kingdom are found in the Theban necropolis, the composition tends to be uniform. The items featured in the offering rows go from the ‘simple’ food stuffs represented by live animals to prepared food as well as various manufactured objects, such as furniture. The presentation of game animals is primarily located immediately next to the desert hunt (Davies 1913: 23 “trophies of the chase”). In these sections the mixture of wild game and domesticate animals do not occur. In the separate offering scene, the gazelle con-tinues to be found, although less frequently. In the tomb of User, the so-called return from the hunt includes an ibex, three gazelles, a hyena, multiple hares, an ostrich and an oryx. One of the gazelles is being guided forth by its horns. The male offering bringer holds a loose leash tied to a hind leg of the gazelle. The two other gazelles are carried on the 110 Guiding the gazelle Figure 45. Guiding the gazelle Figure 44. shoulders of offering bearers. The scene does not have headings. The animals found in the offering procession correspond to the standard game of the desert hunt scene, which unfortunately is quite damaged in this tomb. The gazelle is also represented by a head depicted on the offering table in the shrine (Davies 1913: Pls XXVI, XXVII). b.__________________________ Mastaba of Sekhemka, (Chapel), G 1029, Giza, end of 5 th – early 6 th dyn. (East wall, PM III/1: 53 (1)-(2); Simpson 1980: Fig. 4) Another characteristic example of bringing forth the gazelle is found on the east wall of the chapel of G 1029, belonging to Sekhemka. The gazelle is both pulled by the horns and pushed from behind by male offering bringers. This wall is divided into five registers, containing activities primarily associated with daily life. On the fourth register from the top, the bringing of wild game included from right to left: an oryx, ibex, addax and finally a gazelle. Each of these amimals are identified by the inscription “fattened” ( ) followed by the name of the species. Two of the male offering bringers accompany the gazelle as it is presented to the oversized deceased. The gazelle is slightly smaller and more slender than the other three animals in the same register, yet oversized in relation to the men bringing it. Once again indicating that it is unlikely that should be read as young, rather than fattened (cf. discussion above, 5.1). Tomb of Ukhhotep (Hall), C 1, Meir, 12 th dyn. (North wall, PM IV: 253; Blackman and Apted 1953: Pl. XV) Ukhhotep 88 has one of the smallest tombs in the cemetery of Meir. The tomb contains both a fishing and a fowling scene, but no desert hunt scene. The gazelle appears however a few times in the registers of offerings. One of the 88 Not the same Ukhhotep as discussed in 4.3.2/b.2, who is the son of Senbi and has tomb B 2. 111 Pulling and pushing the gazelle Figure 46. Figure 47. Guiding the gazelle gazelles is brought forth by an offering bringer, and even though the scene breaks off at the neck of the gazelle, it can be deduced that the gazelle was being held at the neck and pushed from behind by the same offering bearer (cf. discussion of Rekhmire below). The gazelle is preceded by two offering bearers, identified as lector- priests. Each of them holds a large foreleg, placing the gazelle in the same category of offerings. Tomb of Rekhmire (Hall), TT 100, Sheikh Abd el-Gurna, 18 th dyn. (North wall, PMI/1: 210 (10); Davies 1943: Pl. XLV) The tomb of Rekhmire features a desert hunt scene as well as a register with the bringing of wild animals located next to it. The animals are the same as those hunted, which include among others, hartebeest, oryx, and hyena. The gazelle is shown pushed forward by the horns and by the hind quarters by a male offering bearer (as are the oryx and hartebeest). In contrast to the Old Kingdom versions of this motif, it seems that this composition did not require two offering bringers to attend to the gazelle. This may relate to the animals being portrayed in a more realistic size than those that had been stall fed. This register appears among the presentations of other products, and connects the desert hunt and the offering. b.________________________________ __ Tomb of Ankhmahor (Doorway), Saqqara, early 6 th dyn. (North wall, PM III/2: 513 (10 b); Capart 1907: Pl. XLIV, cf. Badawy 1978: Fig. 35) The “pulled and pushed” motif is augmented in the tomb of Ankhmahor with the nursing element. In the upper of two registers an oryx and a nursing gazelle are brought forth. Above the scene the text reads ! " , ‘bringing the desert game that is brought for him by the - servant(s)’. 89 The oryx to the left is guided by two male offering bringers, holding the horns and muzzle of the animal. The description of this scene reads, “fattened oryx” ( ) and then “seizing a large (one) for you” 89 Badawy (1978: 27) confuses the two crooks (Gardiner sign list S38, S39) transliterating # instead of while still translating “desert animals”. 112 ( ). 90 The nursing gazelle is found at the far right of the scene. This is the only known example of a nurturing gazelle in this context. Here two men try to control the gazelle, while she suckles her fawn. The man to the left holds the muzzle and horns, while the other pushes from behind. The inscription above reads “fattened gazelle, holding it (her) tightly for stability” ( ). 91 In this instance, as with the desert hunt, the role of nursing mother is reserved for the gazelle. Figure 48. Guiding a nursing gazelle b.1.__Striding ‘independently’ Tomb of Seshemnefer [IV] (Architrave) LG 53, Giza, end of 5 th – early 6 th dyn. (PM III/1: 225 (19), Junker 1953: 205, Fig. 79) The offering procession in the tomb of Seshemnefer includes the gazelle striding without assistance. This scene is divided into three short registers, with an aurochs on the upper register, a cow in the middle and the gazelle in the lower register. This scene is found on the western side of the architrave and a similar scene is located on the eastern side with the gazelle replaced by an addax and ibex. This manner of ‘bringing’ the gazelle is relatively 90 But cf.Badawy (1978: 27): “… , young oryx, … pull strongly to thee”. 91 But cf. Badawy (1978: 27): “ , young gazelle, … , Hold him properly”. Note that even though the label over the gazelle mother lacks the feminine ending , referring to a nursing animal as “him” ( ) is misleading. 113 common, with the ‘independent animal’ often shown as last in the line of animals. Even though the caption above the gazelle simply reads , it can be concluded that it was a part of a fattened group of animals based on size and context. Figure 49. Gazelle striding independently Tomb of Khety (Hall), BH 17, Beni Hassan, 11 th dyn. (North wall, PM IV: 156 (7); Newberry 1894: Pl. XIV) In a scene that is not a clear cut offering scene (as it is not directed explicitly towards the tomb owner), but still depicts the bringing of goods, a number of Figure 50. ‘Herding’ the gazelles gazelles striding forth independently can be noted. The group includes four adult gazelles and two young. At the far left of this register there is a man with a short stick, as if guiding a ‘herd’ of gazelles. A similar arrangement is repeated in the three registers below, which included oryxes, geese and cranes. Tomb of Ineni (Doorway), TT 81, Sheikh Abd el-Gurna, 18 th dyn. (North wall, PM I/1: 163 (19); Dziobek 1992: Pl. 29) It can be concluded that, despite the fragmentary condition of the tomb wall paintings, the tomb of Ineni once contained a desert hunt scene, however no image of a gazelle has been preserved. The gazelle does appear in the offering context, where it is seen striding independently in front of a male offering bearer, who is holding a ‘tray’ laden with traditional bread and vegetable offerings. It may be noted that on the opposite side of the doorway (south wall), the scene is almost identical, except for the gazelle, that has been replaced by a calf. This calf, on the other hand, is on a leash, wrapped 114 tightly around its muzzle, the offering bringer carries a short stick in his other hand. The contrast between the wild animal striding independently and the domesticated calf held on a tight leash is striking. Furthermore, the equation of the gazelle and calf echoes Old Kingdom offering scenes where this is a common feature. _______Striding ‘independently’, nursing Mastaba of Rawer [II] (Chapel), G 5470, Giza, late 5 th dyn. (East wall, PM III/1: 162 (1); Junker 1938: 233, Fig. 48) The motif of the independently striding gazelle is augmented with that of nursing in the mastaba of Rawer, where the text found with the offering procession refers to bringing the animals from the funerary estate ( ). The procession originally extended over five registers. The deceased stood to the right of these. In the third register, from right to left, are two oryxes ( ), followed by an ibex ( $ % ), ending with the motif of a gazelle suckling her young. The mother has her head turned back, keeping an eye on the fawn (cf. Kadua, discussed above) The two oryxes are accompanied, while the ibex and the gazelle are not. All four animals are said to be “fattened” ( ). The realistic representation of the individual animals is expanded to refer to a more general concept of offering, as the entire phrase reads [ ], “a thousand fattened gazelles”. The other animals are similarly characterized as “a thousand fattened ...”. This appears to be a reference to the common description of funerary offerings as consisting of ( ) a “thousand bread and beer ...” (cf. e.g. Junker 1934: 69, 75; Franke 2003: 49). Once again in this otherwise uniform representation of the common combination of desert game, the gazelle stands out as the animal that nurses its young. Tomb of Kadua (Offering room), Giza, 5 th dyn., Niuserre or later (South wall, PM III/1: 245; Hassan 1951: 103, Fig. 82) The striding, nursing gazelle is also found in the tomb of Kadua. Here the motif of a nursing gazelle is the second and final image in an offering row, 115 Figure 51. Nursing the fawn preceded by the motif of an ibex brought forth by a male offering bringer, gripping the horns and muzzle of the ibex. The mother and fawn are alone, without any offering bringer guiding them forward. Above the ibex is the standard phrase “fattened ibex” ( ), and that above the gazelle reads “fattened gazelle” ( $ % ) confirming that the gazelle is also an offering animal. In the two upper registers, as well as the lower one, there is another scene where male offering bearers guide the wild game forward. The gazelle mother has her head turned back, as if to check upon her young. One of the gazelle mother’s hind leg is upraised (cf. Ptahhotep, 4.3.1/b.3), scratching the ear or the muzzle; this motif correlates to numerous images of the suckling cow (e.g. Roth 1995: Pl. 156, cf. also Keel 1980: Figs 12, 26; Simpson 1980: Fig. 30). The apparent analogy drawn between the nursing gazelle and cow indicates that the two are associated. Examples of nursing gazelles in offering scenes in the tombs of Nebemakhet (Keel 1980: 73, Fig. 32) and Kapi (Roth 1995: Pl. 59b, frontispiece) further confirm that among the many animals, only the gazelle is represented nursing in the offering scenes. An additional observation that may relate to specific artistic traditions is that the nursing gazelle in an offering context is primarily found in tombs at Giza, 92 while the nursing gazelle in a desert hunt scene context is a feature of the tombs of Saqqara. 93 The incorporation of the gazelle mother-child constellation of the nursing scenes into an offering context has the effect of putting an emphasis on the generative aspect of the funerary meal, both in terms of an implicit reference to a “meal – nursing” correlation and in that the deceased will receive both mother and child as part of that meal. b.2 Carrying the gazelle Analysing the different poses in presenting offering goods, Vandier (1964: 117- 125, Figs 33-36) has no less than 123 different categories of “Attitudes des porteurs d’offrandes”. Three of these involve carrying a gazelle (Vandier 1964: 119-121, Figs 34, 35, Postures 49, 85, 93). The majority of the examples of this pose have the offering bearer carry a gazelle either on the 92 Cf. e.g. the tombs of Rawer (Junker 1938: 233, Fig. 48), Kadua (Hassan 1951: Fig. 82), Kapi (Roth 1995: Pl. 59 b) and Nebemakhet (Keel 1980: 32). There are two examples of nursing gazelles in offering context in Saqqara tombs: Ankhmahor (Badawy 1978: Fig 35) and Kagemni (von Bissing 1905: Pl. VII). 93 Cf. e.g. tombs of Ptahhotep (Davies 1900: Pl. XXI), Pehenuka (Harpur 1987: 530, Fig. 188), Niankhkhnum and Khnumhotep (Moussa and Altenmüller 1977: Pl. 38), a block from shaft no. 6 (Hassan 1975b, Pl. XIVc) and the causeway of Unas (Labrousse and Moussa 2002: Fig. 55). 116 shoulders or next to the chest. In addition to the gazelle, the domesticated calf and large birds are commonly carried in the processions of offering bearers. The context, frequency and manner of carrying the calf and the gazelle indicate that the two were treated as analogous. Also included in this category is the motif in which an animal is carried in baskets on a pole or yoke, with the gazelle being the most frequently portrayed animal in this context. ___________ ____________le on shoulders Tomb of Seshat-hotep (Chapel), G 5150, Giza, early 5 th dyn. (West wall, PM III/1: 150, (5) and (7); Junker 1934: 182, Fig. 28) A good example of the gazelle carried on the shoulders of a male offering bearer is found in the mastaba of Seshat-hotep. The bearer has one hand holding the legs and the other grasping the neck of the animal (cf. Vandier 1964: Fig. 35, Posture 92). The other desert game animals, oryx, ibex and on the lower register ox and addax, are brought forward with the guidance of male offering bringers and are depicted considerably larger than the carried gazelle. Figure 52. Seshat-hotep: Figure 53. Seshemnefer: Carrying the gazelle Carrying the gazelle Tomb of Seshemnefer [III] (Offering room), G 5170, Giza, 5 th dyn, Isesi (East wall, PM III/1: 154 (1); Junker 1938: 73, Fig. 8b) One of the most common variants of carrying a gazelle on shoulders can be observed in the offering procession of Seshemnefer. In that representation the animal lies across the shoulders of the male offering bearer, the legs in front, next to his chest. Both hind legs and one of the fore legs are restrained by one 117 hand; the other arm is around the animal’s neck, holding a foreleg. This motif is further elaborated with additional offering goods in the arms or hands of the offering bearer (cf. Vandier 1964: Fig. 35, Posture 93) Tomb of Ukhhotep, (“Room B”), C 1, Meir, 12 th dyn. (North wall, PMIV: 253; Blackman and Apted 1953: Pl. XVIII) In one of the offering rows in the tomb of Ukhhotep a female offering bearer carries a gazelle on her shoulders. One arm is around the neck of the gazelle, and her other hand grasps the feet of the animal. This posture is fairly common during the Old Kingdom, however, female offering bearers are not found in this position, making this a rare example. The gazelle appears to be the only animal carried in such manner in this tomb, repeating a pattern observable during the Old Kingdom. Figure 54. Female offering bearer carries a gazelle Tomb of Menna (Hall), TT 69, Sheikh Abd el-Gurna, 18 th dyn. (East wall, PMI/1: 137 (5); Mekhitarian 1978: 87) A male offering bearer carries the gazelle on his shoulders, one hand grasping the neck and the other tightly holding the feet of the animal. This composition is one of the most common postures in this context during the New Kingdom and is seemingly reserved for male offering bearers. There is a limited variation within this category and is in no way comparable to the diversity in detail displayed during the Old Kingdom. b.2________ _________________"_____#_____ Tomb of Nesutnefer, (Chapel), G 4970, Giza, early – middle 5 th dyn. (East wall, PM III/1: 143 (2)-(3); Junker 1938: Fig. 28) Another way of carrying a gazelle is next to the chest, in the arms. This composition is also varied in many different ways. Two main variations may be distinguished, either hands holding on to the legs of the gazelle or hands/arms located under the belly. The manner in which the gazelle is carried next to the chest is also found with large birds (cf. Vandier 1964: Fig. 35, Postures 83 and 84) and occasionally other young wild game (Vandier 1964: Figs 35, 86). The domesticated calf appears frequently in the arms of male offering bearers as well. 118 In the bottom register of the east wall, the offering row contains various food items such as bread, beer, fowl and red meat, all brought to the oversized Nesutnefer and his wife. The two last offering bearers to the far left carry a calf and a gazelle, albeit in slightly different ways. The gazelle is held next to the chest, restrained by the forelegs, with the neck of the animal in a firm grip. Even though the posture differs slightly from that of carrying the calf, which was carried next to chest, hands under the belly, the two are analogous. This example is used in Figure 55. Vandier’s analysis (1964: 119, Fig. 34, Carrying next to chest Posture 49; cf. 120, n. 2) and is parallel to the way birds are carried (where the beak was restrained rather than the neck, cf. Vandier 1964: 119, Fig. 34, Posture 50). This posture is an uncommon way to carry a gazelle during the Middle and New Kingdoms. This is reflected in the Vandier’s (1964: 113-126), documentation of different postures of primarily Old Kingdom date. b.2. _ Carrying the gazelle next to chest, holding legs Mastaba of Kaninesut [I] (Offering room), G 2155, Giza, early 5 th dyn. (West wall, Vienna ÄS 8006, PM III/1: 79 (7); Junker 1934: Fig. 18) Three registers with offerings presented to the oversized Kaninesut and his wife are found between two false doors on the west wall. The lower register depicts 10 men bringing various offerings, including forelegs ( ), birds and other meat offerings. The sixth man from the right carries a gazelle, holding it next to his chest; one of his hands clasps all four legs and the other hand is on the side of the belly, securing the grip (Vandier 1964: Fig. 35, Posture 85; cf. 123, n. 2). The gazelle is the only four-legged animal in this Figure 56. Carrying, register, with the ox implicitly represented by the holding legs two -forelegs. 119 Tomb of Amenemhat (Hall), BH 2, Beni Hassan, 12 th dyn. (North wall, PMIV: 142 (7)-(11); Newberry 1893: Pl. XIII) Figure 57. Holding legs In a fairly long offering row, where a variety of prepared food stuffs, poultry and an ox are being presented to the tomb owner, a male offering bearer carries a gazelle next to his chest, holding its legs. Again the gazelle represents the only game animal to be offered, even though a desert hunt scene appears two rows above, including multiple desert species. The combination of ox, poultry and gazelle as live animals is an echo of the earlier period. This position is not common during the Middle Kingdom. From an unknown Theban tomb, 18 th dyn. (BM 37980, Wreszinski 1923: Pl. 32) A fragmentary block now in the British Museum displays a painted offering procession with four male offering bearers preserved. Two of the men are offering vegetable and flowers, another man brings two hares and the fourth man is carrying a gazelle next to his chest, holding its legs. Considering that the other offering goods are vegetables and flowers, the scene should be understood as part of an offering scene rather than a so- called return from hunt. This posture is most common during the Old Kingdom, with few corresponding examples from later periods. b.3 Carrying the gazelle in a basket on a pole A variation of carrying the gazelle as offering involves baskets on a pole. The yoke, from which the baskets hang, is, as a rule, carried by male offering bearers, with exceptions however being found (cf. tomb of Nehwet-desher, Kanawati 1988: Fig. 3). The gazelle is not the only animals carried in a basket; birds, hares and hedgehogs are also among those found. The majority of the examples of the basket motif are from an offering scene context, while two examples of this motif can be distinguished in a desert hunt context (cf. above 4.2.1/b and 4.3.1/b.5), where it is associated with the collection of small animals. Numerous examples of the baskets motif are included in the analysis of Vandier (1964: Fig. 33, Postures 14 and 25; Fig. 35, Postures 65-68). 120 __$________ ____________ _____%___ Tomb of Idut (“Room III”), Saqqara, 6 th dyn. (South wall, PM III/2: 618 (13); Macramallah 1935: Pl. X) Examples of gazelles in baskets can be found at least three times in the tomb of the princess Idut (Macramallah 1935: Pls X, XX). They are all similar in composition. A basket or box hangs from the pole with the head of a gazelle protruding from either side, forming a ‘pair’. This was the most common variant of the motif of two gazelles in a basket 94 (cf. Vandier 1964: Fig. 33, Posture 25). There are examples of young gazelles in a basket where there are more than two animals (Nebemakhet, Keel 1980: 73, Fig. 32; Niankhkhnum and Khnumhotep, Moussa and Altenmüller 1977: Pl. 34), possibly referring to a general concept of abundance. Even though the gazelles in baskets are shown with horns, their size and willingness to sit still indicate that it is a question of young animals (Osborn 1998: 177). The recumbent pose found here suggests a carry over from the standard depiction of the young animal in hiding, common in inserts (cf. above 4.1.4). The motif of gazelle in basket occurs mainly during the Old Kingdom, with only one example known that is dated to the Middle Kingdom (Ukhhotep, Blackman 1915a: Pl. VIII, cf. below). In the Middle Kingdom example, the gazelle is both recumbent and has its head turned back, yet another feature corresponding to the gazelle inserts. Two motifs are shared by the offering and hunt scenes: the nursing gazelle and the gazelle in the basket. These two motifs, both involving a young gazelle, appear to be associated. In approximately half of the examples of offering scenes where the nursing motif is found, the basket motif also occurs. Most of the scenes where this motif is found are located in Saqqara. 95 94 Cf. e.g. Ptahhotep (Davies 1900: Pl. XXII), Hetepherakthi (Mohr 1943: Fig. 9) and Ti (Wild 1966: Pl. CLXV). 95 The motif of baskets on pole (Old Kingdom) is found in the Saqqara tombs of Ptahhotep (Davies 1900: Pl. XXII), Khnumhotep and Niankhkhnum (Moussa and Altenmüller 1977: Pl. 34), Meryteti (Decker and Herb 1994: Pl. CXL), Idut (Macramallah 1935: Pl. X), Hetepherakhti (Mohr 1943: 41, Fig. 9). In Giza, in the tomb of Nebemakhet (Keel 1980: 73, Fig 32). The Niuserre block originated from Abu Ghurob (von Bissing 1956: Pl. XI a). 121 Figure 58. Gazelles in basket Tomb of Ukhhotep (Hall), B 2, Meir, 12 th dyn. (West wall, PM IV: 251, (12); Blackman 1915a: Pl. XI) The single Middle Kingdom example of the motif of male offering bearers carrying gazelles in baskets is located in the tomb of Ukhhotep at Meir. This section of the tomb was partially unfinished with the grid lines still visible. The picture is still exceptionally detailed and differs from the examples from the Old Kingdom. The baskets are bowl shaped, instead of the box-like or oval forms of the earlier period. A single gazelle lies in either basket, in a recumbent position, with the head turned back. This position is the same as that seen in the so-called inserts from the desert hunt scenes, which would confirm the interpretation of collecting young animals in the desert. This composition reiterates the idea of a pair of gazelles, albeit in a different form. c. A Late Period version of the offering procession Tomb of Petosiris (Pronaos), Tuna (Hermopolis Magna), c. 350 B.C. (East wall, PM IV: 172 (81)-(82); Lefebvre 1924: Pls XXXV, XXXVI) The tomb of Petosiris is one of the last tombs decorated with traditional ancient Egyptian motifs. There is no desert hunt scene but a long register shows offering bearers with a mixture of wild and domesticated animals, including the gazelle. Even though there are some non-Egyptian elements in the style of these reliefs, the motifs have their origin in traditional Egyptian compositions. The gazelle is presented in three ways, all of which can be traced back to the Old Kingdom. The gazelle is shown on a leash (cf. 5.1.1/a.1 above), striding independently (cf. 5.1.1/b.1 d above) and carried on shoulders (cf. 5.1.1/b.2.a above). The gazelle is not the only animal represented like this; most of the other species were portrayed with the same variation (Soemmerring’s gazelle, ibex, oryx, fallow deer, calf, and goat). Children are also carried on shoulders, providing an interesting commentary to the animals found in a similar position, suggesting a reference to ‘age’. 122 Figure 59. Carrying two gazelles in baskets. Those carrying the gazelle on the shoulders are male offering bearers, while the gazelle on a leash is led by both a man and a woman. The striding animals are found next to the male offering bringer. The scenes from the tomb of Petosiris indicate that the gazelle continued to be regarded as an important part of the offering scene, with its representation faithfully adapted from earlier versions. 5.1.2 Offering scene motifs - concluding remarks A number of variations are found in the depiction of the gazelle in offering scenes. The gazelle is found walking on a leash (a.1), when led by the female personifications of the estate or being pushed and pulled by the men of the offering procession (b.___-_•__ ‰___ __________#___ ____<_ ‹<______Œ___ „____ #___< ______________@__% ___‹ __________Œ_Z_____-_•__ The gazelle can also be carried, in the arms of a female offering _______Z__$•______„_____<<__ __________Z____- _•_____#___________________<___ ma____<<__ __________Z_____•__‘__#___________#___ __ _______<<__ ______#___ ___ in a basket hanging from a yoke, either alone or with one or more of the gazelles (b.3). Like the other desert animals found in the offering scenes, the gazelle is described as “fattened” ( ). This relates to the idea of the hunt as involving the capture as well as the killing of these animals. The element of nursing is added to some of these poses, giving a nursing gazelle on a leash in the procession of the estate (a.3), and in the offering processions either while being pulled along (b____•____@____@__% ___ ___________Z_____•___^___ ____ __# _#_„____#______________#________#_ ___ as “fattened”. The gazelle occurs as both an adult and as a young animal. Size is not only used as an attribute to indicate the age of the animals. The disproportionately small gazelles in the procession of the estate might, being on leashes, be interpreted as young animals. One variant of this motif however includes nursing, making it clear that at least in this instance the gazelle, in spite of its size, is an adult. Other considerations, such as various aspects of the aesthetics of the scene, appear to have determined how large or small the gazelle is depicted. Contextually however there are indications that some of the animals depicted are young. A parallelism with the calf found in the pose with the gazelle across shoulders would indicate a young animal, as would the motif of gazelle in the basket, associated as it is with the collection of young animals in the desert hunt scene. The composition of the nursing motif in the offering scenes also displays similarities with that featuring the cow and calf. It is, however, only 123 the gazelle among the desert game animals that is shown suckling her fawn. This restriction of the nursing motif to the gazelle is also true of the desert hunt, indicating continuity in motif between the two types of scenes. The ease with which the nursing variation is added to the various motifs also suggests that it is primarily, if not exclusively, the female gazelle that is depicted. 5.2 Offering lists The desert hunt and offering scenes, it could be argued, are elaborate versions of the offering list, describing the procurement and presentation of the offerings, as opposed to a simple listing. The offering list in contrast is a straight forward account of those offerings. Its composition is simple, consisting of a list of the gifts that the deceased is to receive, often placed in relationship to the image of the recipient before an offering table. Appearing on temple as well as tomb walls, the list also ensured similar benefits for the gods (Barta 1963: 1). The offering list 96 can be understood as a “Speiselist” (e.g. Junker 1934: 69), with references to various food stuffs and drink. It also, however, can include cosmetic oils, incense, cloth and eye paint, as well as other more specialized items, representing typical grave gifts (Hassan 1948: 76), making it a list of both necessities and luxuries. The earliest hieroglyphic list traces back to the 2 nd dynasty (Hassan 1948: 45, el-Metwally 1992: 5). Being found primarily on the tomb wall during the Old Kingdom, the offering list is one of the most fundamental images in the ancient Egyptian tomb iconography (Junker 1934: 70). The private offering lists of the Middle Kingdom appear mainly on the coffins, with examples located on tomb walls being few. An abbreviated version of the offering list seems to have been transferred to tomb stelae instead (Barta 1963: 98-99). As for the New Kingdom, the offering list seems to have been replaced by depictions of various offering rituals (Barta 1963: 105-106). In short, the offering list was used extensively during the Old Kingdom, while during the succeeding periods the inclusion of the list became less common, with its form changing as well. The royal offering lists formed a category of their own, where the gazelle only is found exceptionally, such as in the offering list of Seti I at Abydos (cf. Barta 1963: 130-134). 97 96 Junker (1934: 69) differentiated between an offering list and an offering formula. 97 For the ancient Egyptian offering lists, cf. Hassan 1948, Barta 1963 and 1968, and el-Metwally 1992. 124 5.2.1 The gazelle in the offering lists The gazelle is found to a much lesser degree in the offering lists than in the offering scenes. The offering lists classify each item according to type, with the most relevant category in this instance being food (cf. e.g. Barta 1963: 47-50). The gazelle appears for obvious reasons as “meat”. When the gazelle is included in the list, it is generally found listed between the more common oxen (‘cattle’, or ) and poultry ( ) (Barta 1963: 60). This represents a hierarchy similar to that found in the offering scenes. The oryx is more frequently found in the lists and appears to have been chosen to represent desert game (Hassan 1948: 58 98 , Pl. IV). Where there is a reference to the gazelle, it is specific, with the spelling followed by a gazelle head as a determinative. Occasionally only the head occurs (Hassan 1948: Pls V, VI, CXIII, CLXV). In these cases identification is dependent upon the characteristic curve of the horns of the gazelle (e.g. Junker 1934: 128, Fig. 11). The horns differentiate the different desert animals and the combination of animals relates directly to those found in the desert hunt and offering scenes. The majority of the meat offerings in the lists are not specified by species but rather by cut, (e.g. , , , , cf. Ikram 1995: 113-144), with no indication of which animals the meat came from. The occasional reference to the gazelle in these lists, does however confirm its status as an offering and a source of meat. Tomb of Seshat-hotep (Chapel), G 5150, Giza, early 5 th dyn. (South wall, PM III/I: 150 (4); Junker 1934: 187, Fig. 33) An offering list that has the full spelling of the word gazelle with the head as determinative is found in that of Seshat-hotep. The tomb wall has a list on the upper half, while the lower section depicts an offering table with loaves of bread and a slaughtering scene. The deceased is seated next to the table, receiving offerings brought to him. The gazelle is the next to last in a row of the Figure 60. in offering list listed animals. It is followed by a hyena ( ), an animal that is unusual in this context, but one that underlines the category “desert animal”. An almost 98 Note that the animal that Hassan (1948: 58, ) identifies as an ibex is in fact an oryx. A further mistake is made when in another example the oryx is called “gazelle” (Hassan 1948: 68). 125 identical scene appears in the tomb of Nesut-nefer, where the gazelle is also included (G 4970, PM III/1: 144 (4); Junker 1938: 75, Fig. 9b). Tomb of Kapunesut (Chapel), G 4651, Giza, early – middle 5 th dyn. (South wall, PM III/1: 135 (2); Junker 1938: 135, Fig. 17) A gazelle head without an alphabetic spelling, but where a determinative is preceded by “fattened” is found in the offering list in the mastaba of Kapunesut. It is found in the lower row, fourth from right, preceded by ox, oryx and ibex. The offering list formed the upper part of the scene, with the deceased seated in front of an offering table with loaves of bread found below. Offering bearers are seen on the opposite tomb wall, including one carrying a gazelle (Junker 1938: 139, Fig. 18). Offering lists tend to be located on one wall (south) while on the opposite wall (north) the bringing of animals forms an additional commentary to the offering theme. 5.3 The gazelle on the offering table in scenes and as object The offering table, piled with gifts before the recipient, is an earlier form of the offering list. The gazelle head, found as a determinative in the spelling of , is found, if rarely, in some examples, among the offerings on the offering table. The primary offering found on the table is that of bread, in different shapes (cf. Vandier 1964: Fig. 26, Bárta 1995: Fig. 4), although food items are also often found (Robins 1998: 957-961). The number of offering table scenes decreases rapidly during the Middle Kingdom, increasing again during New Kingdom. The examples from Middle and New Kingdom are often lavishly decorated with bread, meat, vegetables and flowers. Tables laden with a diversity of offering goods are most common during the New Kingdom. 5.3.1 Tomb of Ukhhotep, B 2, Meir, 12 th dyn. (South wall, PM IV: 250 (4-5); Blackman 1915a: Pl. VI) A good example of a scene depicting an offering table featuring the head of a gazelle is found in the Middle Kingdom tomb of Ukhhotep. The offering table not only has the head of the gazelle but also that of an oryx, an Figure 62. ibex and a calf. The characteristic distinctions in the Gazelle head on an offering table 126 Figure 61. Offering list. Gazelle to the left shape of the horns are used to distinguish the animals. Here too there appears to be an intentional grouping of animals, representing in this context, as seen from the lists, “meat”. 5.3.2 Offering tables as objects A votive object in the shape of offering tables is found throughout ancient Egyptian history, with its popularity peaking twice, once during the Old Kingdom and later in the Late Period. Its primary location was in the tomb, in front of the false door or some other image of the deceased (Hassan 1944: 180). Offering tables or altars occur in temples as well. The offering table appears in various shapes; perhaps the most common is a rectangular stone slab with the sign on the facing surface (Mostafa 1982: 1-2). The surface is commonly inscribed with the name and title of the owner and a short offering formula. The formulae rarely contain more information than a list of a group of offerings, such as poultry ( ) and oxen ( ) (e.g. Mostafa 1982: 14). The offerings, mainly different kinds of bread and meat offerings, could also be depicted, either in sunken or raised relief depending on the date of the object. These food offerings, named and/or depicted, were made viable by pouring a libation over the offering table. The water/beer/wine could be assembled into small basins, formed in the offering table. The libation would then drain out via a small spout, pouring onto the ground. The offering tables saw little development during the Middle and New Kingdoms, with the number of depicted offerings increasing and the basins becoming cartouche shaped (Bolshakov 2001: 572-576). The gazelle did not constitute a regular item on these offering tables (cf. Habachi 1977, Borchardt 1937, Hassan 1944, Kuentz 1981). As always, there are exceptions to this rule. a. Offering table of Teti, Giza, Old Kingdom (Hassan 1944: 184, Fig. 32) A gazelle head can be distinguished on an offering table of Teti from Giza (Hassan 1944: 184, Fig. 32), in the section that concerns meat offerings. There are no hieroglyphs specifying the word , however, the characteristic curve of the gazelle horns clearly identifies the animal, following the same pattern as that for the two-dimensional depictions of offering tables. The term precedes the gazelle head, a feature that is common in the offering scenes (cf. above 5.1). Further, the offering next to the gazelle is the head of a calf. In short, the function of the gazelle on the offering table is the same seen in 127 the offering scenes, lists and offering table scenes, serving as sustenance for the deceased. 5.4 The gazelle as offering - concluding remarks The gazelle appears in a large variety of compositions as an offering; in the offering rows, lists and tables. The majority of the examples originate from private rather than royal sources. The offering scenes display great variation in the depictions of this animal, particularly during the Old Kingdom. An equivalent diversity in detail is not seen in later periods. Even though the offering lists, offering table scenes and actual offering tables are far more restricted in their portrayal of the gazelle, some comparable features can be noted. The gazelle in the offering scenes is carried in different ways, emphasizing its small size. This composition often occurs parallel with the domesticated calf, indicating that the gazelle, when carried, is also treated as a young animal. The number of examples of carrying the gazelle either on the shoulders or next to chest dating to the Middle and New Kingdoms decreases radically, but the compositions as such remained stable. The second category of offering images is comprised of bringing forth the gazelle, either on leash, guiding forth by horns or pushing, or with the gazelle striding independently. The gazelle is the only animal shown nursing its fawn in this context. Some of the compositions are similar to that of a cow and her calf, again indicating a correlation between the cow and the gazelle, possibly in a “domesticated – wild” pairing, as well in an emphasis on the relationship between mother and young. The nursing motif in the offering context is only found during the Old Kingdom. The young gazelle is also found in the so-called basket motif. The gazelle is the most common animal found in this motif, although it is not exclusive for the gazelle. Further, based on some of the examples, the “ideal” number of gazelles depicted in the baskets is two. This is yet another example of gazelle pairs, similar to compositions in other contexts (cf. Chapters 6 and 7 below). The offering list on tomb walls is primarily used during the Old Kingdom. The gazelle occurs as a detail in these lists, still they add correlating information concerning its role as offering. The word is occasionally included, reflecting the characterisation found in the offering rows. The gazelle is grouped either with other wild animals or together with cattle and poultry; another detail similar to the offering registers. 128 Depictions of the gazelle on offering tables are rare. However, when present the animal is easily identified by its distinctive horns. The same can be said for the gazelle on actual offering tables, where the horns indicate the intended species. The greatest variation of the gazelle in the offering context is thus observable from the material dating to the Old Kingdom. The development toward fewer examples of the gazelle as offerings (in all categories) began during the Middle Kingdom and continued during the New Kingdom as well (cf. Vandier 1964: 136). The depictions of offering scenes in the private tombs of Middle Kingdom and of the 18 th dynasty are generally replaced with those focusing on various funerary rituals (cf. 5.2 above). The more mundane offering goods are superseded by the products of high status industries that produced desirable funerary equipment. When the gazelle is found in the offering context, the compositions are the same as those seen during the Old Kingdom, even though the tomb itself may be several centuries younger. The offering of the gazelle is a standardized element of one of the most important rituals of ancient Egyptian civilization; the funerary meal (Vandier 1964: 81). This ritual connected the deceased to living relatives, with both receiving sustenance from the flesh of the gazelle, albeit on a symbolical level. 129 6 The Gazelle Motif on Objects In the discussion of the early depictions of the gazelle (Chapter 3), a number of objects that bear its image are cited: ceramics knife handles, combs, palettes and the disc from the tomb of Hemaka (3.2-3.5, 3.7). These objects primarily illustrate the use of the hunting motif in a Pre- and Early dynastic context. This is followed up in Chapter 4 with the discussion of hunting scenes that include a number of objects from the tomb of Tutankhamun: bow case, chest, tunic and unguent jar (4.2.3/a), decorated with examples of the royal hunt. In the discussion below, additional categories of objects, exemplified with individual examples, from the Early Dynastic Period and after, are examined in relationship to the development of the iconic image of gazelle. 6.1 The gazelle wand A pair of short hand-held staffs, each with a gazelle head, is found in the collection of the Egyptian Museum, Cairo. (6.1.1). Depictions of this object also occur as determinatives in the Pyramid Texts (6.1.2). Representations are also found in scenes from private tombs and temples (6.1.3-4). More properly termed a “wand”, it is, like the sceptre, symbolic in character (Graham 2001: 165-166) and differs from sceptres in its association with women rather than with men and gods (Graham 2001: 165-166, cf. Kaplony 1986: 1373-1374). Although only rare examples of these objects have survived (e.g. Hayes 1953: 284-287), a pair of gazelle headed wands (see 6.1.1) as well as a sceptre, with the head of a ‘canine’ 99 can be traced to the 1 st dynasty through archaeological finds in Giza and Abydos (Petrie 1903: Pl. II, 11, cf. also Wilkinson 1999: 189- 190). The only other example of a sceptre with an animal motif is the - sceptre, with the head of another canine, the jackal. The use of animal forms on sceptres/wands is limited to these examples, as otherwise floral motifs, such as the papyrus, is favoured (cf. Kaplony 1986: 1376, Andrews 1994: 82). It is interesting to note the 99 The identity or classification of the animal located on top of the -staff remains uncertain; the suggestions vary from dog, to jackal to the Seth animal (Kaplony 1986: 1374, Wilkinson 1992: 181) and to even the gazelle (Graham 2001:166). The other zoomorphic ‘staff’ would be the jackal headed hieroglyph (Gardiner Sign List F 12), which is used e.g. in the names of the 5th dynasty kings Userkaf and Niuserre. 130 juxtaposition of the gazelle and the canine as wand/sceptre symbols in a period when the “dog attacking gazelle” motif is a prevalent theme. 6.1.1 A pair of gazelle wands, Giza, 1 st dynasty (Cairo, CG 69246 / JE 38972; Petrie 1907: Pl. IV; Hickmann 1949: Pl. XI, B; cf. PM III/1: 312) A pair of gazelle headed wands of ivory (c. 15 cm in length, including head and handle) was discovered in tomb no. 23 during an excavation in the southeast section of the Giza cemetery (Kafr al-Batrân). This tomb is associated with a mastaba dated to the 1 st dynasty (Petrie 1907: 4-6, cf. also Hickmann 1949: 22). The wands are in two pieces, head and “handle”, assembled together. This pair is the only known example of the gazelle headed wand, and only one of these appears to be preserved in Cairo today. Petrie (1907: 4-6) reported the name of the owner of the mastaba to be “Zet”, and there is nothing in the archaeological record for the adjacent tomb 23 that provides information about their use. The inclusion of these objects in the catalogue of “Instruments de musique” (Hickman 1949) apparently reflects a deduction made from the various representations where they are seen used in a way similar to clappers, that also occur in ivory and in pairs, and to sistra. 6.1.2 The Pyramid Texts and the gazelle wand, 6 th dyn. The image of the gazelle wand is found in the Pyramid Texts, where it occurs as the determinative for the word (or ) in two of the three versions of Utterance 504. The spell concerns the purification of the king and begins with reference to the birth of the feminine dawn ( ). This birth empowers the king who “raises himself”. The spell continues with reference to purification in two groups of lakes. The Pyramid Texts provide a number of examples where the Lake of the Jackals ( ) is paired with the Lake of the Netherworld ( ), with a clear reading of or most often with the town ( ) determinative. The context in which these two lakes occur is however the same as that in Utterance 504. In Utterance 268 (§372b-c, W, N) Horus bathes ( $ % ) the 131 Figure 63. Gazelle wands, Giza king in the Lake of the Jackals and purifies ( ) the king’s ka in the Lake of the Netherworld. In Utterance 512 (§1164b, P, N) the deceased king is called upon to bathe ( ) in the Jackal Lake and be “deified” ( ) in the Lake of the Netherworld. Utterance 697 (§2170a, N), similarly refers to bathing ( ) and purification ( ) in the two lakes. In these examples the reference is to two different lakes rather than two groups of lakes. There are also two other references to the Lakes (plural) of the Netherworld, without mentioning that of the jackal. In Utterance 568 (§1432b, P), the Bull of the Sky desires to pass ( ) over to the Lake of the Netherworld and in Utterance 577 (§1530a, P), the king becomes a duck of the marsh ( ), and the Lord of the Lakes of the Netherworld descends to him so that the king can bathe ( ) in the Goose Lakes ( ). Although passage §1083a-b reads so that Lakes of the have a parallel role to that of the Lake of the Netherworld, the spelling with the gazelle wand determinative and plural dots indicates that it differs from the other references. The verb has the meaning “to worship” (e.g. Faulkner 1962: 310, Wb V: 426-428), and therefore can mean “she who worships”, encouraging Faulkner (1969: 180) to translate “Lakes of the Worshipping Women”, this reading is reinforced by the image of a woman holding the gazelle wand. In the earlier lines of the utterance (§1082b), there is reference to the dawn ( ) as the daughter of Nut, the night sky (cf. discussion in Goebs 2008: 9-10). This offers the possibility of connecting the dawn and the Lake of the Netherworld by writing instead of That the gazelle wand was thought appropriate here suggests that it was associated with allusions to, and possibly rituals for, the dawn and the rising sun. The connection between the lakes, connected to gazelle imagery and the Jackal Lakes, is also worth noting, as another example where the gazelle and a canine are combined. 132 Pepi II Merenre Pepi I 6.1.3 Dancing with gazelle wands a. Tomb of Inti, Deshasheh, middle of the 6 th dynasty or later 100 (PM IV: 121 (2)-(3), Petrie 1898: Pl. XII) In the tomb of Inti at Deshasheh the gazelle wands appear in a scene where female dancers hold them in their hands. One can separate these dancers into two groups based on their position and the number of wands. The group to the left consists of four women, each holding a single gazelle wand in their hands. There are five women 101 in the second group, with a wand in each hand. Figure 64. Gazelle wands in the tomb of Inti The dancing women with the gazelle wands appear among other dancers (on the row above), with a harp player found on the register beneath, suggesting that this is a banquet scene. The lower register has a slaughtering scene. These activities are all played out in front of the tomb owner and his wife and daughter. This composition and combination of motifs are unusual for Old Kingdom private tombs (Harpur 1987: 117). 6.1.4 The gazelle wands and the royal women at the Heb Sed a. Kheruef, TT 192, ‘Asâsîf, 18 th dyn., Amenhotep III-IV (c. 1390-1336 B.C.) (Court, west wall, PM I/1: 298 (5); Epigraphic Survey 1980: Pls 44, 45) Traces of depictions of gazelle wands are found in the 18 th dynasty tomb of Kheruef, among the many scenes in this tomb related to the Heb Sed celebration of Amenhotep III. Four women carry a gazelle wand in one hand and a menat necklace in the other. They are grouped in pairs, side by side. There may have been additional women carrying wands, the walls however 100 The dating of Inti’s tomb has been debated (Kanawati and McFarlane 1993: 17). 101 From the 1993 publication of this tomb, it can be concluded that the group at the right end originally consisted of five women (Kanawati and McFarlane 1993: Pl. 29), while in the earlier publication of Petrie (1898: Pl. XII) the fifth person is lacking, probably due to the poor condition of the tomb wall at the time of documentation. 133 are too damaged to make out any more figures. These women, described as chantresses ( ), 102 wear platform crowns, surmounted by feathers or some kind of floral motif. The inscription “beautiful girl(s)” is found above the group. They are part of the scene depicting the “towing of the night bark” (Wente 1980: 51), an aspect of the Heb Sed represented with several episodes on the same wall. Thus these women were among the participants in the Heb Sed (Wente 1969: 84). 103 b. Temple of El-Kab, 19 th dyn., Ramses II (c. 1279-1213 B.C.) (PM V: 175, Wilkinson 1971: 117, Fig. 51) Two daughters of Ramses II, Merytamun III and Bananit I (Troy 1986: 170) are depicted holding gazelle wands on a block from his temple at El- Kab. In their other hand they hold a sistrum, decorated with a Hathor head. They also wear platform crowns with a gazelle protome (cf. below 6.2). Removed in the online version by request of the publisher Figure 65. Princesses at el-Kab The Iwn-mutef officient, a role usually assumed by the crown prince (Spieser 2000: 131-133) is also present. In another relief on the west wall of the temple, Ramses II runs with the -bull, a ritual that is also part of the Heb Sed (Martin 1984: 786). c. Temple of Bubastis, 22 nd dynasty, Osorkon II (c. 874-850 B.C.) (PM IV: 29, Naville 1892: Pls XIV, XXV) Several female musicians hold a gazelle wand in one hand and a sistrum in the other on the Heb Sed portal of Osorkon II from Bubastis. Three joined blocks are carved with the images of these women (cf. Barta 1978: Pl. I). A woman holding up a sistrum is included in the group. The actions of these women are described with the word ‘dance’ or ‘clap hands’ (Faulkner 102 Cf. this with the Inti depiction where the women with this wand are dancers, rather than “chantresses” (Wente 1980: 52). Dancers are located in another section on the Kheruef tomb wall (Epigraphic Survey 1980: Pls 34, 36, 38, 40). 103 A similar feathered headdress is worn by several women depicted as participants in the same Heb Sed celebration at Soleb (PM VII: 170 (7), Schiff Giorgini 1998: Pl. 119). They do not however carry gazelle headed wands, but rather sheaves or bouquets. 134 1962: 174). They are also called ‘chantress’ (Naville 1892: Pl. XXV). On one of the blocks a woman kneels holding a gazelle wand. (Naville 1892: Pl. I). Their headdresses have a floral design reminiscent of that seen in the tomb of Kheruef (cf. also Soleb, Schiff Giorgini 1998: Pl. 119). Figure 66. Gazelle wands at Bubastis This is yet another example of women with gazelle wands participating in the Heb Sed, a celebration related to the renewal of the reign of the king. (Barta 1978: 29, Pl. I; Wente 1969: 84, Martin 1984: 782). It should be noted, that this scene is generally thought to be a copy of an earlier version of the Heb Sed representation (cf. e.g. Barta 1978: 25-26, Galán 2000: 255). 6.1.5 The gazelle wand – concluding remarks The documentation of the gazelle wand, although sparse, stretches from the 1 st through to the 22 nd dynasty, covering a period of over 2000 years. In this material some recurring elements can be noted. The earliest reference to the wand tends to point to more general regenerative connotations. In the PT the “Lake of the Worshipping Women” is a place of purification, with an explicit word play on the word “dawn”, as well as an oblique comparison to the Netherworld. The scene from the tomb of Inti shows the wand used in a dance, performed in a funerary context. The idea of regeneration is confirmed in the context of the Heb Sed where the wand is documented during the New Kingdom and then during the 22 nd dynasty. The wand itself seems to have been used in ritual dance and is found together with the sistrum decorated with a Hathor head. In general, the context in which the wand is found, suggests that it belongs to a ritual environment, such as the Heb Sed, in which Hathor, as a generative force, is well attested (cf. Wente 1969: 89). 6.2 Gazelle protomes Diadems fitted with gazelle heads as protomes, like the gazelle wands, represent a very specific use of the gazelle as “symbol”. Some of the 135 examples where a double gazelle protome is depicted show it combined with a modium crown, often decorated with various floral details. This kind of crown is sometimes referred to as a “papyrus crown” (Troy 1986: 121), which may further be understood as a reference to Khemmis (Goebs 2001: 325). The few but consistent representations of the gazelle protome show it with a pair of gazelles, although two dimensional depictions are not always distinct with regard to this feature. The diadem featuring a double gazelle protome does however support the notion of a preference for showing the gazelle as a duality. The combination of a double gazelle protome on a modium crown appears to have been worn exclusively by women, in contrast to goddesses who are not known to be depicted with crowns or diadems with a gazelle protome. The simple modium crown, as well as one with additional details, is frequently worn by a number of female deities though, perhaps most notably Hathor and Taweret (Cincinnatti 1997: 130, 132, 138, cf. also Malaise 1976: 224-225 on the association of the Hathor crown and the solar eye). The women depicted wearing the gazelle protome have in general been interpreted as concubines (Wilkinson 1971: 116), although this reflects an out-dated understanding of the title "royal adornment" (cf. e.g. Drenkhahn 1976: 60, 66). The double gazelle protome appears to be analogous to the double uraeus. The two uraei, a common attribute of the crown worn by queens (Troy 1986: 124, Ertman 1993: 44) can be found wearing the crowns of Upper and Lower Egypt. This expresses a relationship to the Two Ladies, Nekhbet, the vulture of the south and Wadjit, the cobra of the north (Goebs 2001: 322). The double uraeus appears to have been introduced during the 18 th dynasty and is thus approximately contemporary with the known examples of the double gazelle protome. The two dimensional representations of gazelle protomes are characterized by their association with noble, and sometimes royal, women. Dated mainly to reigns of Tuthmosis III – Amenhotep III, the time span for the documentation of this type of headdress is narrow, extending with one example from the 19 th dynasty, with two daughters of Ramses II. 6.2.1 Diadem with gazelle protomes, Tomb of Three Princesses, Thebes, 18 th dynasty, Tuthmosis III (c. 1479-1425 BC) (MMA 26.8.99, PM I/2: 592; Lilyquist 2003: 225, Fig. 155) This diadem with two gazelle protomes was found in the tomb belonging to the three foreign wives of Tuthmosis III (Wady D1, Wadi Qirud, Lilyquist 136 2003: 155, 161-163). The diadem has a double gazelle protome, positioned at the centre of a headband. They are flanked by two rosettes, with additional rosettes found on the band that stretches over the crown of the head. These rosettes may be the floral component also found in the drawings of gazelle protomes. They are also of a similar design as those found on panels from the tunic of Tutankhamun (cf. above 4.2.3/a.4). The craftsmanship and the design of the diadem are in conflict, according to Lilyquist (2003: 158), suggesting that a number of different craftsmen had a hand in its creation. The diadem shows signs of wear, indicating that it was not a funerary object per se. This is confirmed by the representations of these head dresses (Wilkinson 1971: 114, Lilyquist 2003: 155), worn by living women. 6.2.2 The Stag Diadem, 17 th dyn. (?) (MMA 68.1361, Aldred 1971: 204-205, Pl. 59) Another diadem with gazelle protomes is found in the collection of the Metropolitan Museum of Art in New York. It is reported to come from El- Salhiya in the eastern Delta which is situated “ten miles east of Qantir” (Fischer 1970: 70), with a suggested dating to the 17 th dynasty or perhaps even late Middle Kingdom (Aldred 1971: 204-205, Fischer 1970: 70). This electrum diadem has a stag head centre protome, flanked by a gazelle protome on either side. Four rosettes are placed between the animal protomes. Based on the date and provenance of the diadem, an Asiatic origin has been suggested (Aldred 1971: 204), although it may equally have been of either Egyptian craftsmanship or even Egyptian design. 6.2.3 Tomb of Menna, TT 69, Sheikh Abd el-Gurna, 18 th dyn., Tuthmosis IV-Amenhotep III (Hall, east wall, PM I/1:134 (2); Davies and Gardiner 1936: Pl. LIII) The daughters of Menna, titled ‘royal ornament’ ( ) are depicted wearing diadems with a gazelle at the brow, in their father’s tomb. The design of the two headdresses differ slightly from each other, with that to the left being more elaborate, consisting of a platform, surmounted by a floral design, the so-called papyrus crown. The gazelle protome on her forehead 137 Double gazelle protome Figure 67. appears to be connected to the petal fillet. An additional element is the miniature double “feathers” ( ) extending from the diadem. Two lotus buds hang over the forehead as well. This woman holds a sistrum, with the head of Hathor in one hand and a menat in the other. The woman to the right is shorter and her headdress is also smaller, and lacks the floral elements. The double feathers are also somewhat shorter. She too holds a sistrum like her sister’s, but no menat. Also like her sister, two lotus buds decorate her brow. In both cases, only one Figure 68. gazelle is visible, it is however, given other Daughter of Menna evidence, likely that the other gazelle is “hidden from sight”. 6.2.4 Tomb of Pairy, TT 139, Sheikh Abd el-Gurna, 18 th dyn., Amenhotep III (PM I/1:253 (1), Lilyquist 2003: 157, Fig. 93b) One of Pairy’s daughters wears a similar diadem to that of the smaller daughter in Menna’s tomb. The composition of the headdress included a petal fillet, a modium, the double feathers and a gazelle protome. She is probably holding a sistrum in one hand, while the other is empty. It is impossible to determine whether the sistrum is decorated with a Hathor head. Only faint traces of the name Hathor identify the girl (Lilyquist 2003: 157, Fig 93b). PM (I/1: 253 (1)), refers to her as a or “royal ornament”. The girl is situated between two taller figures, a man in front of her and a woman, behind, described as family members. The larger sized woman is followed by two men, also shorter. This size differentiation may reflect age and rank. The daughter of Pairy represents the only (known 104 ) example featuring a single person with gazelle protome. The other two-dimensional 104 It is possible that the royal daughter ( ) Amenipet (daughter of Tuthmosis IV, Troy 1986: 165, 18.31) sitting in the lap of Horemheb (TT 78, PM I/1: 153 (6); Wreszinski 1923: Pl. 251) also wears a ‘single’ gazelle headed crown; unfortunately the section where the protome would have been is destroyed. The design of her headdress can otherwise be compared to that found on the girl to the left in the Menna representation, with a modium with floral stalks, fillet and double feathers (cf. Wilkinson 1971: 116). This Horemheb is contemporary with Tuthmosis III – Amenhotep III (PM I/1: 152), and therefore approximately contemporary with Menna. The daughter of Nebamun (TT 90, PM I/1: 184 (6)), the 138 portrayals of such crowns are found in compositions that include two women or, as in the case of Satamun, a mirror image that creates a dual image. 6.2.5 Chair of Satamun, KV46, 18 th dyn., Amenhotep III (CG 51113, PM I/2: 563; Quibell 1908: Pl. XL) Satamun, the oldest royal daughter 105 ( ) of Amenhotep III, wears a papyrus modium crown and a fillet with the gazelle protome in a representation found on the surface of the back support of a chair from the Figure 69. The chair of Satamun tomb of her grandparents Yuya and Thuya. She also wears a side lock and holds a Hathor headed arched sistrum and a menat necklace in either hand; attributes which would correspond to the woman on the left side on the Menna tomb wall discussed above. This scene represents the only seated example of a woman with gazelle protome, the chair depicted possibly reflecting the object on which the representation is found. The two mirror images consist further of the motif of offering “gold from the southern foreign lands” ( ! ") to the seated Satamun. The woman offering the gold wears a similar headdress, consisting of modium and fillet, without however floral details or protomes. Segerttaui may also have had a gazelle protome on her papyrus crown, however here too the area where the protome would have been is destroyed (Davies 1923: Pl. XXI). 105 Satamun II was one of the five daughters of Amenhotep III and Teye (cf. Troy 1986: 166, 18.35-18.39). Yuya and Thuya were Satamun’s maternal grandparents. 139 6.2.6 Temple of El-Kab, 19 th dyn., Ramses II (PM V: 175, Wilkinson 1971: 117, Fig. 51) In the temple of Ramses II at El-Kab, the two women carrying gazelle wands are also found wearing gazelle protomes (cf. above 6.1.4/b, Fig. 65). This is a simple headdress, consisting of a modium (Wilkinson 1971: 117, Fig. 51) with the gazelle protome attached possibly to a fillet or circlet. They also have side locks, despite being labelled , “wife of the king” (cf. 6.2.1 above that belonged to a royal wife). Both women hold a Hathor headed arched sistrum, together with a gazelle wand. 6.2.7 The gazelle protome – concluding remarks The number of modium crowns adorned with a (double) gazelle protome is limited, yet the consistency in design indicates traditional use and connotations. Such headdresses appear to have been reserved for women of “subordinate ranking in the harem” (Troy 1986: 130). The ‘lower’ status may also have been a reflection of a young age, as some of the depictions of women shown wearing a crown with gazelle protomes occur in the daughter role. In contrast, there is no support for the idea that the gazelle protomes are worn by so-called “concubines”. Only the daughters of Menna and Pairy hold the court title (‘royal ornament’). Drenkhahn (1976: 64) has pointed out that most of the women with this title are also priestesses of Hathor, making the occurrence of the sistrum and menat appropriate. Even though the majority of the examples come from funerary contexts, such as on tomb walls (Menna, Pairy) or objects retrieved from tombs (chair of Satamun and Wadi Qirud diadem), the context of the depiction and the evidence of the Three Princesses’s diadem indicates that this headdress was worn in life. 6.3 The Horus cippi 106 The male deity featured on the so-called Horus cippi can be depicted with a single gazelle protome at his brow. This god is identified as the young Horus, or, in a variation as Shed or Horus-Shed (cf. Kákosy 1977: 61, Brunner 1984: 548). An additional example of the single gazelle as protome is found at the brow of the ‘foreign’ god Reshep ( ), who is also featured on votive stelae but not on those classified as cippi. These deities are characterized by their magical protective skills (cf. Simpson 1984: 243, Kákosy 1977: 60-61). 106 Cf. Sternberg-El Hotabi 1999a-b for a thorough study of the Horus cippi. 140 The god on the cippi stands on two crocodiles, holding snakes, scorpions, lions and antelopes. In some examples of this image, this deity wears a gazelle protome on his brow (Sternberg-El Hotabi 1999a: 27-36, cf. Bruyère 1952: 142-143, Figs 18-20). The composition reflects the protective role of the god and of the cippi (Leca 1971: 73). Drinking the water that had been poured over a cippus was said to heal anyone stung or bitten by dangerous desert animals. The idea of power over the animals of the desert is conveyed in the iconography that includes crocodiles, snakes, scorpions, lions and antelopes. The term antelope is used here as oryx, ibex and gazelle can all occur, with the oryx being perhaps most common (cf. Sternberg-El Hotabi 1999a: 8, Fig. 1). The god, often depicted with a side lock, is either shown en face or in profile. The head of Bes is generally found above the scene (Kákosy 1977: 60). Some cippi feature additional motifs, such as the solar bark or Isis nursing Horus in the marshes, while others have simpler versions of the Horus image (cf. Sternberg-El Hotabi 1999b). A magical formula against dangerous desert animals is commonly written on the verso of the cippus (cf. Bruyère 1952: 143, Fig. 20, top). A long mythological version of this text is found on the most well known example of the object known as the Metternich Stela (MMA 1950.50.85, Sternberg-El Hotabi 1999b: 72). In this depiction however the god wears the uraeus rather than a gazelle protome. In many cases, it is impossible to determine whether the protome is a uraeus or gazelle because of wear or damage. Among the preserved examples, however, there seems to be an approximate 50/50 division between the two (cf. Sternberg-El Hotabi 1999b: 117-201, Pls I-LXb). Horus stelae have been found in domestic houses as well as in tombs, confirming that these objects have a non-funerary use (Kákosy 1977: 61, Sternberg-El Hotabi 1999a: 4), and this may explain the worn condition that is characteristic for the cippi. The desert motif is also found in relation to the male god Reshep who has been connected to several different western Semitic, Mesopotamian and Greek deities. Reshep is called the god of warfare because of his attributes, consisting of maces, spears, axes and shields (Simpson 1984: 244-245). Most of the representations of Reshep include a tall conical crown, reminiscent of the white crown of Upper Egypt. Reshep is often adorned with a gazelle protome on the brow (Schulman 1979: 69, 71). This has been interpreted as reflecting “his nature as a god from the desert” (Simpson 1984: 245, cf. Leibovitch 1939: 157). The gazelle protome can be replaced by a uraeus or his crown can lack both. A good example of Reshep featuring a gazelle protome is found on a stela in the collection of the Egyptian Museum of 141 Turin (Tosi 1988: 169, Fig. 231; inv. Cat. 1601 = CGT 50066; Sternberg-El Hotabi 1999a: Fig. 20). 6.3.1 An early Shed Stela, 19 th dynasty, Ramses II (DeM 118/JE 72024, PM I/2: 697; Sternberg-El Hotabi 1999b: 97, Bruyère 1952: 142, Fig. 18) One of the earliest examples of a cippus shows the deity (Horus-)Shed standing on two crocodiles (?) holding snakes, scorpions, a lion and a bow in his hands. This was found in a temple dedicated to Ramses II in Deir el-Medina and is dated to the 19 th dynasty and the reign of Ramses II (Bruyère 1952: 141). The decorated surface is divided into two sections, with the Shed scene located on the upper half. The lower part is dedicated to the royal scribe Ramose who donated the stela to the temple. He is depicted kneeling, his arms raised in adoration. The protome on the brow of Shed is, according to Bruyère, “une tête de gazelle” (1952: 141); while Sternberg-El Hotabi (1999a: 28, n. 55) expresses her doubts; saying that it is “nicht klar”. The motif of two gazelles nibbling on a branch (‘palmette’), located in front of the feet of the deity, is an unusual feature, marking however a connection to the corpus of gazelle motifs (cf. below 6.4). The inscription is laconic but nonetheless enlightening. Shed is described as coming from the desert lands ( ) with the healthy udjat eye ( ) in order to protect the shrines (in this case, those of the temple of Ramses II where the stela was found, cf. Sternberg-El Hotabi 1999a: 29, n. 57). 6.3.2 A Horus Cippus, Saite Period? 107 (Pushkin I.1.a.4467, Hodjash and Berlev 1982: 249-251, cat. no. 182) On one of the magical stelae in the Pushkin Museum in Moscow we can observe the young Horus wearing the side lock of youth (Janssen and Janssen 1990: 40), with a gazelle protome on his forehead. That he is naked provides another reference to his status as a child (Janssen and Janssen 1990: 26, 37). He stands on two intertwined crocodiles and holds snakes, scorpions, a lion and an oryx (?) in his hands. This combination of animals is apparently iconic for “desert”. A so-called Nefertum standard is in front of him and behind him is a standard with a falcon crowned with double ‘plumes’. The 107 The Pushkin catalogue does not provide a date for this cippus. Sternberg-El Hotabi classifies it as a “Stelentypus I a” (1999a: 94-95) and further notes that “Das Kind trägt in der Saitenzeit in der Regel den Gazellenkopf an der Stirn…” (1999a: 94). 142 falcon in this scene more commonly perches on a flower (Kákosy 1977: 60, cf. e.g. Hodjash and Berlev 1982: cat. no. 192, I.1.a.4491 or Sternberg-El Hotabi 1999a: 18, “Horus who is on his papyrus” & ). Above the image of the god is the head of Bes. These elements are all common for the cippus (cf. Kákosy 1977: 60). A row of striding deities along the lower edge of the stela, is divided by two udjat eyes. A lengthy magical spell is found on the verso of this stela (Hodjash and Berlev 1982: 250-251). Figure 70. A Saite Horus cippus 6.3.3 A Horus-Shed Relief, Temple of Montu, Karnak, (Enclosure wall) (PM II: 15 (55), Sauneron 1953: 54 for figure) An incised relief from the Late Period is a good example of the iconography of Horus-Shed. It is found on the enclosure wall of the Montu temple at Karnak (Sauneron 1953: 53-55). The young deity is shown standing on (two) crocodiles, holding two serpents in either hand. He appears to have been naked except for the broad collar on his chest and the gazelle protome on the forehead. A -booth serves as a frame for this motif, surmounted by the frontal face of Bes. The emblem of Nefertum is found before Horus-Shed, inside the booth; a lotus flower has been added to the top of a standard. Double plumes or feathers emerge from the flower. Behind Horus-Shed traces of another lotus (or papyrus?) standard with a falcon perched on top of 143 it can be discerned. This standard is also located inside the booth. The falcon wears double plumes. These components correspond largely to the Horus cippus described above and the cippi in general. This relief motif represents an elaborate fusion between the young Horus and Shed (cf. Bruyère 1952: 142-143, Figs 18-20). The inscription on the enclosure wall of the Montu temple is fragmentary yet some information can be gleaned from it. Above Horus- Shed it reads , ‘Horus-Shed, the great god, son of Osiris, born of Isis, the divine’ (Sauneron 1953: 55). A lengthier sentence is inscribed outside the booth, to the left. Even more fragmentary, it is difficult to read beyond the reference to Geb and Nut as father and mother. 6.3.4 The Horus Cippi – concluding remarks The representations of Horus and Horus-Shed with gazelle protome are of young deities, often wearing a side lock and commonly shown nude. This status may be analogous to that of some of the female wearers of the gazelle protome that are predominantly associated with the status of daughter, or (minor) wife. The gazelle protomes in this case however appear to be single, rather than double, just as the alternative single uraeus, is common in connection with the diadem or crown of the king. The main contextual reference for this deity is that of one who protects from the dangers of the desert, primarily the bite and sting of snakes and scorpions. In this respect the “antelope”, including the gazelle, represents the desert environment to be controlled. The protome however appears to refer to agents of protection as well as danger, as is suggested by the occurrence of the uraeus in the same position. The connection gazelle-uraeus-udjat eye is found in the short reference to the healthy eye, and is mostly likely emblematic of the young god’s healing powers. 6.4 The palmette with antithetical gazelles on two chests One common motif featuring the gazelle is that of antithetical gazelles eating from a palmette, a stylized tree (Kepinski 1982: 7), elaborated with floral petals, buds and stalks. This image appears mainly on furniture and household objects. Most of these gazelles-and-palmette examples date to the New Kingdom (Spalinger 1982: 117). The palmette motif has previously been seen as of western Asian origin (cf. Montet 1937: 143-146), but as pointed out by Spalinger (1982: 117) “…the reverse is equally possible: the appearance of this motif in Syrian art is due to Egyptian influence.” A similar conclusion is reached by Kepinski (1982 I: 116), who studied the different 144 palmette compositions found in e.g. Cyprus, Egypt and Iraq, compiled into three volumes (L’arbe stylisé en Asie Occidentale I-III, 1982). Volumes I and II present a meticulous study on the composition of the palmette, while Volume III is a catalogue with illustrations. It is worth noting that Kepinski’s catalogue of the Egyptian palmettes does not include all known examples (e.g. excluded are the wooden cosmetic spoon, CG 44911/JE 33211, Wallert 1967: Pl. 20 and the funerary chariot panel, CG 51188, Quibell 1908: Pl. LIII). Although the frequent use of the palmette in western Asia makes an origin there plausible; it would appear that this motif has a further development in ancient Egypt, with a different style and expression, including such elements as grazing gazelles. The grazing gazelle motif can be traced back to the Old Kingdom, where a single gazelle is found nibbling on a bush (e.g. mastaba of Pehenuka, Harpur 1987: Fig. 188; temple wall of Niuserre, von Bissing 1956: Pl. XI a). Similarly, antithetical gazelles are a feature found in earlier times, as in the 11th dyn. tomb of Ip (above 4.3.2/d). There are several examples where a palmette is used as a separating element between two animals that eat from it (cf. Kepinski 1982 III: Nos 903- 918). It can also appear as an independent image without flanking animals (e.g. Bubastis silver jar CG 53262/JE 39867, Edgar 1925: Pl. I, Fig 1). The most common species associated with the palmette are the goat and the gazelle. While the goat is generally found nibbling on a tree 108 on tomb walls (e.g. TT 217, Ipuy, Wreszinski 1923: Pl. 366; Ka-hep, Kanawati 1980: Fig. 15; Akhet-hetep-her, Wreszinski 1923: Pl. 108), the motif of the gazelles grazing on a palmette is more common on objects. Examples of this motif are found on a range of objects, with just a selection cited here: “bronze” jar stand (Chicago Field Museum of Natural History no. 30177 b, EGA 1982: 120, Fig. 106), wooden cosmetic spoon (CG 44911/JE 33211, Wallert 1967: Pl. 20), funerary chariot panel (CG 51188, Quibell 1908: Pl. LIII), game board (CG 68005, Pusch 1979: Pl. 45 (the animal could be an ibex)), and the image of a basket on the tomb wall of Ramses III (KV 11, PM I/2: 521-522; Montet 1937: 108, Fig. 146). To this list of examples where a gazelle eats from a palmette should be added a cippus, discussed above (6.3.1). In addition to the great variety of objects with the gazelle and palmette motif, there is a diversity of materials and techniques, from a painted surface on the chests to carved wood panelling 108 A chest located in the tomb of Sennedjem (TT 1) belonging to his wife Iyneferti is an exception to this rule; painted on the lid we can observe a gazelle standing on its hind legs, leaping upon a tree. The background was spotted, as if to imitate desert land. The gazelle has its head turned back and a hieratic inscription reading “made for Iyneferti ” is included at the bottom of the scene (JE 27271, PM I/1: 5; Capart 1947: Pl. 756). 145 and open work metal for the jar stand. In short, the gazelle and palmette motif is not limited to a specific category of objects, yet the repetition of the motif indicates its broad popularity. 6.4.1 Chests of Perpaouty, Thebes, 18 th dyn., Amenhotep III Two painted wooden chests belonging to a man called Perpaouty ( , with varied spelling, Killen 1994: 38) are decorated with two antithetical gazelles nibbling on a palmette. The chests are located in different museums: Museo Civico Archeologico in Bologna and Durham University Oriental Museum. The grazing gazelles are on the short ends of both chests. The gazelle and palmette motif is augmented with the addition of suckling young as well. While the motif was the same on both boxes, the style differs slightly, suggesting two artists. The chests were most likely used to store cosmetic jars, linen and clothing (cf. the boxes of Kha, TT 8, PM I/1: 17; Killen 1994: 44). This would have been its function in a funerary context as well and this kind of box is often depicted as part of the procession of funerary gifts (Kozloff 1992: 287). These, as well as other, chests are often decorated in accordance to their funerary function. The lids of the two chests, for example, are painted with the same pattern as a typical tomb ceiling, and the long sides of the chests are decorated with ‘traditional’ offering scenes with the deceased seated in front of an offering table (Kozloff 1992: 286, Killen 1994: 50). The inclusion of the motif of nursing gazelles, grazing on a palmette, found on both chests, indicates that it was a deliberate choice of a possibly popular funerary theme. Discussion of these chests and their decoration has referred to the possible foreign origin of their owner Perpauoty. Although his Theban tomb is lost today, he apparently lived during the reign of Amenhotep III (Bologna 1994: 71). With his and some of this family’s unusual names, Kozloff (1992: 286) concluded that “the gentleman and his family were foreigners” and that the motif found on the chests could likewise be of foreign origin. This conclusion, as noted above, is far from certain. a. The Durham Chest (PM I/2: 838 109 , Durham no. N. 1460; Kozloff and Bryan 1992: Pl. 33) The details of the motif on the two short ends of the chest in Durham differ slightly from each other. One end displays nursing gazelles, standing on their 109 The name of Perpaouty is read in PM I/2: 838 as . Only the chest in Durham is cited, with the Bologna chest being omitted. 146 hind legs and nibbling on a flower sprouting from the palmette. The fawns are given short stubs, indicating growing horns. Palms hanging upside- down from the upper corners are unusual, possibly inspired by Middle Assyrian iconography (Kozloff 1992: 286). The other short end is similar, but without the nursing element. This time the gazelles are most likely fawns with short straight horns, possibly alluding to the young ones on the other side of the chest, only slightly older. A curious detail is the rather prominent udder on their bellies, despite their young age. The end panel, lacking nursing gazelles, coincides with the other New Kingdom examples of this particular motif (e.g. Kepinski 1982 III: cat. Nos 931, 936, 941, 942, 1032; also single gazelle, cat. Nos 926, 928). b. The Bologna Chest (Bologna, KS 1970; Bologna 1994: 71) It has been suggested that the chest in Bologna was painted earlier than that in Durham as the gazelles were “drawn with straighter lines than the curvaceous outlines of the Durham gazelles” (Kozloff 1992: 287). The motif is still the same, nursing gazelles, standing on their hind legs, eating from the palmette. Some details differ however. The fawns, for example, lack indications of horns. They stand with their feet on the ground and the design of the palmette is slightly less elaborate than seen on the Durham chest. Furthermore, both short ends of the Bologna chest are decorated with the same motif of nursing gazelles separated by a palmette. These two chests are not the only ones attributed to Perpaouty, another plain chest has been suggested to come from this tomb (Killen 1994: 42). 6.4.2 Antithetical gazelles and the palmette – concluding remarks The motif of nursing gazelles eating from a palmette can only be found on the Perpaouty chests while the ‘basic’ motif of two gazelles nibbling on a palmette is widely distributed on other New Kingdom objects (Kepinski 1982 147 Figure 71. The Perpaouty chest in Bologna III: cat. Nos 931, 936, 941, 942, 1032; also single gazelle, cat. Nos 926, 928). The image on the short ends of the Perpaouty chests represents a fusion between two motifs that can be otherwise observed separately; the nursing gazelle, which can be traced back to Old Kingdom desert hunt and offering scenes (cf. Appendix III below) and the antithetical gazelles nibbling on a palmette, which can be observed on contemporary objects. 6.5 The nursing gazelle on faience bowls Small shallow faience bowls, decorated with aquatic and floral motifs sketched in black or dark violet on both interior and exterior surfaces have been recognized as a specific “type” of vessel. Strauss interpreted their decoration as a picture of Nun, and coined the term “Nunschale” (1974: 70-82). Pinch (1993: 313) however uses the designation ‘marsh bowls’, a term she considers to be “more neutral”. They are mainly dated to the New Kingdom (Strauss 1974: 9, 65-66) and more specifically to the 18 th dynasty (Pinch 1993: 311, Milward 1982: 141). The interior iconography varies from flowers, fish, ponds (‘water’), to Hathor heads, cows and girls playing the lute. The exterior focuses mostly on the floral motif (cf. Strauss 1974: 9). 110 The motif of a nursing gazelle, as the only gazelle motif, although not among the most common on the bowls, is also found. The exact use of the bowls is difficult to establish as most lack a recorded context (Strauss 1974: 65). The known provenances include temple areas (Pinch 1993: 308 111 , 312), many of which are cult sites of Hathor. Faience bowls of this type have also been found in tombs, more specifically those in western Thebes (Strauss 1974: 65). The known find contexts point to an association with a ritual of some kind. Considering the dominant aquatic motif, they may have functioned as a container for libation water (cf. Pinch 1993: 313). Another possibility is as a drinking cup for wine, a suggestion yet again based on iconography, as the marsh motif may have referred to the Delta where the majority of the vineyards were located (Poo 1995: 11, 17-18). The possibility that the bowls were used as a drinking cup for milk has also been suggested (Strauss 1974: 67, Pinch 1993: 314-315). This idea interested Bruyère (1937: 89), who tested the dried residue from some bowls and found that “…ce résidu provenait de l’évaporation et de la dessiccation 110 Strauss (1974) provides a good survey of the decorative range of this category of objects. 111 Pinch (1993: 308, cf. also 311) states that most of the faience bowls come from a limited number of sites: “Deir el-Bahri, Faras, Serabit el-Khadim, and Timna”. 148 du lait”. 112 One source that supports the interpretation of these bowls as drinking cups is found on the early Middle Kingdom, Deir el-Bahari sarcophagus of Kawit (JE 47397), a wife of Mentuhotep II (Naville, Hall and Ayrton 1907: Pl. XX, Section “II”), where she is seen drinking from a small bowl similar in shape and size to the faience bowl. A male servant pours liquid from a small jug, said to be for her ka ( ). That Kawit drinks milk from the cup can be deduced from the adjacent scene in which a jug similar to that used by the servant is used to collect milk from a cow (Naville, Hall and Ayrton 1907: 55). If indeed the faience bowls were used to serve milk there is some sense to the presence of the nursing gazelle as decoration. The examples of the nursing gazelle motif found on the bowls are similar, but not identical. At least four 113 have been identified: the Maiherperi bowl (CG 24058/JE 33825, Daressy 1902: Pl. VI), two bowls in the collection of Ashmolean Museum in Oxford (E 1890.1137, Petrie 1891: Pl. XX, and E 1912.57, unpublished) and a fragment in the collection of the Petrie Museum (UC 30054). In each case a gazelle nursing her young in a floral-aquatic environment is found. The suggested term marsh bowl by Pinch would correlate with the iconographic elements in which this gazelle motif appears. Three of the bowls are stylistically similar. It is the Gurob bowl (Ashmolean E 1890.1137) that differs in style but is still similar in the composition of the image of the gazelle. 6.5.1 The bowl of Maiherperi, KV 36, mid-18 th dynasty (CG 24058/JE 33825, PM I/2: 557; Daressy 1902: 24, Pl. VI) The perhaps most well known of the bowls displaying the nursing gazelle motif would be that found in the tomb of Maiherperi. The interior of the faience cup is decorated with a gazelle nursing her fawn. The mother nibbles on a branch that extends from her mouth. The markings of the gazelle are represented with spots and stripes across the neck as well as a prominent eye ring. The gazelle appears to be standing near or in a pond, represented by lotuses and three tilapia fish. The bodies of the fish, like the gazelle, are decorated with spots, with the fins marked with stripes (cf. fragment in Munich, ÄS 5633, Strauss 1974: 63, Fig. 67; also UC 30054 and Ashmolean 112 Bruyère appears to have cited personal experience when he says that the solution resulted in a “violente odeur” (1937: 89), yet no chemical analysis seems to have been undertaken (?). 113 A fragment located in the collection of Munich (ÄS 5633) shows an animal with a striped, elongated neck and a spotted body. Traces of a palm tree and lotus buds may be discerned as well (Strauss 1974: 62-63, Pl. 13, 2). Based on the other faience bowls featuring gazelles, it may be speculated that this fragment was originally a part of a nursing gazelle motif. 149 E 1912.57). One is represented “under” the gazelle, near a group of lotus buds, while two are drawn on either side of gazelle’s neck, apparently chewing on a strand of a pond plant (cf. Strauss 1974: 18 “durch einen gemeinsamen Stengel miteinander verbunden sind”). This gives the odd impression of the fish “hanging” on the neck of the gazelle. Leaves of ivy along the rim of the bowl complete the floral decoration. The Maiherperi bowl is the only complete bowl of the four and the only with a tomb provenance. Maiherperi, titled “Child of the Nursery” and “Royal Fan-Bearer” was buried in the Valley of the Kings (KV 36) even though not of royal blood. His tomb, after being robbed, was resealed with many of the original grave gifts, including this bowl. It has been dated tentatively to the reign of Hatshepsut. 6.5.2 The Gurob bowl (Ashmolean Mus. E 1890.1137, Petrie 1891: Pl. XX) A bowl fragment, dating to the 18 th dynasty and found in the temple area of Medinet Gurob 114 is also decorated with the nursing gazelle motif (Petrie 1891: 19). The primary components are the same as those found on the Maiherperi bowl: the nursing gazelle, the Figure 73. The Gurob bowl lotus buds and petals, and bush (rather than branch), from which 114 According to Petrie's publication, the bowl fragment was found at Medinet Gurob (1891), while the card in the files of the Ashmolean Museum states that it was a part of the “Riqqeh Corpus”. 150 The Maiherperi bowl with nursing gazelle Figure 72. the gazelle mother nibbles. Here however there is a firm ground line, similar to that found in tomb paintings. The more naturalistic depiction clearly identifies the animal as a gazelle with its characteristic horns. The body of the gazelle is not however decorated with spots and stripes, which otherwise reoccurs for this motif (cf. Strauss 1974: Figs 3-20). The nursing gazelle is also framed by two palmette-like plants. The remains of a large flower above the gazelle continue the floral theme. 6.5.3 The large Ashmolean Bowl (Ashmolean Mus. E 1912.57, unpublished (?)) The second faience bowl, now in the Ashmolean Museum collection, featuring the motif of a nursing gazelle, was once rather large, although now represented by nine fragments that form only half of the bowl. The remaining section of the bowl preserves the nursing gazelle motif. Similar to the Maiherperi bowl, the gazelles, mother and child, are spotted, with the elongated neck striped. A branch extends to the mouth of the mother gazelle also as in the Maiherperi bowl. The surrounding motifs consist of lotus flowers, buds and a stylized palmette. The provenance for this bowl is cited on the exhibition card as “Serabit el-Khadim”, one of the cult centres of Hathor at Sinai (Pinch 1993: 50, 58). 6.5.4 The Petrie Museum fragment (UC 30054: unpublished (?)) Figure 74. Bowl fragment in the Petrie Museum A small fragment now in the collection of the Petrie Museum represents another version of the nursing gazelle seen on the Maiherperi and Gurob bowls. The gazelles are yet again decorated with spots and stripes. A branch reaches up to the mouth of the mother. The surrounding floral design is more similar to that on the Gurob bowl, with distinctive lilies. Further details are lacking on the fragment. The provenance for this fragment is not known, and an 18 th dynasty date is suggested on the basis of the parallels. 151 6.5.5 The nursing gazelle on faience bowls – concluding remarks The nursing gazelle is found as a reoccurring motif on the faience bowls known as “marsh bowls” or “Nunschale”. Two styles are found in the four examples cited above. The more stylized image with the gazelle decorated with spots and stripes, a branch found at the mother’s mouth, is represented by three examples. The provenance of two of these are known, with one coming from the Valley of the Kings’ tomb of Maiherperi and the other from the Sinai site of Serabit el-Khadim. The geographic distribution of the two examples suggests either a coincidental connection between the two finds, or that the motif was widely used. The other more naturalistic version of the nursing gazelle motif, found on the Gurob fragment, has elements in common with the first version, such as that of the mother eating while nursing. This is however a common addition to the depiction of the nursing gazelle (cf. e.g. the chests, above 6.4.1). Perhaps the most striking aspect of this depiction is the connection made here between the gazelle and water in the scene itself. In both styles the gazelle is found near or “in” a pond of sorts. As seen in the discussion above, the gazelle is otherwise characterized as a “desert” animal. The connection to liquid is found on several levels here, with the bowl itself most likely a drinking vessel. The aquatic imagery strengthens this connection, and may provide the background for the inclusion of a nursing scene. 6.6 A gazelle-shaped vessel (tomb of Kenamun, TT 93) 18 th dyn. (West wall, PM I/1: 191 (9); Davies 1930: Pl. XX) Animal-shaped vessels (“zoomorphic”) are found in various forms, with Middle and New Kingdom dates. In a scene from the tomb of Kenamun there is a depiction of a collection of New Year’s gifts. Among them are vessels in the forms of a recumbent oryx, ibex and gazelle. The gazelle and ibex-shaped vessels have lotus flowers extending 115 from their mouths that most likely functioned as spouts (cf. Quaegebeur 1999: 33). This is confirmed by a vessel in the Louvre (E 12659) that has the form of a recumbent ibex. The animal’s mouth is the opening of the vessel. The Louvre vessel also has two fawns, one on either side of their mother’s neck (Gauthier 1908: Pl. III). It may have once contained “cosmetic substance” (Freed 1982b: 24), although the motif of mother and fawn favours a function as a milk jar (Paris 1981: 115 Although Davies (1930: Pl. XX), only shows the gazelle with the lotus coming out its mouth, LD III: Pl. 64a shows the flower in both the ibex’s and the gazelle’s mouth. The photograph in Wreszinski (1923: Pl. 306) shows that the area near the ibex’s mouth was damaged when copied by Davies. 152 227). Similar red-polished vessels shaped as a woman holding a child in her lap have been described as milk containers, used medicinally (Desroches-Noblecourt 1952: 49-67, Hayes 1959: 195, Freed 1982b: 61). Quaegebeur (1999: 33, 35) argues that the shape of the ibex horns is similar to the hieroglyph “young” (Faulkner 1962: 150). Following this thread, it may be suggested that the gazelle-shaped vase on the Kenamun tomb wall is a milk jar, and that the rejuvenating properties of milk are associated with the beginning of a new year. 6.7 ‘Cosmetic’ Spoons 116 Ivory spoons with zoomorphic handles have been found in graves from the Badarian Period (c. 4400-4000 B.C.) and these are described as “for eating with” (Brunton and Caton-Thompson 1928: 32, Pl. XXII). Similar objects of dynastic date have early on been treated as cosmetic utensils. The objects labelled ‘cosmetic spoons’ have handles and shallow containers, often round or oval in shape, hence the term ‘spoon’. Many of the objects understood as cosmetic spoons or dishes have been found in tombs “belonging to both men and women” (Freed 1982a: 207), while some have been found in temples. A few have been found in palace areas, such as Malqata or Amarna. Many of these cosmetic containers lack a specific archaeological context with the documentation only giving a place name such as Memphis or Thebes (Wallert 1967: 53). There are much fewer examples of these spoons dated to the Old and Middle Kingdoms than to the New Kingdom when they are both numerous and elaborate. A few spoons of New Kingdom date feature the gazelle. 6.7.1 Typology The style of the spoons varies greatly, as does the material of which they were made. This is particularly true of the New Kingdom examples. Cosmetic spoons of this period with gazelle motifs can be divided into three different types: the so-called swimming-girl spoons, the spoons with a handle and a flat container, and the trussed animal dishes. The swimming-girl spoon refers to objects where the handle is shaped into an almost nude adolescent girl in an outstretched position, as if swimming (cf. Keimer 1954: Pls I-VI). The girl’s outstretched arms hold a container. This container can be in the shape of a duck or goose, an oval 116 A concise overview of the development and the classification of the cosmetic spoons can be found in Wallert (1967). 153 container (i.e. the “cartouche pond”) or, as in one example, a recumbent gazelle. These zoomorphic containers are often crafted with a sliding lid. The second group of spoons is the most diversified. The spoons are often of wood, with the handles commonly carved in open work. The handles can be in the form of Bes figures, adolescent girls playing a musical instrument, intricate floral decoration or zoomorphic motifs (Frédéricq 1927, Wallert 1967, Freed 1982a, Kozloff 1992, Paris 1993). The gazelle occurs in this type on the handle. The flat or shallow containers are generally in the form of an oval cartouche. This can either be empty or decorated with fish, lotus flowers and/or birds. The third type is that of the so-called trussed animal dishes (Paris 1993), and are excluded from Wallert’s analysis as they are not spoon-like in their shape. Yet they have been treated as cosmetic implements (Frédéricq 1927: 13, Peck 1982: 212-214, Paris 1993). The dish is shaped like a trussed animal, with the body serving as a shallow container. The most common animal found in this type is the oryx, followed by the ibex, probably due to the more sturdy shape of the horns (cf. Peck 1982: 212) that also form a smooth outline of the dish itself. Examples of trussed gazelles are also found (e.g. British Museum BM 20757, Frédéricq 1927: Pl. IX; Louvre E 11123, E 11043, E 22916, Paris 1993: 30-31). The horns of the gazelle are missing and not integrated with the object itself. 6.7.2 Function The term ‘cosmetic spoon’ has caused some objections (Keimer 1954: 59, n. 1; Wallert 1967: 49-50, Freed 1982a: 207, Kozloff 1992: 331) as there are no explicit pictorial sources for the use of cosmetic dishes or any other indication that this was how the object was used. It is notable that the spoons found in tombs were not included in boxes or containers for cosmetic utensils (Wallert 1967: 53-54). Furthermore many of the spoons are too shallow to contain larger amounts of cosmetic substances and therefore would have been rather impractical. A few of these so-called cosmetic spoons have been shown to contain traces of residue or “incrustation” (Frédéricq 1927: 9). No chemical analysis has, however, been described. A double spoon belonging to the collection of the British Museum (BM 5953) is said however to have contained “remains of wax (?) or ointment (?)” (Frédéricq 1927: 9, Pl. VII). An alternative interpretation of the spoons suggests that they have a ritual character, as “offering spoons” (Wallert 1967: 66) or as “ritual implements” (cf. Kozloff 1992: 331). This connection is supported by the trussed animal motif, with its association with offering. While Wallert raises the question of the function of the spoons, she does not refer to their 154 decorative forms. The iconography of the spoons has however been treated by Kozloff (1992: 331). The elaborate execution of many of these spoons has been seen as evidence of skilled craftsmen (Frédéricq 1927: 7, Peck 1982: 213, Paris 1993: 5), which would indicate the importance of this group of objects. The gazelle is not a common motif among the cosmetic spoons. The spoon however draws on the same kind of motifs as the faience bowls (cf. above 6.5.1), and thus provides further evidence for the inclusion of the gazelle in a complex of available motifs. 6.7.3 Swimming-girl spoon with gazelle container (New York, MMA 26.2.47; Wallert 1967: Pl. 15) An example of a swimming-girl spoon holding a gazelle is found in the collection of the Metropolitan Museum of Art. The handle is in the shape of a young woman, her arms outstretched, holding a container. The container has Figure 75. Swimming-girl spoon with a recumbent gazelle as container the form of a recumbent gazelle. The upper part of the gazelle’s body, the neck and head constitute the sliding lid, while the belly forms the actual container. This sliding lid construction is found in other examples of swimming-girl spoons. The girl is naked except for a girdle made in a separate material, as is her wig that has a side lock. Freed (1982a: 206) saw a similarity between this hair style and that of Satamun on the chairback (cf. above 6.2.4). The gazelle, like the girl, is young, with only stubs indicating horns. Comparing the sliding lid with other such spoons reveals that the most common motif was the duck or goose (Wallert 1967: Pls 11-15, and N 1725A, N 1725C in the Louvre, Paris 1993; cf. Kozloff 1992: 332). 155 6.7.4 Cartouche Pond (British Museum, BM 5958; Wallert 1967: Pl. 19) A wooden cosmetic spoon in the British Museum is in the shape of a so-called cartouche pond. The “pond” is indicated by two antithetical tilapia fish with lotus buds and flowers sprouting from their mouths, similar to those seen on the faience bowls. The ‘handle’ has the form of a recumbent gazelle with its head turned back. The animal is carved in open work and the details on its belly indicate that it is a male. This spoon belongs to the cartouche pond type, with interior motifs consisting of tilapia fish, lotus flowers and birds, all representing ‘pond life’. The handle iconography is more varied. In addition to the gazelle 117 , a hare (Brooklyn 37.608E, Wallert 1967: Pl. 20) and a gosling (AFIM 1990.35, Kozloff 1992: 352, cat. no. 79) may be noted. The gazelle motif found here is clearly taken from the form typical for the insert (cf. above 4.1.4), representing the young gazelle in hiding. 6.7.5 A gazelle container (Cairo, JE 44744; Freed 1982a: 201, Fig. 54) This object, although not a box, is related to the spoons as a small 118 container for “scented unguent” (cf. Freed 1982a: 200). Made of wood and in the shape of a recumbent young gazelle, this object reiterates the motif found on the New York spoon described above. The horns are missing, but may have originally been made in a different material (cf. the gazelle statue MMA 26.7.1292, see below Fig. 83). Such zoomorphic containers have generally been dated to the 18 th dynasty (Freed 1982a: 200). This object is included in Maspero’s presentation of ancient Egyptian art (1912: 200, Fig. 385), without comments on provenance. 117 There is a similar cartouche pond spoon in the Cairo Museum (CG 44911/JE33211), where the ‘handle’ is carved with the motif of two gazelles nibbling on a palmette (Wallert 1967: Pl. 20). 118 No measurements are given by either Maspero (1912: 200) or Freed (1982a: 200). 156 spoon with fawn Figure 76. Cosmetic 6.7.6 Cosmetic spoons and containers – concluding remarks These three objects represent different kinds of containers, all possibly intended for some kind of cosmetic substances. The gazelle representations all have the recumbent posture that point to the young age of the animal. Aquatic references are also present. These components relate the spoons to the same decorative sphere as the faience bowls, with the fawn occurring instead of the mother-child combination. 6.8 Scarabs The scarab was one of the most popular amulets in ancient Egypt, with a popularity that also reached beyond Egypt (Andrews 1994: 50). Its form not only gives the image of the beetle that rolls balls of dung within which its young are born, but also the hieroglyph “to become”, “be transformed”, giving a context to its protective qualities (Bianchi 2001: 179). Originally an amulet with scarab form in the Old Kingdom (Bianchi 2001: 180), by the Middle Kingdom the base was commonly decorated in such a way that it has been understood as a personal seal (Andrews 1994: 52). The scarab appears to have retained its protective function, with the base displaying a growing diversity of motifs. Various geometrical designs and hieroglyphic phrases, understood as beneficial, are common (Ward 1978, Tufnell 1984a-b). The desert hunt appears as an element of scarab iconography during the Middle Kingdom (cf. Hornung and Staehelin 1976: 138, Andrews 1994: 53) and is especially popular during the time of Ramses II (Giveon 1984: 976). The components in the hunt scene are similar to those found in the tomb versions (cf. above 4.1.2), but more limited. The hunters could vary from archer to dog and lion (cf. e.g. Petrie 1925: Pl. XIV, Newberry 1906: Pl. XXV, 26). The desert topography can be represented by a branch or a uraeus, usually seen above a single striding or recumbent antelope (Tufnell 1984a: 132). The oryx and the ibex are the preferred animals on scarabs, most likely because their horns have a ‘practical’ shape. 119 It may be suggested that the desert game 120 seen on scarabs should rather be understood as antelopes in general rather than any specific species. ”Die genaue Zuordnung der Tiere (Antilope, Gazelle, Steinbock usw.) spielt im Grunde keine Rolle, da sie alle zum Wild der Wüste gehören und die einzelnen Tiere eine ihnen gemeinsame Symbolik haben” (Wiese 1996: 134). This is a view shared by several authors 119 Cf. Andrews 1994: 30, on ram headed amulets and their horns. Also Lilyquist 2003: 159, on portraying animals in “small scale”. 120 Excluding species such as hares, hedgehogs and snakes. 157 (e.g. Hornung and Staehelin 1976: 138, Matouk 1977: 111-114, Tufnell 1984a: 132). These different species, as a group and individually, convey however very specific references to the desert landscape (cf. Goldwasser 1995: 21). 6.8.1 The gazelle on the scarab There are a small number of scarabs decorated with the image of an antelope that can be identified as a gazelle (e.g. Hayes 1959: Figs 17, 48; Petrie 1925: Pl. XIV, Newberry 1906: Pl. XXV, 22; Matouk 1977: 387, no. 737). The limited use of the image of the gazelle may be explained by its lyrate (S-shaped) horns that pose some difficulties for the artist when faced with the limited space on the scarab base. It has been suggested that the image of desirable game had the function of ensuring sustenance (Hornung and Staehelin 1976: 140, Andrews 1994: 51, Bianchi 2001: 180). If the scarab is related to the idea of the solar cycle as it would seem, then this becomes the desire for a daily renewal of this game. The branch, 121 commonly found above the antelope (and here above the gazelle), is read as , translated as ‘young’ (Faulkner 1962: 150). In other words the plant represented “die Idee vom immer wieder jung sein” (Hornung and Staehelin 1976: 138). The desert game iconography provides an additional regenerative level to the scarab. This idea is confirmed in the use of the motif of a gazelle nursing her young 122 documented in at least two examples (Keel 1980: Fig. 49c, Matouk 1977: 387, no. 737) and on a seal plaque (Keel 1980: 88, Fig. 49b) as well. The scarab motifs bring the nursing gazelle with her fawn together with the notion of young ( ) and the scarab form of the new born sun god Khepri. 121 Hornung and Staehelin (1976: 138-139), further note the similarities between the branches on scarabs and the branch sprouting from the mouth of the nursing gazelle on the Maiherperi faience bowl (cf. above 6.5.1, 6.5.3 and 6.5.4). 122 The scarabs constitute the except where several examples of nursing ibexes can be observed (Keel 1995: 97, Fig. 165; Keel et al. 1997: 633, no. 287; 677, No. 43. It should be noted however that these scarabs were not found in Egypt). With the exception of the scarabs, the nursing motif is otherwise almost exclusively reserved for the gazelle. This exception may be explained as another example where the shape of the horns is decisive in the artist’s choice of animal when dealing with limited surfaces. 158 A branch and gazelle Figure 77 6.9 The gazelle motif on objects – concluding remarks The objects bearing the image of the gazelle can be viewed from two perspectives. On one hand the motifs used are those found in tomb painting. These are abstracted from that context and combined with other elements to strengthen the reading implicit in the motif. The preference for the nursing gazelle and the fawn suggests that there is a beneficial, and plausibly regenerative, understanding of the value of this image. This is explicit as the gazelle is placed in ritual and expressly symbolic, contexts, with the gazelle wands and headdresses with gazelle protomes. The parallelism between the gazelle and the uraeus underlines the elevation of this image to a meaning bearing icon. Its insistent association with young women also indicates a movement towards the solar daughter sphere that the uraeus represents. 159 7 The Gazelle and the Divine The discussion up to this point has mainly focused on pictorial evidence in the form of representations of the gazelle either on temple and tomb walls or on objects. In reference to that material the primary aim has been to identify the motifs that are characteristic for the gazelle and to examine the context in which they occur. In this analysis, the natural world has dominated as the origin for the form of these representations. Some exceptions do however occur in the material discussed above that suggest that the image of the gazelle had another level of meaning. The gazelle wand, depicted in funerary dances and royal ceremonial processions, appears to have ritual significance (6.1). Found in the same, as well as other, contexts, a pair of gazelles as the protomes of a diadem adorns the brow of participating women (6.2). The other example of the gazelle as a protome is as the attribute of the god found on the Horus cippi. This also indicates that the image of the gazelle is not exclusively a natural representation. Suggestions that the Egyptians connected the gazelle with the cow in the combination of nursing mother and fawn, also indicate the manner in which the image of the gazelle tangents the divine sphere. Similarly it appears to be, in some contexts, interchangeable with the uraeus, as a brow ornament. This chapter surveys the evidence for the gazelle as a representative of the divine. It follows the same chronological line as in previous chapters, beginning with Predynastic evidence and concluding in the last years of ancient Egyptian civilization. 7.1 The Predynastic gazelle burials Animal burials are found in several cemeteries of Predynastic date. These animals are however commonly domesticates. The occurrence of the gazelle, a non-domesticate, is exceptional. The problem of interpretation represented by these burials is underscored by the discovery of an elephant grave in an elite cemetery at Hierakonpolis (Adams 2004, Friedman 2004: 132ff). Whatever the motivation for including these animals, either in separate graves, or together with humans in the same grave, in these cemeteries, it is plausible to conclude that the burials entail a desire that these animals partake of the same afterlife as that awaiting the other cemetery inhabitants. Immortality and proximity to the divine is thus not, in this early period, an exclusively human prerogative. 160 Animal burials are found at cemetery sites dating from the Badarian through to the Naqada periods. 123 The most common animals found are dog, sheep/goat and cattle. As these are all domesticated animals, Flores (1999: 84) sees the custom of burying gazelles as an indication of attempts at domestication. This connection between burial and domestication thus regards the grave as a way of reaffirming a tie that existed in life. This discussion is however somewhat more difficult to pursue given the discovery of the elephant burial. Gazelles have been found in human graves and alone in pits, although individual burials are rare (Flores 1999: 33-34). The sites at which they are found are limited to a relatively well defined area in Upper Egypt, between Matmar - Mostagedda and el-Khatara, Ballas and Armant (Flores 1999: 83- 87). Gazelle burials have sometimes been described as relatively common (Behrens 1963: 75, Debono 1954: 635). Closer examination of the bones recovered has however altered this picture. While earlier excavation reports have identified some of the bones from animal burials as gazelles (e.g. Debono 124 1950: 234, 1954: 635-637; Leclant 1954: 73, Behrens 1963: table I), newer analyses have changed the classification of those bones to sheep/goat (cf. Flores 1999: 34, and Appendices A and B). Consequently, rather than being common, gazelle burials are now more accurately described as “moderately frequent” among the Predynastic animal burials. The occurrence of the gazelle in the cemeteries of the Naqada culture indicates that it had a special status during this period, something that is also evidenced in the contemporary imagery (cf. Chapter 3 above). It appears to represent a desirable attribute of the afterlife. The most prevalent way to view the gazelle burials is to see the value of the animal in its meat and hide and thus part of the subsistence economy of the period. The later occurrence of mummified gazelles as possible “pets” buried with their owners (cf. above 2.4) also relates to the discussion of the gazelle as a “semi-domesticate”. Whether the gazelle, at this early period, represented a divine force, identified with a specific deity or deities, as is later the case (cf. below 7.2-6), is an open question, given the lack of written documentation. 123 E.g. Mostagedda (Brunton 1937: 57), Ballas (Petrie and Quibell 1896: 16), Matmar (Brunton 1948: 8) and el-Mahasna (Ayrton and Loat 1911: 21). 124 Debono (1950: 234, 1954: 635-637) is uncertain in his identifications of the gazelle bones and his suggestions are tentative. 161 7.2 Gehesty – “The Place of the Two Gazelles” Textual reference to gazelles as a pair is found in the place name Gehesty ( ), “[The Place of] the Two Gazelles”, first found in a number of Pyramid Texts utterances dated to the 6 th dynasty. The name includes an ending commonly read as indicating a dual form, 125 an interpretation reinforced by the Pyramid Text writing of the place name with two gazelles (cf. below 7.2.1). Images of gazelle pairs occur in a number of different contexts in this material. A possible naturalistic background is the tendency for gazelles to graze in pairs during periods of limited grasses (noted in 2.2). This may account for the occurrence of gazelles in pairs in desert hunt scenes (Chapter 4, cf. also Appendices I, II). The aesthetic possibilities for depicting the gazelles in pairs were exploited in the late Predynastic period where a pair of gazelles, positioned back to back is found on a palette (3.5.2). Later this motif is used in relationship to the desert hunt (4.2-4.3), also occurring in the palmette composition with two feeding gazelles and the more subtle occurrence of the two young gazelles in baskets (5.1.1/b.3). That this becomes a distinct motif is illustrated by the examples of furniture decoration cited above (6.4). The symbolic use of the two gazelles is evidenced in the diadem with the two gazelle protome (6.2). Parallelism with the uraei, and their association, in turn, with the Two Ladies, the vulture of the south, Nekhbet, and the cobra of the north, Wadjit, indicate that the two gazelles of the diadem are female. Thus , read as the (The Place of) “the Two Female Gazelles”, fits into a pattern of preferred imagery. Gehesty is cited throughout the history of Egyptian religion as a place associated with the death and resurrection of Osiris (cf. Griffiths 1980: 22). A specific relationship between this place and the goddesses Anukis, Nephthys and Hathor is found in the later material, with evidence that an equation was made between Gehesty and # (Gauthier 1925: 63, 87, Duemichen 1865: Pl. LXV, no. 23), a cult place of the goddess Anukis (Altenmüller 1977: 513), as well as having a connection to (Komir) providing an association with Nephthys (Chassinat 1931: 232). 126 7.2.1 Gehesty in the Pyramid Texts, Old Kingdom There are four utterances in the Pyramid Texts that include references to Gehesty, all of which come from 6 th dynasty versions. 125 Cf. Gardiner 1957: 58, §72-73 for as a feminine dual ending. 126 In the autobiography of Weni (CG 1435, Borchardt 1937: 115-119, Pls 29-30) a toponym traditionally translated as “the Gazelle’s Nose” (e.g. Edel 1981: 10-11) includes a hieroglyph depicting in fact not a gazelle but possibly an addax (cf. above 2.1.4/c, also Osborn 1998: 158, Fig.13-71). 162 In the lengthy Utterance 478 (Pepi I, Merenre, Pepi II, §§ 971a-980c), the ladder to heaven is addressed, and there is an apparent reference to Isis searching for Osiris. 972 a You have come seeking your brother Osiris 972 b His brother Seth has thrown him on his side 972 c on that side of Gehesty In the shorter Utterance 485B (Pepi I, §§1032a-1035c) it is Geb that comes searching for Osiris. 1032 c Geb comes, the moment (of strength) being upon him # His yellow (eyes) are in his face 1033a when he strikes you He examines the foreign lands searching for Osiris 1033 b He found him being put on his side in Gehesty An additional reference to the search for Osiris is found in Utterance 637 (two versions, Pepi II, §1799a-1804b). This time it is Horus that is searching for his father. 1799a Horus comes carrying unguent, He has sought his father Osiris 1799b He has found him on his side in Gehesty In each of these utterances, a god seeks out Osiris who is “on his side” in a place called Gehesty. This information is found in the context of different forms of resurrection: a ladder that reaches to heaven, the defeat of Seth as Osiris is admonished to “stand up”, and being anointed with the unguent of the Eye of Horus. The fourth reference to Gehesty is found in Utterance 574 (Pepi I, §§ 1485a-1491c) addressed to “the tree that encloses the god” ( ). A somewhat obscure text, this utterance equates the tree ( ) with an apparently feminine Djed pillar. There are references to the tree assembling those in the Underworld ( ) and those in the “celestial expanses” ( ) (§1486). Most likely it is the tree/Djed pillar that is referred to as “this peaceful maiden that this ba of Gehesty made” ( 163 §1487c). Although not entirely clear, the utterance appears to equate the tree with the power ( ) that defeats Seth. The spelling of the four surviving references to Gehesty indicates that two of the references retain an association with a gazelle pair, and with a “desert” location. The other two have phonetic spellings, with the determinative clearly indicating a place name. §972c (only Pepi II) §1033b (Pepi I) , §1799b (Pepi II) §1487c (Pepi I) Gehesty in these utterances is thus the place where Osiris fell, was found and resurrected. In Utterance 637, the imagery is that of the transition between tomb and the next life, aided by a female tree/Djed pillar created by a “ba of Gehesty”. It is a place of both death and resurrection. In two of the examples, its spelling indicates a “desert” location. 7.2.2 Gehesty in Coffin Texts, Spell 837, Middle Kingdom Only one reference to Gehesty is found in the Coffin Texts. Spell 837 (CT VII, 37-39) is found on the Theban coffins of Mentuhotep (Cairo 28027=T9C) and that of Amenemhat (Cairo 28092=B10C) from el- Bersheh. The sky opens its doors and Horus and Thoth go to Osiris, so that he may take his place at the head of the Ennead. Gehesty occurs here as the place where Osiris rises up between Isis and Nephthys. Rise up Osiris ! " on your side in Gehesty Isis has your arm, Nephthys has your hand May you go between them To you are given the sky and the earth CT VII, 37q-38a This Coffin Text spell places emphasis on Gehesty as the place of resurrection, introducing Isis and Nephthys as agents that facilitate the transition from death to new life. Given that the Coffin Texts are written in hieratic, the phonetic spellings , are not surprising. 164 7.2.3 Geheset in the Ramesseum Dramatic Papyrus, 12 th dyn. (P. Ramesseum B, British Museum; Sethe 1928 127 ) In 1896 a collection of 22 papyri was found by Quibell in a Middle Kingdom shaft tomb, located in the western part of Ramesseum. Among these papyri was the so-called Ramessum Dramatic Papyrus that was acquired by the British Museum in 1929. It is generally interpreted as a description of either the coronation of Sesostris I (c. 1956-1911 B.C., Shaw 2000: 480), whose name occurs in the text, or as a ritual for a statue of that king. The text relates the ‘drama’ of the royal enthronement, with allusions to the death of Osiris and the conflict between Horus and Seth and to the Sed Festival. It has been debated as to whether the papyrus is an updated version of an older ritual text, with some dating it to as early as to transition between the 2 nd and 3 rd dynasties (Altenmüller 1975: 1139). The place name Geheset ( ) occurs in the last preserved scenes (45-46). The text begins with the bringing of a cake (of natron) and a vessel (of water) to the palace and most likely to an Osiris figure. This is followed by an admonishment “Don’t give to Gehest(y) the place where his father Osiris fell” (Sethe 1928: 240, columns 136-139, Pl: 22). Sethe interprets this text as setting up an opposition between the palace where the offering is taken, and the Place of the Gazelle (cf. 242, n. 137c) where Osiris fell, saying that Osiris is not to be found where he fell, but is resurrected in the palace. This reiterates the negative connotation associated with Gehest(y) as the place where Osiris was murdered found in the Pyramid Texts. 7.2.4 The stela of May, 19 th dyn., Seti I (Brussels, E. 5300; Speleers 1921:113-144) The stela of May is inscribed with a lengthy hymn to Osiris, a large part of which corresponds to Chapter 181 of the Book of the Dead (cf. Faulkner 1990: 180-181). This text has a number of parallels, only one of which, the stela of Tournaroi (cited by Speleers 1921: 123), also refers to Gehesty. The hymn consists primarily of a series of epithets describing Osiris. Among them is a reference to the praise he elicits from all beings, living and dead. (the one) to whom people, gods, Akhu and the dead have come bowing for whom multitudes in Gehesty shouted 127 Gardiner (1955: 8) described the papyrus as “very cryptic”, referring to Sethe’s 1928 publication of the text. 165 for whom those who are in Duat rejoice This citation, from columns 11-12, indicates a parallelism between Gehesty, (written in the May version and in the version on the stela of Tournaroi) and the Duat. The Coffin Text passage discussed above has a division of roles between Nedit as the place of death and Gehesty as the place of resurrection. This kind of relationship between Gehesty and the Duat would be expected here, as a way of expressing the came entirety found in the combination of “people, gods, Akhu and the dead” found in the lines above. In which case, Gehesty would represent the place of the “living” (or reborn) contra that of the deceased in the underworld of the Duat. 7.2.5 Khnum, Lord of Gehesty, 21 st dyn. Khnum, the ram headed god, worshipped primarily at Elephantine but who is also part of the larger Egyptian pantheon is given the epithet “Lord of Gehesty” 128 in two chapters of a 21 st dynasty version of the Book of the Dead. An additional example of the connection between this god and Gehesty is found in the temple of Dendera. The example of the Book of the Dead discussed here was found in the royal cachette (TT 320, Bab el-Gasus) and belongs to a woman called Neskhons, who bears the title priestess of Khnum ( ), an association that may explain the exceptional inclusion of references to Khnum. The first occurrence is found in Chapter 17 (Naville 1912: Pl. XIII, 8) and the second in Chapter 112 (Naville 1912: Pl. XXII, 12). In both chapters Khnum is titled ! " . In the example from Chapter 17, is written with the two standing gazelles drawn clearly and distinctively. The writing from Chapter 112, shows two recumbent gazelles. There is no apparent explanation for the reference to Khnum other than the owner’s affiliation to his cult, nor is it clear what the association with Gehesty implies. The next known reference to a connection between Khnum and Gehesty is dated to the Greco-Roman period. The epithet Lord of Gehesty ( ) occurs again in the temple of Dendera. It is found in the context of the cult of the four living rams (bas). This cult was celebrated primarily at Elephantine and Esna, as well as being documented at the Hathor temple at Dendera (Otto 1975b: 953). The fours rams represent the four gods Re, Shu, Osiris and Geb. Khnum, associated with Shu, is called Lord of Biggeh, as 128 This epithet is not included for Khnum in LGG VI, 15a-34a. 166 well as Lord of Gehesty (Brugsch 1871: 83). Biggeh, a small island next to Philae, was the burial place of Osiris, and thus possibly analogous to Gehesty in function. The association with Khnum, who is in essence a creator god, with Gehesty, would then appear to relate to its role as the place of burial, and possibly resurrection of the god. 7.2.6 Sarcophagus of Pa-di-sema-tawy, 26 th dyn. (Cairo, JE 31566; Rowe 1938: 157-195) The text found on a sarcophagus belonging to Pa-di-sema-tawy continues the trend of placing Gehesty in the framework of the death and resurrection paradigm. The sarcophagus, belonging to a general in the army of Psamtek II, was found at Kom Abu Yasîn (in the eastern Delta, near Horbeit, cf. PM IV: Map I, G 4). Another sarcophagus from the same date and location has a similar inscription (Daressy 1898: 78). The text of interest is found on the sarcophagus lid. It is divided into three sections and once again refers to the death and resurrection of Osiris. Following convention, Isis is found at the foot end where she assures the coffin owner, as Osiris, that she is at his legs, watching him, protecting him from drowning. The central text is that of Nut who is said to extend herself over the dead, making him a god with no enemies, protecting him from all evil things. It is the text that is found at the head end of the sarcophagus lid that is of interest. As is customary, here it is Nephthys that is featured. - O Osiris Pa-di-sema-tawy Your sister Nephthys comes to you, ! " ! " the sister who is in Geheset(y) 129 She raises your head for you # # She collects your bones for you She assembles your limbs for you. The association between Gehesty and Nephthys 130 found here reiterates the emphasis on resurrection, found in the Coffin Texts citation. 129 According to Rowe (1938: 181, n.3), this verb should be read and not . 130 Lengthier versions that describe Nephthys collecting the pieces of the body of the deceased (‘Osiris NN’) are found on at least three other contemporary coffins in the Egyptian Museum in Cairo (i.e. CG 41002, CG 41006, CG 41007, Moret 1913: 44, 95, 102; cf. also CG 41044, Gauthier 1913: 32). There are similarities in the description of the assembling of the body together with PT Spell 637 (§ 1801a-c) and CT Spell 837 (discussed above). 167 7.2.7 Papyrus Jumilhac, Greco-Roman Period (Louvre, E. 17110; Vandier 1961) The toponym occurs fours times in the late Ptolemaic-early Roman (Vandier 1961: 1, Rössler-Köhler 1982: 708) papyrus known as Papyrus Jumilhac. Currently consisting of 23 “pages” 131 of well formed hieroglyphs written in columns, the text of this papyrus is accompanied by vignettes, with some Demotic commentary along the margins. The papyrus appears to be a ‘handbook’ for the clergy of the 17 th and 18 th Upper Egyptian nomes, describing local religious traditions (Rössler-Köhler 1982: 709). The texts found on this papyrus are largely mythological in nature, relating a version of the narrative of the death and resurrection of Osiris that features a form of Anubis that had become closely associated with Horus in local tradition. The episode in which two references to Geheset are found, involves the role played by Isis in protecting her dead husband from Seth and his cohorts. The goddess actively pursues Seth and while doing so transforms herself, first into the ferocious lioness Sakhmet, then into a dog ( ), with a knife-like tail and finally into a serpent ( ), in which guise she is associated with Hathor. $ % Then she went north of the nome. She transformed herself into a serpent # She entered into this mountain to the north of this nome to watch the confederates of Seth when they went out at night It is said of her “Hathor Mistress of Geheset” (Jumilhac III, 7-8) The goddess continues to watch the allies of Seth and then she strikes. And then she was angry at all of them # She put her venom in their limbs They fell immediately and at once Their blood fell on this mountain $ % and became juniper berries on Geheset. (Jumilhac III, 10-12) 131 The papyrus was probably cut up by Sabatier into these 23 sheets, who is reported to have been the first ’owner’ of the papyrus, later inherited by Jumilhac (Vandier 1961: 1). 168 The last text section of the papyrus is given the title “Geheset” by Vandier (1961: 134, XXXVIII). It repeats the narrative of the transformations of Isis, adding further elaborations. Regarding Geheset, 132 h, Nephthys was there at her side. The companions (of Seth) passed by her without their knowing And then she bit them all. She threw her two lances at their limbs. Their blood fell on this mountain, flowing and their death happened immediately (Jumilhac XIII, 10-15) This passage gives the wordplay that connects the juniper berries ( ) on the Geheset mountain with the flow ( ) of blood. The final reference to Geheset is found in a part of the text, treated by Vandier as a subtext, accompanying a vignette. Found on the lower part of sheet IX, and designated Section XLVII, the text begins by describing the gods buried in the necropolis of Geheset “Beginning with Shu, continuing with Osiris and ending with Horus, son of Isis” ( IX, 1-2" The text continues to list the gods buried there, including Hathor of Geheset (IX, 6). In discussing the Geheset found in this text, Vandier (1961: 53) described it as “une existence réelle”, with a cultic relationship as the site of the temple of the uraeus (XXIII, 12) to Hathor of Geheset. It is evident that Geheset in Papyrus Jumilhac has a mythic status that is somewhat different from that found in earlier texts. It is the place where Isis, as Hathor, defends Osiris against Seth. Horus is curiously absent in this version, rather it is Isis-Hathor that has the role as defender of Osiris. Appropriately enough she vanquishes Seth in the form of a serpent ( ), 132 With the variant spelling . 169 with the implication that she is really the uraeus, since Geheset is the site of the temple of the uraeus. Geheset in Jumilhac is where Isis transforms herself into forms associated with the solar eye (cf. below 7.4), as well as being the final resting place of the gods. 7.2.8 Gehesty – concluding remarks Gehesty, the Place of the Two Female Gazelles, reoccurs as an important place in the Osirian myth for a period of over 2000 years. From being the place where Osiris was sought, found and resurrected in the Pyramid Texts, Gehesty becomes primarily a place of resurrection in the single reference in the Coffin Texts and possibly in the hymn to Osiris on the stela of May. Similarly, associated with Nephthys on the head end of the sarcophagus of Pa-di-sema-tawy, there is the implication that Gehesty is where the dead rises. The Jumilhac evidence gives a slightly different focus to Geheset in its association with the transformations of Isis-Hathor and the defeat of Seth and his companions. Here it is the place where violent forms of this goddess defeat the forces of chaos and rather than being a “desert” ( ) landscape, it is specifically a mountain ( ), also a place apart from the ordered life of the valley. When identified as a real cult place, Geheset has been linked to , the Komir of today. The centre of the worship of Nephthys in Greco- Roman times, it is also the site of the gazelle catacombs (cf. below 7.3.4). An alternative location that is suggested is # (Gauthier 1925: 63, 87), a cult place of the goddess Anukis (Altenmüller 1977: 513). 7.3 The gazelle at Wadi Hammamat, 11 th dyn., Mentuhotep IV (M 110, Couyat and Montet 1912: Pl. XXIX; 1913: 77-78) The naturalistic images of the gazelle in tomb and temple reliefs have a textual counterpart in the well known Wadi Hammamat inscription of Mentuhotep IV. A series of five inscriptions, inscribed on the cliff walls, relate events of a quarry expedition of the 2 nd year of the reign of this king. 133 The purpose of the expedition was to quarry blocks for the royal sarcophagus and its lid. The narratives are linked sequentially by the dates of the texts, covering a period of 25 days of the second month of Akhet. Day 3 The miracle of the gazelle (M 110) Day 15 Fetching the blocks (M 113) 133 For an overall discussion of these texts see Blumenthal 1977: 106-107, Gundlach 1980: 112 and Shirun-Grumach 1993: 5, 18. 170 Day 15 Raising the stela to Min (M 192a) Day 23 The miracle of the well (M 191) Day 28 The sarcophagus blocks are taken to Egypt (M 192b) These texts, “signed” by the vizier Amenemhet, generally taken to be the successor of Mentuhotep IV, and the first king of the 12 th dynasty (c. 1985-1956 B.C.) add the miraculous to the task of quarrying the stone that will, as sarcophagus, aid in the creation of a royal Osiris. The miracle of the gazelle marks the regenerative quality of the stone itself. The text narrating the miracle of the gazelle (M 110, Couyat and Montet 1913: 77-78; 1912: Pl. XXIX) is incised on a square block. A scene accompanies the text, showing Mentuhotep IV offering two milk jars to Min the Coptite (Gundlach 1980: 99). The text relates the appearance of a pregnant gazelle at the quarry site. This miracle which happened for his majesty The animals of the desert came down to him. And the pregnant gazelle came, walking her face was toward the people before her. Her two eyes looked straight ahead. She did not turn back until she arrived at this noble mountain to this block. It was in its place for this lid of this Lord of Life. She gave birth on it. This army of the king looked on. And then her throat was cut, being put on it as a burnt offering. Lines 2-6 After the offering was made the block was brought down from the quarry and homage was paid to Min, Lord of the Desert ( ). The block of stone that was to become the lid of the sarcophagus is identified by the gazelle giving birth on it. This event is described as a miracle ( ) for his majesty, relating to the generative properties of the sarcophagus to be sculpted from the block. The sacrifice of the gazelle also provides an example of what has been deduced regarding the gazelle as offering from the offering processions (cf. Chapter 5 above). The sculpting of the sarcophagus from the block is implied in M 113 (Couyat and Montet 1913: 79-81; 1912: Pl. XXIX) that describes the purpose of the expedition and the craftsmen (“sculptors, draughtsmen, metal-workers, 171 gold-workers”) included in the expedition. Another text (M 192a, Couyat and Montet 1913: 98-99; 1912: Pl. XXXVII) dated to the same day, the 15 th , is devoted to the erection of a stela, dedicated to Min, and provides further information on the composition of the expedition drawn from several regions of Upper Egypt. Some 20 days after the gazelle gives birth on the block at the quarry, another miracle occurs, described in M 191 and known as The Miracle of the Well (Couyat and Montet 1913: 97-98; 1912: Pl. XXXVI). A more difficult text, with different proposed translations (cf. e.g. Schenkel 1965, Gundlach 1980 and Shirun-Grumach 1993), the miracle of the well has some elements that appear to be an extension of the miracle relating to the gazelle ( ). While working on the block on which the gazelle gave birth, it begins to rain. the desert was made into [a] flood, the water rising to the edge of the block 134 ! " a well was found in the middle of the valley… Column 3 The imagery of the block is that of an island in the midst of rain water. The underlying theme of the gazelle episode is repeated here, as the block intended for the sarcophagus emerges from the flood, and rock opens up as a well in a way reminiscent of the stories that place the source of the Nile in two caves located at Elephantine (# , Pécoil 1993: 97-102; van der Plas 1986: 176). The final episode, dated to day 28, (M 192b, Couyat and Montet 1913: 99-100; 1912: Pl. XXXVII) tells of the celebrations that accompanied the completion of the lid. It is then taken to Egypt proper by 3000 soldiers from Lower Egypt. The reference to “Egypt” as the destination for the block marks the quarry area as foreign, desert, territory. This group of texts centres on the procurement of a sarcophagus for the king. The reference to the lid as the place where the gazelle gives birth reflects both the form of the block, as a slab suitable for the purpose and the future properties of the lid, where the image of the goddess Nut, the mother that will give the deceased new life, will be inscribed. The gazelle, as an animal of the desert landscape where the quarry is found, fits into the realistic level of the narrative. It also carries with it certain allusions, such as the imagery of the desert hunt, implying the mastery of this landscape, and the 134 Cf. Faulkner 1962: 136 for the translation of as “dry rock (?)”. Schenkel (1965: 268) suggests that the translation should read to mean that water was flowing from the rough surface of the stone. 172 idea of resurrection that, as has been shown, is found in the identification of Gehesty, where Osiris is found and given new life. The addition of the miracle of the well, introduces another level with an oblique reference to the original and repeated creation through the flood of waters, with the lifeless desert being given new life. While relating a seemingly practical expedition to a quarry, these small texts imbue this activity with mythological implications. 7.4 The gazelle and Anukis The gazelle, while rarely functioning as the pictorial manifestation of a goddess, is documented in a few sources as an attribute of Anukis (Otto 1975a: 333). All of the evidence dates to the New Kingdom and is mostly concentrated to western Thebes (Valbelle 1981: 117, 124). The written material provides one example where Anukis is explicitly associated with the gazelle. It is found in the texts from the temple of Esna, dated to the 1st century A.D. Here Anukis is called “lady of the gazelle” ( cited by Valbelle 1981: 132 and Sauneron 1968: 230, no. 312, 7, cf. below). The late date of this epithet suggests the need for caution with regard to the significance of the gazelle in understanding Anukis in earlier times. It is worth noting that this relationship is not found in the epithets collected by Leitz (cf. LGG II, 172b - 174a). 135 7.4.1 A relief from the temple of Buhen, 18 th dyn. (PM VII: 133, Caminos 1974: Pl. 20) A relief on one of the pilasters in the southern temple of Buhen depicts Anukis giving life to Tuthmosis III, holding an ankh-sign to his nose. Anukis embraces the king with her other arm. The goddess is identified by her plumed head dress. Similar compositions with Anukis holding the ankh-sign to the king’s nose can be traced back to the Middle Kingdom, featuring e.g. Sesostris III and Neferhotep (Habachi 1950: Figs 1, 2). The hieroglyphic inscription on the pilaster is fragmentary, yet the remaining traces suggest the standard phrase “giving life, stability and dominion”. Behind Anukis a small graffito “incised rather deeply” (Caminos 1974: 21) has been added. The horns are curved inwards, 136 the legs slender and the short tail points upward. 135 However, some of the other gazelle related epithets and references occur under the heading of / , with a selected bibliography (LGG VII, 324c). 136 Short horns that curve inwards are a typical feature for female gazelles (cf. Osborn 1998: 175). 173 These anatomical details are specific for the gazelle (Osborn 1998: 175). The animal is furthermore standing on an individual base line, thus serving as an iconographic comment to the goddess. This represents perhaps the earliest known example of Anukis associated with the gazelle. As it is difficult to establish when the gazelle graffito was incised, it is possible that it is of a later date than the 18 th dynasty. Yet, the motif suggests an awareness of the iconographic link between Anukis and the gazelle. Figure 78. Anukis giving life, a gazelle graffito is behind her 7.4.2 The tomb of Neferhotep, TT 216, Deir el-Medina, 19 th dyn., Ramses II – Seti II (PM I/1: 313 (6), Davies 1923: 52, Fig. 20) Figure 79. Neferhotep’s ‘garden’ of gazelles, with a nursing scene 174 From a period when the desert hunt is no longer included in the standard tomb decoration, an unusual scene is found in the tomb of Neferhotep, depicting an undulating landscape with various plants, trees and waterways, possibly indicating an island landscape. As many as eight gazelles walk around the area, with one, in the lower left of the scene, nursing her young. The heading for this representation is cited (PM I/1: 313) as the “Temple in grove of Anukis with gazelle on Island of Elephantine.” Anukis herself is however not present. This scene is not analysed by Valbelle (1981: 30), other than describing it as a garden with gazelles: “animaux sacrés d’Anoukis”. A similar comment is made by Bruyère (1926: 36) referring to a “parc d’antilopes d’Anoukit à Èléphantine”. It is apparent that both regarded the content of the scene as self-evident. Even though this scene is considered unique (Davies 1923: 51-52), no further discussion of this scene appears to have occurred (cf. Kampp 1996: 494-496). This ‘silence’ indicates perhaps how enigmatic the motif is. Anukis is primarily mistress of the island of Sehel (Valbelle 1981: 94), and is associated with the cataract area. There are however a few New Kingdom examples of Anukis as , ‘lady of Elephantine’ (de Morgan et al 1894: 7). Satis, often found together with Anukis in a triad with Khnum (e.g. Habachi 1957: Pl. VIII, Inscr. 27; de Morgan et al 1894: 93, dM 132, 96, dM 153) remained nevertheless the main goddess of Elephantine (Valbelle 1981: 106-107). The rich vegetation and the calm attitude of the animals in this scene should be compared to the barren landscape and pursuit theme of the desert hunt (Chapter 4), suggesting that this is an idealized image of the cult area of this goddess, where possibly a herd of her sacred animal the gazelle was kept. 7.4.3 Two ostraca from Deir el-Medina Two ostraca, both originating from Deir el-Medina, further confirm the connection between Anukis and the gazelle, both in iconography and text. These examples represent the most explicit sources known to link the goddess with this animal. a. A votive for Anukis (Stockholm, Medelhavsmuseet, MM 14011; Peterson 1973: Pl. 19) An ostracon now in the collection of Medelhavsmuseet in Stockholm features a seated Anukis, with two recumbent gazelles in front of her. The goddess is found to the left, holding a staff in one hand and an ankh-sign in the other. 175 An offering table separates the animals from the deity. The inscription in front of her reads # , ‘Anukis, mistress of Sehel’. The title mistress of Sehel is established from the Middle Kingdom onward (Valbelle 1981: 107), with occurring as the determinative for the toponym The inscription above the gazelles reads , which translates as ‘wild gazelle’ or possibly ‘small gazelle’. Peterson (1973: 77) suggests that these two gazelles may have referred to Gehesty (cf. 7.2). Traces of an inscription along the lower edge read /// ///, ‘…hearing the summons (?) in the Place of the House of Truth, Amen-em-ipet ///’. 7.4.3/b Giving praise to Anukis (Cairo, JE 43660; Quaegebeur 1999: 22, Fig. 14). The second ostracon is found in the Egyptian Museum in Cairo. To the left is the royal scribe Hay, kneeling and with his hands raised in an adoration position. A lavish offering table is in the middle of the scene. To the right a gazelle strides forth from the mountains, facing the offering table and Hay. The inscription above the scene is divided into two sections; one describing Hay and the other the gazelle. Daressy published a complete transcription of the text (1919: 77), beginning with the inscription above the offering table and the kneeling Hay. # Giving praise to Anukis is that which the royal scribe 137 in the Place of Truth Hay, justified ' and Saamunnakht, justified, son of his son did. The text above the gazelle reads ‘an offering which the king gives Anukis, lady of the sky, mistress of the gods’ ( # ), clearly identifying the gazelle as Anukis. The motif of a gazelle emerging from mountains is analogous to that of Hathor striding forth from the western mountains, in her role as the lady of the west and the protector of the deceased (Hornung 1990: 58-59). 137 Cf. Ranke 1935 PN 1: 232, 8 for the transliteration of the name. 176 Figure 80. Anukis and the two recumbent gazelles Figure 81. Hay adoring Anukis in the shape of a gazelle 177 7.4.4 The One who Dwells in Komir ( ! " ) The relationship between the gazelle and Anukis, first documented in the New Kingdom, is reflected in some of the deity’s titles. The title ! " , ‘the one who dwells in Komir’, is inscribed on a temple wall of the Khonsu Temple at Karnak dating to the 19 th dynasty (Helck 1968: 121). This confirms that Anukis was connected to Komir as early as the New Kingdom (Gomaá 1977: 684). This site is situated ca 12 kilometres south of Esna, on the west bank of the Nile. This association is maintained until the Roman Period when one of Anukis’ titles is , ‘mistress of Komir’, found on the north inner wall of the temple at Esna (Sauneron 1975: 119, no. 516, 6). Sauneron (1975: 119 n. b), pointed out that this title has a parallel in another scene on a pillar at the same temple where however, has been replaced by , ‘mistress of Geheset’, written with a gazelle standing on a standard (Sauneron 1968: Esna III, 230, no. 312, 7). This equates with (Gauthier 1928: 219, cf. above 7.1). Blocks once forming a part of a Ptolemaic Period temple at Komir further confirms that is an alternate place name for (cf. Valbelle 1983: Fig. 9, column 17). These inscriptions connect both Anukis and Nephthys to the toponym . 7.4.4/a The gazelle cemetery at Geheset / Per-merw A necropolis that includes several catacombs used for the burial of gazelle mummies is located in a desert area some three kilometres south of Komir. It has been dated to the Greco-Roman Period (Lortet and Gaillard 1903: 78-81, Gaillard and Daressy 1905: 13). Other animals, such as the ibis and the baboon, were kept in large numbers as cult animals that were purchased to serve as mummified messengers to the deity. This suggests that gazelles may have been kept for a similar purpose, and thus been a part of a temple complex in which gazelles were treated as sacred animals. The mummified gazelles found in the Komir necropolis were wrapped with the limbs tucked under the belly (Lortet and Gaillard 1903: 78-79, Figs 42- 43) in a position reminiscent of the recumbent gazelles in the two and three dimensional depictions (contra the shape of the ‘standing’ gazelle mummy of Isetemkheb D, TT 320; cf. above 2.4). Many of these gazelle mummies were reported to be female (Lortet and Gaillard 1903: 82). The overall mummification technique is described as poor (Lortet and Gaillard 1903: 78, 81, Gaillard and Daressy 1905: 12), which is a common feature ascribed to the votive mummies. In contrast to other animal votive mummies, the embalmed gazelles do not seem to have been equipped with any written 178 messages to a deity. The function of the votive mummies is not fully understood, but it is suggested that they communicated with the deity for whom they were regarded sacred (Ikram 2003a: 90). In addition to Komir, a few gazelle mummies have been located in Kom Ombo, Dendera, Thebes, Hermopolis and Saqqara (Kessler 1989: 18-26), indicating a widespread but exclusive practice of mummifying gazelles during the Late Period. In a Demotic lease contract from Thebes (c. 227-175 B.C.), a reference to a tomb of gazelles among the tombs of “Memnoneia” (Clarysse 1978: 234) is made. The document concerns the position of certain tombs, described as located next to the road of Amun and mentions “the house of the gazelles” (Papyrus Philadelphia XXIV, El-Amir 1959: 110- 113). The so-called Philadelphia Archive was “found in a corner of a Ptolemaic house… at Dra c -Abu-el-Naga” (El-Amir 1959: 65, n. 1). Carnarvon and Carter excavated a site with Ptolemaic vaulted tombs at Dra Abu el-Naga (Carnarvon and Carter 1912: 49-50, PM I/2: 611) and at this site a few clay shrines, one of them containing “the bones of a gazelle”, were found (Carter 1912: 50, Pl. LXII, 2). The question remains whether the small shrine with its arched opening is the referred to in P. Philadelphia XXIV. 7.4.5 A Demotic funerary text, Roman Period (P. dém. Louvre N 2430c, Chauveau 1990: 3-8) An enigmatic Demotic papyrus, dating to the Roman Period (P. dém. Louvre N 2420 c, Chauveau 1990: 3-8), with a suggested Theban origin, illustrates the connection between antelope and goddesses. $ % Receive her, O westerners O deceased ones of the Hall of the Two Truths Because it is a young one (?) They will give to her a place in the West # They will pour libation water for her (on) the offering table after (pouring libations for) Isis and Osiris $ % She will find Hathor in the West sitting on a bed ! " while the antelope, the gazelles, (the) deer (and) the wild game of the desert 179 are on the ground before her saying: (5) "Is this our mother, our mother?" In this short text, the inhabitants of the afterlife (the “West”) are asked to receive a young woman or child so that she might enjoy the benefits of a funerary offering. Filled with errors, and with no parallels to assist in the reading, the meaning of the text is difficult to comprehend. It is however clear that the text places the gazelle and other antelopes in the context of the necropolis as desert animals. The relationship with Hathor, as the presumptive “mother” of these animals, adds an additional level of divine association. 7.4.6 The gazelle and Anukis – concluding remarks The connection between the gazelle and Anukis is confirmed in a limited number of sources from the New Kingdom. Anukis is further related to Komir, where a gazelle cemetery was located. The role of Anukis is perhaps best understood via other goddesses, such as Hathor as Lady of the West, protecting the deceased and Nephthys’ role in Gehest(y). This relates the connection between the gazelle and Anukis to the (western) mountains and regeneration. Further, this review of the evidence reveals that the association between Anukis and the gazelle is not as prevalent as previously suggested (e.g. Valbelle 1981). 7.5 The gazelle and the divine eyes The imagery of the divine eyes of the gods Horus and Re plays an important part in Egyptian mythology. The two texts discussed here place the gazelle in the context of first the eyes of Horus and then in relation to the goddess Tefnut, in the role of the Solar Eye. The Eye of Horus is one of the central elements of the myth of Osiris. Taken from Horus and damaged by Seth during their struggle for the throne, it is returned to Horus after it was being made whole. At that point, Horus gives the Eye to his father Osiris, who thus completes the resurrection process becoming the king of the dead in the Underworld. The Eye of Horus thus becomes an icon for all offerings to the dead (Assmann 2001: 49-50). The Solar Eye, daughter of Re, is a divine form that is associated with a group of goddesses that can occur in the form of the lioness Sakhmet and has associations with the fire-spitting uraeus. The most prominent among these goddesses is Hathor, who appears in the role in the well known story 180 given the title “Destruction of Mankind” (cf. e.g. Lichtheim 1976: 197- 199, with reference). This and related tales tell of how the goddess runs off, and ends up beyond Egypt’s border in a foreign ( ) land. She is eventually enticed back, giving cause for celebration with the Festival of Drunkenness ( Sternberg-El Hotabi 1992: 101-102). The transformations of Isis, described in Papyrus Jumilhac (cf. above 7.1.5) is one example of a goddess in the Solar Eye mode. Although the two stories discussed below deal with different aspects of divine eyes, they share a basic theme, regeneration and the renewal of the kingship. 7.5.1 The Contendings of Horus and Seth (Papyrus Chester Beatty I, 1:1-16:8; Gardiner 1931: 8-26, Pls 1-16; cf. Broze 1996) The story of the conflict between Horus and Seth, how it began and how it ended, is found on Papyrus Chester Beatty I, dated to the reign of the 20 th dynasty king, Ramses V. The myth that it relates, it has been argued, can be traced back to the Middle Kingdom (Broze 1996: 3). Introductory lines establish the focus of the tale as the trial that is to judge which of the two gods, Horus or Seth, is the true heir of Osiris. A series of events leads to the escalation of the conflict between Horus and Seth. In the episode of interest here, Seth deprives Horus of both of his eyes, while he lies under a tree in an oasis. As for Horus, [ ] he was lying under a shenusha-tree in the oasis country. The Seth found him, ! " and he seized him, ! " and threw him on his back on the mountain. 2 He removed his two sound (eyes) from their places and buried them on the mountain 2 Toward morning his two eyeballs 2 became two bulbs and they grew into lotuses. And then Seth came to him and told Pre-Harakhti falsely: “I did not find Horus”, although he had found him. 181 Then Hathor, mistress of the southern sycamore, went and she found Horus $ % as he lay weeping in the desert Then she caught a female gazelle and milked it, and said to Horus: “Open your eye, that I may put milk there.” He opened his eye and she put the milk there She put on the right (eye), she put on the left (eye); And she said to him: “Open your eye(s)!” He opened his eye(s). She looked at him, ! " she found them healed. Then she went to speak to Pre- Harahkti: ! " “I found Horus, Seth had deprived him of his eye(s) but I restored him again.” Lines 10,1-11 (Gardiner 1932: 50-51) Predating Papyrus Jumilhac by some 1000 years or more, still there are elements in this episode that tie the two together. In Papyrus Jumilhac, as in this narrative Isis intervenes on Horus’s behalf and transforms herself. And here, as in Jumilhac, Isis and Hathor combine efforts. The crux of the story however is found in the injury to the eyes of Horus, a central element of the Osirian myth. In other versions, the wounded eye, stolen by Seth, is healed by Thoth (Griffiths 1960: 29, 82; cf. also Book of the Dead Chapter 17). Here it is the milk ( ) of the gazelle ( ) that heals both eyes ( ). As in Jumilhac, the location is a mountain ( ). And indeed the presence of the gazelle may allude to the toponym Gehest(y), lending connotations of regeneration to this part of the story. 182 7.5.2 The gazelle in the Myth of the Solar Eye The Demotic text known as the Myth of the Solar Eye (Pap. Leiden I 384, recto), dated to the early Roman Period, gives a clear example of a goddess, in this case Tefnut, in that role. The premise of the story is that Tefnut has left Egypt in anger and must be persuaded to return (Smith 1984: 1082-1083). Thoth is sent to Kush where the goddess has fled to cajole her by entertaining her with stories. 138 Tefnut begins the journey back to Egypt, but must take on the forms of different animals in order to escape her father’s enemies. Somewhere between el-Kab and Thebes Tefnut transforms herself into ‘a female gazelle’ ( # Pap. Leiden I 384, recto 21, 7-10; de Cenival 1988: 64). Her arrival in Thebes is greeted with a song, and she is further described as the ‘(female) gazelle of the mountain’ (# , Pap. Leiden I 384, recto 21, 22; de Cenival 1988: 66). Tefnut it is surmised is eventually reunited with her father Re in Heliopolis. Both the beginning and the end of the papyrus is missing however, so the “conclusion of the myth is lost” (Smith 1984: 1084). Tefnut takes on other forms on this journey. She transforms herself into a vulture ( ) when in el-Kab (Pap. Leiden I 384, recto 21, 3; de Cenival 1988: 64). This is logical considering that El-Kab was a cult centre for the vulture goddess Nekhbet. This suggests that the gazelle form may have had special interest for Thebes, although there is nothing specific to support that. What is most interesting with the information from the Myth of the Solar Eye is that it provides evidence for the gazelle as a form of the female Solar Eye. 7.5.3 Additional references to the myth of the Solar Eye References to the myth of the Solar Eye have been found in a number of temples dated to the Greco-Roman Period (e.g. Philae, Dendur, Kom Ombo, Esna, Edfu, Dendera, cf. Junker 1911 and Inconnu-Bocquillon 2001). An example of the inclusion of the gazelle in this context is found in a song inscribed on a pillar in the Hathor temple at Philae (PM VI: 251 (g)-(l); “deuxième colonne du Sud” (Daumas 1968: 9, § 18). The inscription is part of a chant that urges the gazelle to come down to Egypt, “Coming down to Egypt, the female gazelle of this desert/mountain’; 139 (Junker 1911: 46, Daumas 1968: 10). The writing 138 Cf. Smith (1984: 1083) for this identification of Thoth as 139 Cf. Daumas (1968: 10, n. 65) on the spelling of the word mountain as versus during the later periods (also Wb V: 545). 183 “desert/mountain” implies a pun with the place name for Komir (cf. above 7. 3.4). The reference to “coming down to Egypt” parallels the events related in the Demotic Myth of the Solar Eye, and is a strong indication that the female gazelle is not merely an additional detail in the Demotic text but incorporated into the imagery of that myth and that the Solar Eye, daughter of Re, has, as one of her forms, a female gazelle from the desert mountains. 7.5.4 The gazelle and the divine eyes – concluding remarks The two stories cited add additional levels of evidence regarding the relationship between the image of the gazelle and divinity. The earlier tale “the Conflict of Horus and Seth”, juxtaposes the gazelle with Isis and Hathor. The scene is that of the mountainous desert where Horus lies helpless having been blinded by his uncle Seth. Gazelle milk, with its connotations of motherhood and thus associated with Isis, is the healing agent. This combination of elements creates an analogy with the death and resurrection of Osiris. The regeneration of the eyes builds on that analogy as they become bulbs that bloom on the mountainside. The gazelle in this context is the mother that facilitates a solar “rebirth.” The Myth of the Solar Eye has another focus. Although Jumilhac provides an example of the protective power of this category of goddess, the Myth of the Solar Eye deals with taming the wild daughter so that she will return to her father. The inclusion of the gazelle in this context suggests that the analogy seen between the gazelle and e.g. the uraeus is more than a question of the aesthetics of adornment. Rather, it has a follow through in the place given the gazelle as a manifestation of the Solar Eye. 7.6 Isis and the gazelle in Roman times It is a Latin source that provides one of the last glimpses of the relationship of the gazelle to the divine. In one of the first natural histories, De Natura Animalium, Aelian (c. AD 175 - 235) describes the worship of Isis at Coptos. Focussing on the relationship of this goddess to the scorpion, the passage concludes with a reference to the gazelle. At Coptos in Egypt the natives pay homage to Isis in a variety of rituals but especially in the service and ministry rendered by women who are mourning either a husband or a son or a brother. And at Coptos there are scorpions of immense size, possessing very sharp stings, and most dangerous in their attack (for when they strike they kill instantly), and the Egyptians contrive innumerable devices for self- 184 protection. But although the women in mourning at the temple of the goddess sleep on the floor, go about with bare feet, and all but tread on the aforesaid scorpions, yet they remain unharmed. And these same people of Coptos worship and deify the female gazelle, though they sacrifice the male. They say that the females are the pets of Isis. De Natura Animalium XI, 23 (Schofield 1959: 315-317) This source presents an observer’s view of the remnants of Pharaonic practices and beliefs. Some of what is described can however be related to known phenomena. The magical power of Isis over the scorpions is noted in the text from the Metternich stela and in her role as Hededet (Meeks 1977: 1076). The preference for the female gazelle, and its role as a pet has been discussed above, while the fate of the male reflects a general tendency to polarize the genders, with the male representing a hostile force (cf. e.g. the red and white hippopotamus, Säve-Söderbergh 1953: 47-52). 7.7 The gazelle and the divine – concluding remarks Expressions of the relationship between the gazelle and the divine are found within a limited but consistent range. Two themes stand out. The first of these is the characterisation of the gazelle as a desert animal that thus represents the role of the desert in mythic thought. The other is the way in which the gazelle is integrated into the complex of ideas represented by female duality and transformation. The combination of these elements brings a focus on the process of resurrection, particularly as a form of rebirth and healing. The gazelle is thus an additional image that manifests some of the most fundamental concepts and paradigms in ancient Egypt. The “desert mountains” as a place with inherent regenerative qualities is encountered in the concept of Gehesty (7.2). The earliest sources consider it to be the place of the death and restoration of Osiris. This resurrection could also (obliquely) apply to the enthronement of the pharaoh (7.2.3). As a “real” place, it is connected to (Komir). ( during the Late Period appears to have been an alternative spelling to the desert mountains ( ). The connection between the gazelle and divinity in a desert setting is implied by the naturalistic setting of the decoration of the funerary D-ware (3.2). This is repeated in the imagery of the desert hunt scene (Chapter 4) that is given an established place in tomb decoration. The so-called Miracle of the Gazelle (7.3), that takes place in a desert quarry, echoes the role of the desert as a place with rejuvenating qualities. These are then emphasized with the birth of a gazelle fawn on the stone slab intended as a sarcophagus lid. As a 185 “historical text”, the Wadi Hammamat inscription connects a real observation to a symbolic image, that relates to iconographic ideal. The idea of the gazelle as an inherent duality is stressed in the dual form of the toponym Gehesty. The selection of pair depictions in desert hunt scenes (cf. Appendix II) reinforces this association. A nexus with the imagery of the uraeus as a duality is found in the gazelle as protome on the diadem and its depictions (cf. 6.2). The connection between the feminine duality of the gazelle and that of the sisters Isis and Nephthys is displayed in the role allotted Gehesty as the place of Osirian resurrection. This duality extends to the transformatory capabilities of the Solar Eye, as the goddess in this role moves from fiercely protective to nurturing, the latter a role particularly suitable for the gazelle as the source of healing milk, illustrated in the Contendings of Horus and Seth (7.5.1). The Demotic myth of the Solar Eye, with the gazelle appearing alongside the vulture, is another point of connection with the duality of the protome, also found as gazelles. Expressed in various constellations, the gazelle with a well defined relationship to the female ‘mode’ alludes to mother and daughter. The different expressions of the Eye goddesses further demonstrate the complexity as well as the ‘validity’ of the gazelle as a meaningful image. 186 8 The Gazelle in Ancient Egyptian Art Image and Meaning The aim of this study has been to examine the role of the gazelle in ancient Egyptian art and determine its basic form and associations. This review, covering a period of some four thousands years, shows that the image of the gazelle is a reoccurring feature of Egyptian art. It is found in a number of different sources, from Predynastic objects (Chapter 3), to desert hunt and offering scenes (Chapter 4 and 5) and on a variety of objects (Chapter 6). The status of the gazelle as something more than a reference to natural surroundings is confirmed in the context in which these images are found as well as in the textual sources (Chapter 7). The vast majority of the images of the gazelle are relatively homogenous, suggesting that they were, by the historical period, canonical and subject to few changes. The written references to the gazelle are few but display a consistent frame of reference. The pictorial and textual images correlate and bring an underlining idea with specific connotations into focus. The primary material indicates that the natural image of the gazelle is paralleled with one laden with cultural concepts at an early stage; image and meaning were essentially “always” interwoven. The gazelle images are to a large degree based on observation of its natural behaviour (Chapter 2). Certain aspects of this behaviour appear to have provoked associations resulting in the selection of specific images that were consequently solidified into icons. These in turn carried associations that motivated their continued inclusion. This indicates that the underlying meaning of the images is as important, if not more so, than the natural representation of the gazelle. The pattern that emerges from following the gazelle imagery through time is one that indicates an explicit relationship between the gazelle and attributes of regeneration. An initial image of the gazelle as prey is joined, and later superseded, by that of mother and child, thus placing the gazelle in the sphere of the feminine, particularly in the funerary context. The connection between the gazelle and the desert landscape as the place where death is transformed into new life is particularly prominent. Here the image of the nursing gazelle and the two gazelles underscore the idea of transition. The Predynastic images (Chapter 3) locate the gazelle in its natural environment, the desert, where it was hunted by various predators. The motif 187 of dog (/lion) attacking gazelle is one of the earliest and most prevailing images. The hunter and the hunted formed binary pairs, connoting control versus chaos. The capture and death of the gazelle provided a food offering, transforming the animal into life giving sustenance. The Predynastic burials of gazelles (7.1) indicate that the relationship with desert prey had gained a ritual character early on. The dynastic royal and private desert hunt scenes (Chapter 4) display more or less the same set of gazelle motifs, demonstrating the established position of the gazelle in such compositions, and the desert hunt scene alters little in its composition during the millennia it was in use. This canonical stability is explained by the function of the motifs. The gazelle stands out in these scenes however in its singular role as nursing mother (cf. Appendix III). One of the most fundamental concepts in the funerary iconography is the offering of food and other gifts to the deceased (Chapter 5). The overall composition of the offering scene does not change significantly during the Dynastic Period. The gazelle as an element in these scenes stands out in a few respects; most notable is the nursing gazelle in an offering row (5.1.1/b.1.______•____@_^____ __ ___ „ ___ _______<<__ ___#____"_________“__ Kingdom. Further, the gazelle is carried by the offering bringers in a great number of variations (5.1.1/a.3, 5.1.1/b.2), focusing on it as a small and, mostly likely, young animal. The compositional position of the gazelle fawn is commonly paralleled with the calf, suggesting that these two are equated and thereby conceptualized as belonging to the category. This creates an analogy with divine cow – calf paradigm found with Hathor and the king. The so-called basket motif (5.1.1/b.3, cf. Appendix III) is another image typical for the Old Kingdom that features the gazelle fawn. The basket motif also tends to include two animals in the basket, providing a distinctive reference to duality as a compositional structure repeated with the gazelle. 8.1 Abstracted motifs Most of the gazelle motifs that have an origin in the desert hunt scenes are used in other contexts. These include the dog-attacking- gazelle motif, the gazelle with face turned back, the nursing gazelle, the recumbent fawn and the pair of gazelles. These are all found on, and as, objects. The textual references represent a correlating adaption of the conceptual role of gazelle imagery. 188 8.1.1 The eyes of the gazelle - face turned back The best known textual description of the gazelle, describes the approach the pregnant animal about to give birth on the slab destined to be the lid of a royal sarcophagus. And the pregnant gazelle came, walking her face was toward the people before her. Her two eyes looked straight ahead. She did not turn back until she arrived at this noble mountain to this block. Wadi Hammamat M 110, Couyat and Montet 1912: Pl. XXIX; 1913: 77-78, cf. above 7.3 This image is easily recognizable as characteristic of the motif of the fleeing gazelle, face turned back, in the desert hunt scenes from all periods. The insistence on this pose suggests that there is more to the composition than a mere observation of the natural behavior. The description in the Wadi Hammamat text focuses on the eyes of the animal, and while observation reveals the importance of the gazelle’s ability to see long distances (cf. 2.3.5), there is also the later connection between the gazelle and divine eyes (cf. 7.5). The integration of the “eye” theme with that of nourishment and healing is also revealed in the Wadi Hammamat inscription as the story of the birth of the gazelle fawn is illustrated with the king offering two milk jars to Min, calling forth associations with the later narrative of healing in The Contendings of Horus and Seth (7.5.1). Although this interpretation might be considered somewhat speculative, it is clear that the eyes of the gazelle were often the focus of its portrayal. 8.1.2 Mother and child – the nursing motif The most common motif portraying the relationship between mother and young was the nursing gazelle. This image appears in the desert hunt scenes from the Old Kingdom throughout the New Kingdom and it is found in the Old Kingdom offering rows as well (Appendix III). The nursing gazelle is transposed to other contexts, most notably in the New Kingdom faience bowls (6.5). Such faience bowls were primarily found and used in the Hathoric cult centers, and the image of the nursing gazelle may infer a reference to both Hathor and the goddess’ use of milk to heal, described in The Contendings of Horus and Seth (7.5.1). 189 The repeated use of the nursing gazelle motif indicates that it had an important connotation particularly in a funerary context. The occurrence of the nursing gazelle on the faience bowls, with an aquatic setting, calls to mind the story of Isis who conceals, protects and nurses the Horus child in the marshes of Khemmis (cf. Pinch 1993: 313). 8.1.3 The hidden fawn The gazelle fawn is often found on the inserts (4.1.4), a motif mainly used in the Old Kingdom desert hunt scenes. This image reflects the natural hiding and survival behavior of the gazelle fawn (2.3.4). The recumbent form of the fawn is the most common motif found for the so-called cosmetic spoons or containers dating to the New Kingdom (6.7). This recumbent position of the fawn has a pictorial resemblance to the trilateral sign used in the word “heir” (Faulkner 1962: 12, Gardiner Sign List E 9), providing a Triliteral sign semiotic link between the gazelle fawn and the child for “heir” Horus, son of Isis. Here too, there is the possibility to see a connection with the idea of the protected child in the Osirian myth. 8.1.4 Single gazelle protome – the uraeus and Udjat Eye The single gazelle protome found on the Horus cippi and on the forehead of Reshep (6.3) most likely referred to the apotropaic qualities of these deities, and a general association to healing. The interchangeability of the gazelle and the uraeus as protome indicates that the uraeus too had this association possibly as Wadjit ( ), the cobra goddess of Lower Egypt. The combination of the gazelle and the sound Eye of Horus ( ) is found Figure 82. on the reverse of a scarab in collection of the Gazelle and the Metropolitan Museum of Art (Fig. 82). The eyes of udjat eye Horus are healed, made sound by the milk of the gazelle (7.5.1). The Eye is also the main icon for offerings. The scarab illustration brings together several levels of regeneration, implicit in the connection between the gazelle and the divine Eyes (cf. 7.5). 8.1.5 The desert mountains The gazelle as a desert animal (2.2) is stressed on numerous occasions, both in the context in which its image (cf. 4.1.1) is found and particularly in the textual material. The qualities of the desert are beneficial for the dead, as 190 demonstrated by the role given Gehesty (7.2), as well as the reoccurrence of the desert mountain topography in the both pictorial and textual sources. The desert is the natural home of the gazelle, it the scene for the desert hunt, and the place from which it is taken to become an offering for the deceased. In mythic terms, the desert is Gehesty “The Place of the Two Gazelles”, where Osiris both dies and is raised up. The two gazelles that make up its name is a motif from the desert hunt scenes (e.g. 4.3.1/b.1 and Appendix II). In the wild, female gazelles pair up when food is scarce (2.2). The repeated motif of two gazelles in the desert hunt scenes may contribute to the idea of the desert as a place of want, with the death of Osiris as a part of that idea. The desert hunt scenes may have the death of Osiris behind them as an implicit condition for the function of the tomb. The myth itself is however implicit in later sources when the milk of the gazelle plays an active part in the resolution of conflict with the healing of the eyes of Horus, leading to the god’s defeat of his father’s murderer and his own ascent to the throne (7.5.1). This too is placed in the context of a desert mountain that, like Gehesty, is given the attributes of both death and regeneration. The gazelle is a natural participant in the quarrying activities required for the acquisition of the stone for a royal sarcophagus. The Wadi Hammamat inscription (7.3) that describes a gazelle giving birth on the slab intended for the lid is metaphoric in character, overlaying the connotations of the desert- gazelle relationship onto the function of the block. The desert mountains as a transformative topography play an active part in the Myth of the Solar Eye (7.5.2), as Tefnut transforms herself into a gazelle upon entering Thebes. The Theban mountains, found on the west bank, give an added level of generative imagery to this tale. This explicit connection of the gazelle to the desert is further illustrated in the Roman Period gazelle necropolis in the desert at Komir (7.4.4). The Egyptian name for Komir, can also be read as the Late Period term for desert mountain . The desert as an attribute of the gazelle is incorporated into a gazelle statue dated to the 18 th Dynasty (MMA 26.7.1292, Arnold 1995: 10; here Fig. 83). The gazelle stands on a wooden base that has been crafted into an undulating desert ground, interspersed with desert plants and bushes. This delicate object shows the gazelle as a desert animal, an image with multiple associations. 191 Figure 83. Gazelle standing on desert ground (MMA 26.7.1292). 8.1.6 The gazelle pair The motif of two gazelles is used in a number of different contexts. Found in the desert hunt scenes (Appendix II), the two gazelle motif is reflected earlier in the pair of gazelle wands (6.1) and repeated in the gazelle protomes (6.2). Common for the latter is an association with a ritual context in which women participate. The evidence for these wands covers the period from the 1 st to at least the 22 nd dynasty, often in the context of the Heb Sed. An early depiction of the wands as determinatives in the term (“worshipping women” in the Pyramid Texts (6.1.2), relates them to a group of lakes in which the king, as Osiris, is bathed as part of the resurrection process. As also the place where the dawn is born, these lakes, represented by the gazelle wands, have clear regenerative properties, similar to those ascribed to Gehesty, the Place of the Two Gazelles. 192 The gazelle wands are often carried by women wearing a modius, in one example ornamented with a double gazelle protome (6.1.4/b). The women wearing the two gazelle protome could also carry sistra and menats, indicating an association between the gazelle wand and protomes with the cult of Hathor. The women themselves appear to occur in the role “daughter”, as noted on the chair of Satamun (6.2.5) and in the tombs of Menna and Pairy (6.2.2-3). The young women depicted in the Heb Sed context are also often termed , “children of the king” (cf. e.g. Troy 1986: 89-90). All of this suggests that there is an association between the gazelle iconography and women of younger “daughter” rank. This connection is affirmed in the incorporation of the gazelle into the Myth of the Solar Eye (7.5.2), in which Tefnut, the daughter of Re, transforms herself into a gazelle. Further, it has been suggested that the chair of Satamun (6.2.5) represents an early image of the Demotic myth (Radomska 1991: 269-275). Hathor is another goddess attributed with the role of daughter of Re, often found with a platform crown with two plumes, said to connect her to the Solar Eye (Malaise 1976: 224). This implies that the gazelle protomes attached to a modius, and in a few examples the plumes, also have this connotation. Hathor is also, in Papyrus Jumilhac (7.2.7) closely associated with Gehesty, the Place of the Two Gazelles. One of the primary forms of the Solar Eye is as a cobra, called in that context a uraeus. While the king wears the single uraeus, it is the double uraeus that characterizes the iconography of the royal women. It is this duality that is paralleled by the double gazelle protome. Additional feminine dualities such as the Two Ladies of Upper and Lower Egypt and the Osirian sisters Isis and Nephthys all are part of a paradigm of renewal (cf. Troy 1986: 46-47), into which the gazelle is incorporated. 8.2 Conclusion The image of the gazelle has its origin in nature, and more so in the response of the Egyptians to seeing it in its natural surrounding. The image that comes from this meeting is employed as an expression of some of the most central ideas of Egyptian culture: as prey in an illustration of the interaction of order and conflict, as an image of nurturing regeneration and healing for the deceased in a funerary context, as a representation of the protective action of the mother hiding her child in preparation for the ascent of a new generation. The gazelle also functions as an icon for the place in which the transition between death and life takes place. The preference for the feminine aspect of the gazelle allows it to move into the paradigms of that role, making it a 193 manifestation of the same conceptual sphere as found for goddesses such as Tefnut, Hathor and Isis, mother and solar daughter. The gazelle as icon and divine image embodies a range of expressions that correlate with its nature as a desert animal, while provoking associations with central cultural concepts. These motifs, with their continuing presence in Egyptian art thus have parallel functions as both image and meaning. 194 Appendix I: desert hunt scenes – royal monuments Old Kingdom Khufu (?), Lisht (L 13-14: 315), 4 th dyn. Source Reused blocks found in the pyramid of Amenemhat I at Lisht. Dated to the 4 th dynasty, from temple of Khufu (?). Motifs 4 gazelles in group, striding References Goedicke 1971: 135, fragment 82 Sahure, Abusir, 5th dyn. = 4.2.1/a Source Blocks from pyramid temple (Berlin 21783) = 4.2.1/a Motifs 2 pair compositions: striding; dorcas and Soemmerring’s, fleeing, pierced by arrow, head turned back, dog attack, recumbent in insert References PM III/1: 327 (5), Borchardt 1913: Pl. 17 Niuserre, Abu Ghurob, 5 th dyn. = 4.2.1/b Source Blocks from Sun temple (Berlin 20036) Motifs Pair composition: dorcas and Soemmerring’s foaling, recumbent, nibbling on bush, basket on pole. References PM III/1: 319, Von Bissing 1956: Pl XI a-b, Edel and Wenig 1974: Pl. 14 Unas, Saqqara, 5 th dyn. = 4.2.1/c Source Causeway leading to pyramid complex Motifs Two pair compositions: striding, one of them dorcas and Soemmerring’s, dog attack, head turned back, mating (?), pair composition: dorcas and Soemmerring’s foaling (?), recumbent in insert, nursing References PM III/2: 419, Hassan 1938: Pl. XCVII A, Labrousse and Moussa 2002: 147-152, Figs 42-59 Pepi II, Saqqara, 6 th dyn. = 4.2.1/d Source Pyramid temple Motifs Pair composition: striding, recumbent in insert (?) References PM III/2: 427 (27), Jéquier 1938: Pls 41-43 195 Middle Kingdom Mentuhotep II, Deir el-Bahari, 11 th dyn. = 4.2.2/a Source Blocks from funerary complex (Brussels, Musée Royaux E.4989) Motifs Fleeing, pierced by arrow, head turned back References PM II: 385, Naville, Ayrton and Hall 1907: Pl. XVI New Kingdom Amarna, 18 th dyn. Source Amarna royal tomb Motif Traces of animals in desert, gazelles fleeing, head turned back (no hunting per se) References PM IV: 236 (10), Smith 1965b: 182, Fig. 62 a Source Block from palace in Amarna Motif Gazelles fleeing in desert, head turned back (no hunting per se). References Smith 1965b: 182, Fig. 62 b Thebes, 18 th dyn. Source Block from the Aten shrine in Karnak motif Traces of animals fleeing in desert References Smith 1965b: 182, Fig. 62 c Tutankhamun, KV 62, Valley of the Kings, 18 th dyn. = 4.2.3/a.1-4 Source a. Bow case (Cairo JE 61502) Motifs Fleeing, male gazelle nibbling on bush References PM I/2: 581, McLeod 1982: Pls VI-XVI Source b. Painted chest (Cairo JE 61467) Motifs Fleeing, species grouping References PM I/2: 577, Decker and Herb 1994: Pl. CLXXV (J 121) Source c. Embroidered tunic (Cairo JE 62626) Motifs Fleeing, head turned back, dog attack, recumbent, nursing References PM I/2: 582, Crowfoot and Davies 1941: Pl. XXII Source d. Unguent jar (Cairo JE 6119) Motifs Fleeing, head turned back, dog attack References PM I/2: 580, Carter 1927: Pl. LI 196 Source Temple of Amun, Karnak Motifs Block fragment showing shooting from chariot, traces of pierced aurochs. According to the inscription a desert hunt ! & .) References Decker and Herb 1994: 343, Pl. CLXXI (J 118) Seti I, temple of Hauron-Haremakhet, Giza, 19 th dyn. Source Stela (no. 80) Motifs Traces, no gazelles visible References PM III/1: 39, Hassan 1953: 104, Fig. 74 Ramses III, Medinet Habu, 20 th dyn. = 4.2.3/b Source Funerary temple = 4.2.3/b Motifs Fleeing, head turned back, pierced by arrow, species grouping References PM II: 516 (185), Epigraphic Survey 1932: Pls 116-117 Appendix II: desert hunt scenes – private tombs Old Kingdom Meidum Nefermaat, Tomb 16a (Cairo 43809), 3 rd -4 th dyn. = 4.3.1/a.1 Motifs Dog attack References PM IV: 93, Petrie 1892: Pl. XVII, Harpur 2001: Pl. 5 Atet, Tomb 16b (Pennsylvania University Museum E.16141), 3 rd - 4 th dyn. = 4.3.1/a.1 Motifs Dog attack References PM IV: 94, Petrie 1892: XXVII, Harpur 2001: Pl. 37 Rahotep, Tomb 6 (Cairo T19.11.24.3G), 4 th dyn. = 4.3.1/a.2 Motifs Fleeing, head turned back, dog attack References PM IV: 91, Petrie 1892: Pl. IX, Harpur 2001: Pl. 40 197 Saqqara Methen, LS 6, 4 th dyn. Motifs No gazelles depicted References PM III/2: 493 (4), Smith 1949: 152, Fig. 60 Raemka, Tomb 80 (D3, S 903) (MMA 1908.201.1), 5 th dyn. = 4.3.1/b.1 Motifs Pair composition: fleeing (?), dog attack, head turned back, recumbent in insert References PM III/2: 487 (3), Hayes 1953: 99, Fig. 56 Pehenuka, Tomb D 70 (LS 15) (Berlin 1132), 5 th dyn. = 4.3.1/b.2 Motifs Nibbling on bush, nursing, recumbent in insert References PM III/2: 491-492 (4), Harpur 1987: 530, Fig. 188 Ptahhotep [II], Tomb D 64b, 5 th dyn., Isesi-Unas = 4.3.1/b.3 Motifs Dog attack, recumbent in insert, nursing References PM III/2: 601 (17), Davies 1900: Pl. XXI Niankhkhnum and Khnumhotep, 5 th dyn., Niuserre – Menkauhor = 4.3.1/b.4 Motifs Recumbent in insert, nursing References PM III/2: 642 (10), Moussa and Altenmüller 1977: Pls 38, 40 Akhethotep, Tomb D 64a, 5 th dyn., Isesi-Unas Motifs Lion attack, recumbent in insert, possibly a dog attack References PM III/2: 599 (1)-(2), Davies 1913: Pl. XL, 1-3 Ti, Tomb 60 (D22), 5 th dyn. Motifs Lion attack References PM III/2: 473 (35), Schweitzer 1948: 54, Fig. 6 Thefu, 5 th dyn. Motifs Lion attack References PM III/2: 605, Hassan 1975b: Pl. LXXXVI, C Fetekta, Tomb LS 1, 5 th -6 th dyn. Motifs Three striding, in insert, with pair of Soemmerring’s gazelle and an ibex. References PM III/1: 351 (6), LD II, Pl. 96 198 Nebkauher, 5 th -6 th dyn. Motifs Traces of desert hunt scene, no gazelles visible References PM III/2: 628 (10), Hassan 1975a: Pl. XIX, C Mereruka, Tomb A, 6 th dyn. Motifs Lassoed, recumbent in insert (?) References PM III/2: 528 (18), Duell 1938 I: Pls 24-25 Meryteti (son of Mereruka), Tomb C, 6 th dyn. = 4.3.1/b.5 Motifs Lion and dog attack, dorcas and Soemmerring’s striding in group, gazelle in basket (?), recumbent in insert References PM III/2: 536 (112), Decker and Herb 1994: Pl. CXL (J 40) Seankhuiptah, 6 th dyn. Motifs Striding gazelles in group, gazelle in insert References Kanawati and Abder-Raziq 1998: Pl. 67 Idut, 6 th dyn. Motifs Reported in PM References PM III/2: 619, “unplaced”, Decker and Herb 1994: 309 (J 37) Wernu, 6 th dyn. Motifs Lion attacking oryx, a gazelle striding References PM III/2: 519 (8), Saad 1943: Pl. XLIII Unknown, Shaft no. 6, 6 th dyn. Motifs Nursing References PM III/2: 613, Hassan 1975c: Pl. XIV, C Giza Minkhauef, Tomb G 7430 + 7440, 4 th dyn., Khufu-Khefren Motifs Fragment of a kneeling hunter, no gazelles visible References PM III/1: 195, Decker and Herb 1994: 299 (J 19), Smith 1949: 170, Fig 65. 199 Nimaatre, Tomb G 2097, 5th dyn. = 4.3.1/c.1 Motifs Striding, dog attack, (?), Pair composition: dorcas and Soemmerring’s mating References PM III/1: 70, Roth 1995: Fig. 189 Seshemnefer [IV], LG 53, 5 th - 6 th dyn. = 4.3.1/c.2 Motifs Fleeing, head turned back, lassoed, recumbent in insert, mating References PM III/1: 224 (6), Junker 1953: Fig. 63 Akhetmerunesut, Tomb G 2184, 5 th -6 th dyn. Motifs Fragmentary, hunting with lasso, no gazelles References PM III/1: 80 (4)-(5), Decker and Herb 1994: Pl. CXXXVIII (J 34) Deir el-Gebrawi Ibi, Tomb 8, 6 th dyn. = 4.3.1/d.1 Motifs Striding, lion attack References PM IV: 244 (11), Davies 1902a: Pl. XI Djau, Tomb 12, 6 th dyn. Motifs Striding, head turned back References PM IV: 245 (7), Davies 1902b: Pl. IX El-Hawawish Hesi-min, Tomb G 42, 6 th dyn. Motifs Traces, no gazelles visible References Kanawati 1987: 13, Fig. 3 Intef, Tomb BA 63, 6 th dyn. or after Motifs Traces, no gazelles visible References Kanawati 1987: 34, Figs 20, 21 Kheni, Tomb H 24, 6 th dyn. - FIP Motifs Fragmentary, two dogs attack. References Kanawati 1981: 23, Fig. 19 200 Qubbet el-Hawa Pepy-nakht Hekaib, A.9, 6 th dyn., Pepi II Motifs Traces, no gazelle visible References PM V: 237, Decker and Herb 1994: Pl. CXLII (J 48) Kom el-Ahmar Sawaris (Scharuna) Pepyankh-hwi, 6 th dyn. Motifs Reported in Decker and Herb References Decker and Herb 1994: 311 (J 43) Kom el-Ahmar (Hierakonpolis) Pepynenankh, 6 th dyn. – MK Motifs Reported in PM References PM V: 197 (1), Decker and Herb 1994: 311 (J 42) Heruemkhauef, MK Motifs Reported in PM References PM V: 197 (4)-(5), Decker and Herb 1994: 328 (J 82) Naga ed-Deir Merw, N 3737, 6 th dyn.- MK Motif Traces of a hunter with bow and arrows References Smith 1949: 297, Fig. 148 El-Mo’alla Ankhtifi, FIP Motifs Dog attack References PM V: 170, Vandier 1950: Pl. XXXVIII Sobekhotep, FIP Motifs Dogs attacking aurochs, possible traces of gazelles References Vandier 1950: Pl. XLII 201 Assiut Khety II, FIP – MK Motifs Reported in Decker and Herb References Decker and Herb 1994: 315 (J 56) Middle Kingdom Beni Hassan Amenemhat, BH 2, 12 th dyn. Motifs Fleeing, looking back References PM IV: 142 (7)-(11), Newberry 1893: Pl. XIII Khnumhotep [III], BH 3, 12 th dyn. = 4.3.2/a.1 Motifs 3 gazelles fleeing in group, one head turned back, foaling recumbent in insert References PM IV: 145 (7)-(11), Newberry 1893: Pl. XXX Khnumhotep [I], BH 14, 12 th dyn. Motifs Traces. Dog attack (from Griffith Institute photo, not published by Newberry) References PM IV: 149 (2)-(3), Newberry 1893: Pl. XLVI, Griffith Institute Photo 1523 Baqt [III], BH 15, 11 th dyn. Motifs Striding, fleeing in group of 3 adults, 1 young. References PM IV: 151 (2)-(6), Newberry 1894: Pl. IV Khety, BH 17, 11 th dyn. = 4.3.2/a.2 Motifs Two scenes: striding, fleeing in group, head turned back; dog attack, lassoed References PM IV: 155 (2)-(3), 156 (5); Newberry 1894: Pls XIII, XIV Baqt [I], BH 29, 11 th dyn. Motifs No gazelles visible. References PM IV: 160 (5)-(6), Newberry 1894: Pl. XXIX 202 Baqt [II], BH 33, 11 th dyn. (?) Motifs Dog attack (?) References PM IV: 160: (3)-(4), Newberry 1894: Pl. XXXV Meir Senbi, B 1, 12 th dyn., Amenemhet I = 4.3.2/b.1 Motifs Dog attacking gazelle, 3 gazelles in insert in opposite directions; nursing gazelle, nibbling on bush References PM IV: 249 (1), Blackman 1914: Pl. VI Ukhhotep, B 2, 12 th dyn., Sesostris I = 4.3.2/b.2 Motifs Two dogs attacking, arrow in body, mating References PM IV: 250 (2)-(3), Blackman 1915a: Pls VII-VIII Ukhhotep, B 4, 12 th dyn., Amenenhat II Motifs Traces of net, reported in PM to be a part of desert hunt References PM IV: 253 (6), Blackman 1915b: Pl. V, 1 Ukhhotep, C 1, 12 th dyn., Sesostris II Motifs Traces of desert hunt, no gazelles visible References PM IV: 253 (not reported), Blackman and Apted 1953: Pl. IX El-Bersheh Djehutinakht [VI], Tomb 1, 12 th dyn. Motifs “Hunting”, cited in PM References PM IV: 177 (1), no published pictures Djehutihotep [II], Tomb 2, 12 th dyn., Sesostris I-II Motifs Fragmentary, possible traces of two gazelles striding References PM IV: 179 (5) Newberry 1895: Pl. VII Neheri, Tomb 4, 12 th dyn. Motifs Pair composition: striding or fleeing References PM IV: 181, Griffith and Newberry 1895: Pl. XI, 7 203 Aha-nakht, Tomb 5, 12 th dyn. Motifs Traces of desert animals, no gazelles References PM IV: 182 (9), Griffith and Newbery 1895: Pl. XVI Theban Necropolis Intefiker, TT 60, Sheikh Abd el-Gurna, 12 th dyn., Sesostris I =4.3.2/c.1 Motifs Fleeing, dog attack, head turned back References PM I/1: 122 (9), Davies and Gardiner 1920: Pl. VI Dagi, TT 103, Sheikh Abd el-Gurna, 11 th dyn., Mentuhotep II Motifs Fragment, no gazelle visible References PM I/1: 216-217 (not reported), Davies 1913: Pl. XXX, 2 Khety, TT 311, Deir el-Bahari (MMA 23.3.173), 11 th dyn., Mentuhotep II Motifs Dog attacking fleeing gazelle (?) References PM I/1: 387 (2)-(3), Hayes 1953, 164, Fig. 100 Djar, TT 366, ‘Asâsîf, 11 th dyn. Motifs Cited in PM as “man holding gazelles” References PM I/1: 429 (1), Kampp 1996: 592 Intef, TT 386, ‘Asâsîf, 11 th dyn. Motifs Fleeing, arrows through eye, neck and belly, head turned back References PM I/1: 437, Jaroš-Deckert 1984: Pl. 21 El-Saff Ip, 11th dyn. = 4.3.2/d.1 Motifs Antithetical composition: dorcas and Soemmerring’s gazelle, separated by a small hill and bush, dog bites Soemmerring’s hind leg. References Fischer 1996: Pls A, 6 Qubbet el-Hawa Sarenput [I], Tomb 36, 12 th dyn., Sesostris I Motifs Traces, no gazelle visible References PM V: 238, Müller 1940: Fig 11 b 204 El-Kab Sobek-nakht, Tomb 10, 12 th dyn. – SIP Motifs Dog attack (?) References PM V: 185 (10), Decker and Herb 1994: Pl. CLV (J 84) New Kingdom, 18 th dyn. Theban Necropolis Djehuti, TT 11, Dra’ Abû el-Naga’, Hatshepsut – Tuthmosis III Motifs Destroyed: fleeing (?) References PM I/1: 23 (16), Säve-Söderbergh 1958: 290, Fig. 7 Hery, TT 12, Dra’ Abû el-Naga’, Ahmose – Amenhotep I (?) Motifs Traces, possibly including gazelles References PM I/1: 25 (5), Wegner 1933: Pl. IV a-b Montuherkepeshef, TT 20, Dra’ Abû el-Naga’, Tuthmosis III = 4.3.3/a Motifs Three fleeing, pierced by arrow (?), nursing References PM I/1: 35 (7), Davies 1913: Pl. XII User, TT 21, Sheikh Abd el-Gurna, Tuthmosis I Motifs Fleeing in pair, pierced by arrows, head turned back, dog attack References PM I/1: 36 (10), Davies 1913: pl. XXII Nebamun, TT 24, Dra’ Abû el-Naga’, Tuthmosis III Motifs Reported desert hunt scene in PM References PM I/1: 42 (7), Kampp 1996: 209-210, no published pictures Puimre, TT 39, Khôkha, Tuthmosis III Motifs Dog attack, 3 downed References PM I/1: 72 (10), Davies 1922: Pl. VII Amenemhat, TT 53, Sheikh Abd el-Gurna, Tuthmosis III Motifs Fleeing, one kneeling, dog attack, head turned back References PM I/1: 103 (5), Wreszinski 1923: Pl. 53 a 205 Userhat, TT 56, Sheikh Abd el-Gurna, Amenhotep II Motifs Pair composition: fleeing, pierced by arrows, species grouping References PM I/1: 113, (13), (14), (15), Wreszinski 1923: Pl. 26 Re, TT 72, Sheikh Abd el-Gurna, Tuthmosis III Motifs Reported desert hunt scene in PM References PM I/1: 142 (4), Kampp 1996: 303-306, no published pictures Ineni, TT 81, Sheikh Abd el-Gurna, Amenhotep I – Tuthmosis III Motifs Traces, no gazelles visible References PM I/1: 161 (10), Dziobek 1992: Pl. 16 Amenemhat, TT 82, Sheikh Abd el-Gurna, Tuthmosis III Motifs Traces, no gazelles visible References PM I/1: 164 (7), Davies and Gardiner 1915: Pl. XXXI Amunedjeh, TT 84, Sheikh Abd el-Gurna, Tuthmosis III – Amenhotep II Motifs Traces, possibly including gazelles References PM I/1: 169 (15), Wegner 1933: Pl. IX a-b Amenemheb, TT 85, Sheikh Abd el-Gurna, Tuthmosis III – Amenhotep II Motifs Deceased confronts female hyena with a stick. No gazelles. References PM I/1: 173 (18), Wreszinski 1923: Pl. 21 Kenamun, TT 93, Sheikh Abd el-Gurna, Amenhotep II Motifs One reclined, with head turned back, identity uncertain References PM I/1: 193 (19), Davies 1930: Pl. XLVIII Rekhmire, TT 100 Sheikh Abd el-Gurna, Tuthmosis III – Amenhotep II Motifs Pair composition: fleeing gazelles, pierced by arrows, head turned back, dog attack References PM I/1: 210 (11), Davies 1943: Pl. XLIII Min, TT 109, Sheikh Abd el-Gurna, Tuthmosis III Motifs Reported desert hunt scene References PM I/1: 227 (17), Kampp 1996: 389-390, no published pictures 206 Amenemhat, TT 123, Sheikh Abd el-Gurna, Tuthmosis III Motifs Photo only of tomb owner hunting from chariot References PM I/1: 237 (10), Decker and Herb 1994: Pl. CLXIV (J 100) Amunuser, TT 131, Sheikh Abd el-Gurna, Tuthmosis III Motifs Reported desert hunt scene in PM References PM I/1: 246 (10), Kampp 1996: 419-422, no published pictures Intef, TT 155, Dra’ Abû el-Naga’, Hatshepsut – Tuthmosis III Motifs Traces, possibly including gazelles References PM I/1: 256 (10), Säve-Söderbergh 1957: Pl. XVI Mentuiwiw, TT 172, Sheikh Abd el-Gurna, Tuthmosis III- Amenhotep II Motifs Pair composition, fleeing, pierced by arrows, species grouping, one recumbent References PM I/1: 280 (7), Decker and Herb 1994: Pl. CLXVIII (J 108) Ahmose, TT 241, Khôkha, Tuthmosis III? Motifs Reported desert hunt scene in PM References PM I/1: 331 (5), Kampp 1996: 517-519, no published pictures Nebemkemet, TT 256, Khôkha, (Amenhotep II) Motifs Reported desert hunt scene in PM References PM I/1: 341 (8), Kampp 1996: 583-535, no published pictures Sayemiti, TT 273, Gurnet Mura’i (Ramesside) Motifs Traces of gazelles visible References PM I/1: 351 does not mention desert scene, Kampp 1996: 545-546, Griffith Institute, Schott 4864, no published pictures Amenemipet, TT 276 Gurnet Mura’i (Tuthmosis IV ?) = 4.3.3/b Motifs Pair composition, fleeing, dog attack, head turned back, species grouping References PM I/1: 353 (11), Wilkinson 1878: 92, Fig. 357 Djehutimes, TT 342, Sheikh Abd el-Gurna (Tuthmosis III-Amenhotep II) Motifs Reported desert hunt scene in PM References PM I/1: 410 (4), Kampp 1996: 581-582, no published pictures 207 Neferhotep, A 5, Dra’ Abû el-Naga’(Tuthmosis III-Amenhotep II) Motifs Group of 4 fleeing, pair composition: fleeing, pierced by arrows, dog attack References PM I/1: 449, Keimer 1940: Pl. III, cf. Osborn 1998: 12 Unknown tomb, Western Thebes (?) = Berlin 5/65, 18 th dyn. Motifs Reported in Decker and Herb References Decker and Herb 1994: 343 (J 119) El-Debeira, Nubia Djehutihotep, 18 th dyn. (Tuthmosis III or later) Motif Traces of shooting arrow from chariot References Säve-Söderbergh 1960: 32, Fig. 5 Late Period Ibi, TT 36, ‘Asâsîf, 26 th dyn. (Psamtek I ) = 4.3.4/a Motifs Lion attack, fleeing References PM I/1: 67 (20), Scheil 1894: 647, Fig. 8 Nesu-su-djehuty, Saqqara (Cairo 17.6.24.11), 26 th dyn. (Psamtek I) Motifs Traces, pair composition: striding References PM III/2: 669, Quibell 1912: LXII, 1 208 Appendix III: selected motifs Mating, foaling, nursing and young gazelles in baskets Mating Desert hunt scenes Royal monuments Unas, Saqqara, 5 th dyn. = 4.2.1/c Source Causeway leading to pyramid complex References PM III/2: 419, Labrousse and Moussa 2002: 150, Fig 52, Doc. 38 Private tombs Nimaatre, Tomb G 2097, Giza, 5 th - 6 th dyn. = 4.3.1/c.1 References PM III/1: 70, Roth 1995: Fig. 189 Seshemnefer [IV], LG 53, Giza, 5 th – 6 th dyn. = 4.3.1/c.2 References PM III/1: 224 (6), Junker 1953: Fig. 63 Ukhhotep, B 2, Meir, 12 th dyn. (Sesostris I) = 4.3.2/b.2 References PM IV: 250 (2)-(3), Blackman 1915a: Pl. VII Objects Silver jar, (Cairo CG 53262, JE 39867), Bubastis, 19 th dyn. References Edgar 1925: Pl. I, Fig. 1 209 Foaling Desert hunt scenes Royal monuments Niuserre, 5th dyn., Abu Ghurob = 4.2.1/b Source Blocks from Sun temple (Berlin 20036) gazelle foaling References PM III/1: 319, von Bissing 1956: Pl XI a-b, Edel and Wenig 1974: Pl. 14 (Z.250) Unas, 5 th dyn., Saqqara = 4.2.1/c Source Causeway leading to pyramid complex References PM III/2: 419, Hassan 1938: Pl. XCVII A Private tombs Khnumhotep [III]. 12th dyn., Beni Hassan, BH 3 = 4.3.2/a.1 References PM IV: 145 (7)-(11), Newberry 1893: Pl. XXX Objects Painted Box, 13 th dyn. – SIP, Riqqeh Comments Foaling gazelle with hyena sniffing the fawn. Traces of Bes and Taweret References Petrie 1907: Pl. XXIV 210 Nursing Desert hunt scenes Royal monuments Unas, Saqqara, 5 th dyn. = 4.2.1/c Source Causeway leading to pyramid complex References PM III/2: 419, Hassan 1938: Pl. XCVII A, Labrousse and Moussa 2002: 151, Fig. 55, Doc. 41 Private tombs Pehenuka, Tomb D 70 (LS 15, Berlin 1132), Saqqara, 5 th dyn. = 4.3.1/b.2 References PM III/2: 491-492 (4), Harpur 1987: 530, Fig. 188 Ptahhotep [II], Tomb D 64b, Saqqara, 5 th dyn (Isesi-Unas) =4.3.1/b.3 References PM III/2: 601 (17), Davies 1900: Pl. XXI Niankhkhnum and Khnumhotep, 5 th dyn. (Niuserre – Menkauhor), Saqqara = 4.3.1/b.4 References PM III/2: 642 (10), Moussa and Altenmüller 1977: Pls 38, 40 Unknown, Shaft no. 6, Saqqara, 6 th dyn. References PM III/2: 613, Hassan 1975c: Pl. XIV, C Senbi, B 1, Meir, 12 th dyn. (Amenemhet I) = 4.3.2/b.1 References PM IV: 249 (1), Blackman 1914: Pl. VI 211 Montuherkepeshef, TT 20, Dra’ Abû el-Naga’, 18 th dyn. (Tuthmosis III) = 4.3.3/a References PM I/1: 35 (7), Davies 1913: Pl. XII Neferhotep, TT 216, Deir el-Medina, 19 th dynasty (Ramses II – Seti II) = 7.4.2 References PM I/1: 313 (6), Valbelle 1981: 118, Fig. 7, 257 B Objects Embroidered tunic, (Cairo JE 62626), KV 62, 18 th dyn. (Tutankhamun) = 4.2.3/a.3 References PM I/2: 582, Crowfoot and Davies 1941: Pl. XXII Nursing: offering scenes Private tombs Nebemakhet, LG 86, Giza, 4 th dyn. (Khaefre – Menkaure) References PM III/1: 230-231 (4), Keel 1980: 73, Fig. 32 Kapi, G 2091, Giza, 5 th -6 th dyn. = frontispiece References PM III/1: 70 (9)-(10), Roth 1995: Fig. 168 Kadua, Giza, 5 th dyn. (Niuserre or later) References PM III/1: 245, Hassan 1951: 103, Fig. 82 Rawer [II], G 5470, Giza, 5 th dyn. = 5.1.1/b.1.e References PM III/1: 162 (1), Junker 1953: 233, Fig. 48 Ankhmahor, Saqqara, early 6 th dyn. = 5.1.1/b.1_ References PM III/2: 513 (10), Badawy 1978: Fig. 35 Kagemni, LS 10, Saqqara, 6 th dyn. (Teti) = 5.1.1/a.2 References PM III/2: 523 (19), von Bissing 1905: Pl. VII, 2 212 Nursing motif on objects Embroidered tunic, (Cairo JE 62626), KV 62, 18 th dynasty (Tutankhamun) = 4.2.3/a.3 Comment Desert hunt scene References PM I/2: 582, Crowfoot and Davies 1941: Pl. XXII Faience bowl, Maiherperi, KV 36 (Cairo CG 24058, JE 33825), 18 th dyn. Tuthmosis IV (?) = 6.5.1 References PM I/2: 557, Daressy 1902: Pl. VI Faience bowl, Medinet Gurob (Riqqeh Corpus) (Ashmolean 1890.1137), 18 th dyn. = 6.5.2 References Petrie 1890: Pl. XX, 5 Faience bowl, (UC 30054, “Petrie Museum fragment”) 18 th dyn. = 6.5.4 Reference Unpublished Silver bowl, Bubastis (?), (MMA 07.228.20), 19 th dyn. References Seipel et al 2001: 97-98, cat. no. 108 Faience bowl, Serabit el-Khadim (Ashmolean 1912.57), NK = 6.5.3 References Unpublished, referred to in Pinch 1993: 310. Chest, Perpaouty, Thebes (Durham Oriental Museum N 1460), 18 th dyn. Amenhotep III = 6.4.1/a References Killen 1994: Pls 29, 32 Chest, Perpaouty, Thebes (KS 1970), 18 th dyn. (Amenhotep III) = 6.4.1/b References Bologna 1994: 71 Scarabs, New Kingdom Reference Cited in Keel 1980: 88, Fig. 49c, 49d; Matouk 1977: no. 737 213 Basket motif Desert hunt scenes Niuserre, Abu Ghurob, 5 th dyn. = 4.2.1/b Source Blocks from Sun temple (Berlin 20036) References PM III/1: 319, Von Bissing 1956: Pl. XI a, Edel and Wenig 1974: Pl. 14 Meryteti (son of Mereruka), Tomb C, Saqqara, 6 th dyn. = 4.3.1/b.5 References PM III/2: 536 (112), Decker and Herb 1994: Pl. CXL (J 40) Khety, BH 17, Beni Hassan, 11 th dyn. References PM IV: 155 (2)-(3), Newberry 1894: Pl. XIII Offering scenes Nebemakhet, LG 86, Giza, 4 th dyn. (Khaefre – Menkaure) References PM III/1: 230 (4), Keel 1980: 73, Fig. 32 Ptahhotep, D 64b, Saqqara, 5 th dyn. (Isesi – Unas) Comments Gazelle with other species such as oryx, ibex and hartebeest. References PM III/2: 602 (18), Davies 1900: Pl. XXI Hetepherakhti, D 60, Saqqara (Leiden F. 1904/3.1), 5 th dyn. (Niuserre or later) References PM III/2: 593 (2), Mohr 1943: 41, Fig. 9 Ti, Tomb 60, (D 22), Saqqara, 5th dyn. (Niuserre or later) Reference PM III/2: 475 (38), Wild 1966: Pl. CLXVI 214 Niankhnum and Khnumhotep, Saqqara, 5 th dyn. (Niuserre – Menkauhor) Comments Six gazelles in a box carried by a donkey, as well as offering bearer with a box of five gazelles References PM III/2: 642 (9), Moussa and Altenmüller 1977: Pl. 34 (Fig. 13) Adua (?), CG 1552, Dashur or Saqqara, 5 th dyn. Reference Borchardt 1964: Pl 58 Idut, Saqqara, 6 th dynasty = 5.1.1/b.3._ References PM III/2: 618 (13), 619 (24), Macramallah 1935: Pls X, XX Ankhmahor, Saqqara, early 6 th dyn. References PM III/2: 513 (18), Badawy 1978: Fig. 49 Nehwet-desher, G 95, el-Hawawish (cemetery of Akhmim), 6 th dyn. (Merenre – Pepi II) References Kanawati 1988: 12, Fig. 3 Ukhhotep, B 2, Meir, 12 th dyn. (Sesostris I) = ‚____”__$__ References PM IV: 251 (12), Blackman 1915a: Pl. XI 215 Bibliography Abbreviations ÄA Ägyptologische Abhandlungen, Wiesbaden. ÄAT Ägypten und Altes Testament, Wiesbaden. ACE The Australian Centre for Egyptology, Sydney. ÄF Ägyptisches Forschung, Glückstadt/Hamburg/New York. AH Aegyptiaca Helvetica, Geneva. AJA American Journal of Archeology, Baltimore/Norwood. ASAE Annales du service des antiquités de l’Égypte, Cairo. AV Archäologische Veröffentlichungen, Deutches Archäologisches Institut, Abteilung Kairo. Berlin and Mainz. BdE Bibliothèque d’Etude, Institut Français d’Archéologie Oriental, Cairo. BIFAO Bulletin de l’Institut Français d’Archéologie Oriental, Cairo. BSEG Bulletin de la Société d'Egyptologie de Genève. CdE Chronique d’Égypte, Brussels. CG Catalogue général des antiquitiés égyptiennes du Musée du Caire. DAIK Deutsches Archäologisches Instituts, Abteilung Kairo. DE Discussions in Egyptology, Oxford. EGA Egypt’s Golden Age: The Art of Living in the New Kingdom 1558- 1058 B.C., ed. Brovarski, E. et al. Museum of Fine Arts: Boston. EEF Egypt Exploration Fund, London. EES Egypt Exploration Society, London. FIFAO Fouilles de l’Institut Français d’Archéologie Orientale du Caire. GM Göttinger Miszellen, Göttingen. HÄB Hildesheimer Ägyptologische Beiträge. Hildesheim: Verlag Gebrüder Gerstenberg. HdO Handbuch der Orientalistik, Leiden/New York/Köln. IFAO Institut français d’archéologie orientale du Caire, Cairo. JARCE Journal of the American Research Center in Egypt. Boston and New York. JEA Journal of Egyptian Archaeology, London. JNES Journal of Near Eastern Studies, Chicago. JSSEA Journal of the Society of the Studies of Egyptian Antiquities, Toronto. 216 LÄ Lexikon der Ägyptologie. Wiesbaden: Otto Harrassowitz. LÄS Leipziger Ägyptologische Studien, Glückstadt/Hamburg/New York. LD See Lepsius 1849-59. LGG See Leitz et al 2002a-c. MÄS Münchner Ägyptologische Studien, Munich/Berlin. MDAIK Mitteilungen des Deutschen Archäologischen Instituts, Abteilung Kairo, Cairo. MIFAO Mémoires publiés par les membres de l’Institut français d’archéologie orientale du Caire, Cairo. MMA The Metropolitan Museum of Art, Department of Egyptian Art, New York. OBO Orbis biblicus et orientalis. Freiburg/Göttingen: University Press / Vandenhoeck & Ruprecht. OIP Oriental Institute Publications, The University of Chicago, Chicago. OLA Orientalia Lovaniensia Analecta, Leuven. OMRO Oudheidkundige Mededelingen uit het Rijksmuseum van Oudheden te Leiden, Leiden. PM I/1 See Porter, B. and R. Moss 1960. PM I/2 See Porter, B. and R. Moss 1964. PM II See Porter, B. and R. Moss 1972. PM III/1 See Porter, B. and R. Moss 1974. PM III/2 See Porter, B. and R. Moss 1978-1981. PM IV See Porter, B. and R. Moss 1934. PM V See Porter, B. and R. Moss 1937. PM VI See Porter, B. and R. Moss 1939. PM VII See Porter, B. and R. Moss 1951. PSBA Proceedings of the Society of Biblical Archaeology. London. RdE Revue d’égyptologie, Paris. RT Recueil de travaux rélatifs à la philologie et à l’archéologie égyptiennes et assyriennes, Paris. SAK Studien zur Altägyptischen Kultur, Hamburg. SAOC Studies in Ancient Oriental Civilisation, The Oriental Institute of the University of Chicago, Chicago. Urk. IV Urkunden IV: 893, 14-15, see Sethe 1907 Urk. IV Urkunden IV: 1245, 14-15, see Helck 1955 Urk. IV Urkunden IV: 1739-1740, see Helck 1957 Wb See Erman and Grapow 1926-1931. ZÄS Zeitschrift für Ägyptische Sprache und Altertumskunde, Leipzig/Berlin. 217 ADAMS, B. 1996 Elite Graves at Hierakonpolis, in Spencer, A. J. (ed.) Aspects of Early Egypt, 1-15. London: British Museum Press. 2004 Excavations in the Elite Predyanstic Cemetery at Hierakonpolis Locality HK6: 1999-2000. ASAE 78: 35-52. ALDRED, C. 1971 Jewels of the Pharaohs. Egyptian Jewellery of the Dynastic Period. London: Thames & Hudson. ALTENMÜLLER, B. 1977 Geheset. LÄ II: 513. ALTENMÜLLER, H. 1967 Darstellungen der Jagd im alten Ägypten. Die Jagd in der Kunst. Hamburg/Berlin: Paul Parey. 1975 Dramatischer Ramesseumspapyrus. LÄ I: 1132-1140. 1977 Jagdritual. LÄ III: 231-233. EL-AMIR, M. 1959 A Family Archive from Thebes. Demotic Papyri in the Philadelphia and Cairo Museums from the Ptolemaic Period. Cairo: General Organisation for Government Printing Offices. ANDREWS, C. 1994 Amulets of Ancient Egypt. London: British Museum Press. ANSELL, W.F.H. 1971 Order Artiodactyla, Main Text in Meester J. and H.W. Setzer (eds) The Mammals of Africa: an Identification Manual, Part 15: 1-84. Washington: Smithsonian Institution Press. ARNOLD, D. 1995 An Egyptian Bestiary. The Metropolitan Museum of Art Bulletin, 52:4 (Spring 1995). New York. ASSELBERGHS, H. 1961 Chaos en Beheersing. Documenten uit Aeneolitisch Egypte. Leiden: Brill. ASSMANN, J. 2001 The Search for God in Ancient Egypt. (English transl. by David Lorton). Ithaca and London: Cornell University Press AYRTON, E.R. and W.L.S. LOAT 1911 Pre-Dynastic Cemetery at El Mahasna. EEF 21. London: EEF. 218 BADAWY, A. 1978 The Tomb of Nyhetep-Ptah at Giza and the Tomb of c Ankm c ahor at Saqqara. Berkley/Los Angeles/London: University of California Press. BARD, K. A. 2000 The Emergence of the Egyptian State (c. 3200-2686 BC), in Shaw, I. (ed.) The Oxford History of Ancient Egypt: 61-88. Oxford: Oxford University Press. BÁRTA, M. 1995 Archaeology and Iconography: and bread moulds and “Speisetischszene” development in the Old Kingdom. SAK 22: 21-35. BARTA, W. 1963 Die altägyptische Opferliste von der Frühzeit bis zur griechisch- römischen Epoche. MÄS 3. Berlin. 1968 Aufbau und Bedeutung der altägyptischen Opferformel. ÄF 24. 1978 Die Sedfest-darstellungen Osorkons II. Im Tempel von Bubastis. SAK 6: 25-42. BEHRENS, H. 1963 Neolitisch-frühmetallzeitliche Tierskelettfunde aus dem Nilgebiet. ZÄS 88: 75-83. BÉNÉDITE, G. 1918 The Carnarvon Ivory. JEA 5: 1-15 BERGER, M. A. 1982 The Petroglyphs at Locality 6, in Hoffman, M.A. (ed.) The Predynastic of Hierakonpolis. Egyptian Studies Association. Publication no. 1, 61-65. Cairo and Illinois: Cairo University Herbarium/Western Illinois University. 1992 Predynastic Animal-headed Boats from Hierakonpolis and Southern Egypt, in Friedman, R. and B. Adams (eds) The Followers of Horus. Studies dedicated to Michael Allen Hoffman, 107-120. Egyptian Studies Association Publication no. 2. Oxford: Oxbow. BIANCHI, R. S. 2001 Scarabs in Redford, D.B. (ed.) The Oxford Encyclopedia of Ancient Egypt 3, 179-181. New York: Oxford University Press. VON BISSING, F. W. 1905 Die Mastaba des Gem-Ni-Kai I-II. Berlin: Alexander Duncker. 1956 La Chambre des Trois Saisons du Sanctuaire Solaire du Roi Rathourès (Ve Dynastie) à Abousir. ASAE 53: 319-338. 219 BLACKMAN, A. M. 1914 The Rock Tombs of Meir I. Arhaeological Survey of Egypt, 22 nd Memoir. London: EEF. 1915a The Rock Tombs of Meir II. Archaeological Survey of Egypt, 23 rd Memoir. London: EEF. 1915b The Rock Tombs of Meir III. Archaeological Survey of Egypt, 24 th Memoir. London: EEF. BLACKMAN, A.M. and M.R. APTED 1953 The Rock Tombs of Meir VI. Archaeological Survey of Egypt, 29 th Memoir. London: EES. BLUMENTHAL, E. 1977 Die Textgattung Expeditionsbericht in Ägypten in Assmann, J., E. Feucht and R. Grieshammer (eds) Frage an die altägyptische Literatur. Studien zum Gedenken an Eberhard Otto, 85-118. Wiesbaden: Dr. Ludwig Reichert. BOESSNECK, J. 1988 Die Tierwelt des Alten Ägypten. Munich: Beck. BOLOGNA 1994 La Collezione Egiziana. Museo Civico Archeologico di Bologna. Bologna: Leonardo Arte Srl. BOLSHAKOV, A. 2001 Offering Tables in Redford, D. B. (ed.) The Oxford Encyclopedia of Ancient Egypt 2, 572-576. New York: Oxford University Press. BORCHARDT, L. 1913 Das Grabdenkmal des Königs S’ahu-Re’ II: Die Wandbilder. Ausgrabungen der Deutschen Orient-Gesellschaft in Abusir 1902- 1908. Wissenschaftliche Veröffentlichungen der Deutschen Orientgesellschaft 26. Leipzig: J.C. Hinrichs’sche Buchhandlung. 1937 Denkmäler des alten Reiches I (ausser den Statuen) im Museum von Kairo Nr. 1295-1808. CG 55:1. Berlin: Reichsdruckerei. 1964 Denkmäler des alten Reiches II (ausser den Statuen) im Museum von Kairo Nr. 1295-1808. CG 55:2. Cairo: Imprimeries Gouvernementales. BREWER, D. J. and R. F. FRIEDMAN 1989 Fish and Fishing in Ancient Egypt. The Natural History of Egypt: Volume II. Warminster: Aris & Phillips. BREWER, D. 1991 Temperatures in Predynastic Egypt Inferred from the Remains of the Nile Perch in Archaeology and Arid Environments, World Archaeology 22, no. 3: 288-303. Oxfordshire: Taylor & Francis. 220 2002 Hunting, Animal Husbandry and Diet in Ancient Egypt in Collins, B. J. (ed.) Handbook of Oriental Studies. The Near and Middle East. Vol. 64. A History of the Animal World in the Ancient Near East, 427-456. Leiden/Boston/Köln: Brill. BROVARSKI, E. 1984 Sokar. LÄ V: 1055-1074. BROZE, M. 1996 Mythe et roman en Égypte ancienne. Les aventures d’Horus et Seth dans le Papyrus Chester Beatty I. OLA 76. BRUGSCH, H. 1871 oder Mendes. ZÄS IX: 81-85. BRUNNER, H. 1984 Sched. LÄ V: 547-549. BRUNNER-TRAUT, E. 1977 Gazelle. LÄ II: 426-427. BRUNTON, G. 1937 Mostagedda and the Tasian Culture. British Museum Expedition to Middle Egypt 1928-1929. London: Bernard Quaritch Ltd. 1948 Matmar. British Museum Expedition to Middle Egypt 1929-1931. London: Bernard Quaritch Ltd. BRUNTON G. and G. CATON-THOMPSON 1928 The Badarian Civilization and Predynastic Remains Near Badari. British School of Archaeology in Egypt and Egyptian Research Account 46. London: British School of Archaeology in Egypt, University College & Bernard Quaritch. BRUYÉRE, B. 1926 Rapport sur les fouilles de Deir el Medinéh (1924-1925). FIFAO 3. 1937 La Nécropole de l’Ouest. Première Partie. Rapport sur les Fouilles de Deir el-Médineh (1933-1934). FIFAO XV. 1952 Note 16. Sur le Dieu Ched, À Propos de Quelques Monuments Nouveaux Trouvés À Deir el Medineh en 1939, in Rapport sur Les Fouilles de Deir el Médineh (1935-1940) II, Trouvailles d’Objets: 138-170. FIFAO XX. DE BUCK, A. 1961 The Egyptian Coffin Texts VII. Texts of Spells 787-1185. OIP 87. Chicago: University of Chicago Press. CAMINOS, R. 1974 The New-Kingdom Temples of Buhen I. Archaeological Survey of Egypt, Thirty-Third Memoir. London: EES. 221 CAPART, J. 1907 Une rue de tombeaux à Saqqarah. Volume II, Planches. Brussels: Vromant & Co. 1947 L’art égyptien IV. Les arts mineurs. Brussels: Vromant & Co. CARNARVON, H.H.M. and H. CARTER 1912 Five Years’ Exploration at Thebes. London: Oxford University Press. CARTER, H. 1927 The Tomb of Tutankhamen II. London: Cassell and Company. CARTER, H. and A. C. MACE 1923 The Tomb of Tutankhamen I. London: Cassell and Company. DE CENIVAL, F. 1988 Le Mythe de l’Oeil du Soleil. Demotischen Studien 9. Sommerhausen: Gisela Zauzich. \•–—˜\•™__š__ 1974 Felsbilder des Nord-Etbai Oberägyptens und Unternubiens. Wiesbaden: Franz Steiner Verlag. CHASSINAT, É. 1931 Le temple d’Edfou VI. MIFAO 23. CHAUVEAU, M. 1990 Glorification d’une morte anonym (P. dém. LOUVRE 2420 c). RdE 41: 3-8. CINCINNATTI 1997 Mistress of the House, Mistress of Heaven. Women in Ancient Egypt. Exhibition Catalogue. Capel, A.K. and G.E. Markoe (eds). Cincinnatti: Cincinnatti Art Museum and New York: Hudson Hills Press. CLARYSSE, W. 1978 Un groupe de tombes dans les Memnoneia entre 227 et 175 av. J.- C. CdÉ LIII: 234-239. COUYAT, M.M.J. and P. MONTET 1912 Les inscriptions hiéroglyphiques et hiératiques du Ouâdi Hammâmât. MIFAO 34:1. 1913 Les Inscriptions Hiéroglyphiques et Hiératiques du Ouâdi Hammâmât. MIFAO 34:2. CROWFOOT, G.M. and N. DE GARIS DAVIES 1941 The Tunic of Tutankhamun. JEA 27: 113-130. CURTO, S. 1963 Gli Scavi Italiani a el-Ghiza (1903). Monografie di archeologia e d’arte 1. Rome: Centro per le antichità, e la storia dell’ arte del Vicino Oriente. 222 DARESSY, M. G. 1898 Notes et remarques. RT 20: 72 – 86. 1902 Fouilles de la Vallée des Rois. CG. Cairo: IFAO. 1919 La Gazelle d’Anoukit. ASAE 18: 77. DARNELL, J.C. 1995 Hathor Returns to Medamûd. SAK 22: 47-94. DAUMAS, F. 1968 Les propylées du temple d’Hathor à Philae et le culte de la déesse. ZÄS 95: 1-17. DAVIES, NINA DE GARIS and A. H. GARDINER 1915 The Tomb of Amenemhet (no. 82). The Theban Tomb Series I. London: EEF. 1936 Ancient Egyptian Paintings I. Chicago: Chicago University Press. DAVIES, NORMAN DE GARIS 1900 The Mastaba of Ptahhetep and Akhethetep at Saqqara I. The Chapel of Ptahhetep and the Hieroglyphs. Archaeological Survey of Egypt, Eighth Memoir. London: EEF. 1901 The Mastaba of Ptahhetep and Akhethetep at Saqqara II. The Mastaba. The Sculptures of Akhethetep. Archaeological Survey of Egypt, Ninth Memoir. London: EEF. 1902a The Rock Tombs of Deir el-Gebrâwi I. Archaeological Survey of Egypt, Eleventh Memoir. London: EEF. 1902b The Rock Tombs of Deir el-Gebrâwi II. Archaeological Survey of Egypt, Twelfth Memoir. London: EEF. 1905 The Rock Tombs of El Amarna II. The Tombs of Panehesy and Meryra II. Archaeological Survey of Egypt, Fourteenth Memoir. London: EEF 1913 Five Theban Tombs (Being those of Mentuherkhepeshef, User, Daga, Nehenawäy and Tati). Archaeological Survey of Egypt, Twenty- First Memoir. London: EEF. 1922 The Tomb of Puyemrê at Thebes vol. I. Hall of memories. Robb de Peyster Tytus memorial series 2. New York: Publications of the Metropolitan Museum of Art, Egyptian Expedition. 1923 The Graphic Work of the Expedition in The Egyptain Expedition 1922-23, The Bulletin of the Metropolitan Museum of Art, Part II: 40-53. New York: The Metropolitan Museum of Art. 1927 Two Ramesside Tombs at Thebes. Robb de Peyster Tytus memorial series 5. New York: Publications of the Metropolitan Museum of Art, Egyptian Expedition. 1930 The Tomb of Ken-Amun at Thebes vol. I. The Metropolitan Museum of Art. Egyptian Expedition Publications vol. V. New York: Publications of the Metropolitan Museum of Art, Egyptian Expedition. 223 1943 The Tomb of Rekh-mi-re at Thebes vol. I. The Metropolitan Museum of Art. Egyptian Expedition Publications vol. XI. New York: Publications of the Metropolitan Museum of Art, Egyptian Expedition. DAVIES, NORMAN DE GARIS and NINA DAVIES 1923 The Tombs of Two Officials of Tuthmosis the Fourth (Nos. 75 and 90). The Theban Tomb Series III. London: EES. 1933 The Tombs of Menkheperrasonb, Amenmose, and another (Nos. 86, 112, 42, 226). The Theban Tomb Series V. London: EES. DAVIES, NORMAN DE GARIS, NINA DAVIES and A.H. GARDINER 1920 The Tomb of Antefoker, Vizier of Sesostris I, and of His Wife, Senet (no. 60). Theban Tomb Series 2. London: EES. DAVIS, W. 1992 Masking the Blow. The Scene of Representation in Late Prehistoric Egyptian Art. Berkeley/Los Angeles/Oxford: University of California DEBONO, F. 1950 Héliopolis. Trouvailles prédynastiques. CdE 50: 233-237. 1954 La nécropole prédynastique d’Héliopolis. ASAE 52: 625-652. DECKER, W. and M. HERB 1994 Bildatlas zum Sport im Alten Ägypten I, II. HdO. Leiden/New York/Köln: Brill. DERCHAIN, P. 1962 Le sacrifice de l’oryx. Rites Egyptiens I. Brussels: Fondation Égyptologique Reine Élisabeth. DESROCHES-NOBLECOURT, C. 1952 Pots anthropomorphes et recettes magico-médicales dans l’Égypte ancienne. RdE 9: 49-67. DODSON, A. and D. HILTON 2004 The Complete Royal Families of Ancient Egypt. London: Thames and Hudson. DRENKHAHN, R. 1976 Bemerkungen zu dem Titel . SAK 4: 59-67. DREYER, G. et al 1998 Umm el-Qaab. Nachuntersuchungen im frühzeitlichen Königsfriedhof 9./10. Vorbericht. MDAIK 54: 77-167. Mainz: Verlag Philipp von Zabern. VON DROSTE ZU HÜLSHOFF, V. 1980 Der Igel im alten Ägypten. HÄB 11. 224 DUELL, P. 1938 The Mastaba of Mereruka, I-II. OIP 31, 39. DUEMICHEN, J. 1865 Geographischen Inschriften I. Altägyptischer Denkmäler in der Jahren 1863-1865. Leipzig: J.C. Hinrichs’sche Buchhandlung / Paris: A. Franck. DUNHAM, D. 1937 Naga-ed-Dêr Stelae of the First Intermediate Period. Museum of Fine Arts, Boston. Oxford: Oxford University Press. DZIOBEK, E. 1992 Das Grab des Ineni. Theben Nr. 81. AV 68. EATON-KRAUSS, M. and E. GRAEFE 1985 The Small Golden Shrine from the Tomb of Tutankhamun. Oxford: Griffith Institute. EDEL, E. 1981 Ägyptische Namen für Vorderasiatische Orts-, Berg- oder Flussbezeichnungen. Eretz-Israel 15: 10-12. Jerusalem: The Israel Exploration Society. EDEL, E. and S. WENIG 1974 Die Jahreszeitenreliefs aus dem Sonnenheiligtum des Königs Ne- user-Re. Staatliche Museen zu Berlin. Mitteilungen aus der ägyptischen Sammlung 7. Berlin: Akademie-Verlag. EDGAR, C.C. 1925 Engraved Designs on a Silver Vase from Tell Basta. ASAE 25: 256-258. EMERY, W. 1938 The Tomb of Hemaka. Excavations at Saqqara. Service des Antiquités de l’Égypte. Cairo: Government Press. 1961 Archaic Egypt. Harmondsworth: Penguin Books. EPIGRAPHIC SURVEY 1932 Medinet Habu II. Later Historical Records of Ramses III. OIP IX. Chicago: University of Chicago Press. 1940 Medinet Habu IV. Festival Scenes of Ramses III. OIP LI. Chicago: University of Chicago Press. 1980 The Tomb of Kheruef, Theban Tomb 192. OIP 102. Chicago: University of Chicago Press. ERMAN, A. and H. GRAPOW 1926- Wörterbuch der ägyptischen Sprache, Volumes I-V. Leipzig: J.C. 1931 Hinrichs’sche Buchhandlung. 225 ERTMAN, E.L. 1993 From Two to Many: The Symbolism of Additional Uraei Worn by Nefertity and Akhenaten. JSSEA 23: 42-50. ESTES, R.D. 1992 The Behaviour Guide to African Mammals. Including Hoofed Mammals, Carnivores, Primates. Berkely/Los Angeles/London: University of California Press. EYRE, C. 2002 The Cannibal Hymn: A Cultural and Literary Study. Liverpool: Liverpool University Press. FAKHRY, A. 1961 The Monuments of Sneferu at Dashur II. The Valley Temple: Part I – The Reliefs. Cairo: Government Printing Offices. FAULKNER, R.O. 1962 A Concise Dictionary of Middle Egyptian. Oxford: The Griffith Institute, University Press. 1969 The Ancient Egyptian Pyramid Texts. Oxford: Oxford University Press. 1978 The Ancient Egyptian Coffin Texts Vol. III. Spells 788-1185 and Indexes. Warminster: Aris & Phillips. 1990 The Ancient Egyptian Book of the Dead. London: British Museum Publications. FISCHER, H.G. 1970 Egyptian Art. Bulletin of the Metropolitan Museum of Art 28 (1969- 1970): 69-70. New York: The Metropolitan Museum of Art. 1996 The Tomb of Ip at el Saff. New York: Metropolitan Museum of Art. FLORES, D.V. 1999 The Funerary Sacrifice of Animals during the Predynastic Period. Graduate Department of Near and Middle Eastern Civilizations, University of Toronto. Ottawa: National Library of Canada. FRANKE, D. 2003 The Middle Kingdom Offering Formulas: A Challenge. JEA 89: 39-57. FRÉDÉRICQ, M. 1927 The Ointment Spoons in the Egyptian Section of the British Museum. JEA 13: 7-13. FREED, R. E. 1982a Cosmetic Arts. Egypt’s Golden Age: The Art of Living in the New Kingdom 1558 – 1085 B.C., ed. Brovarski et al, 199-215. Exhibition Catalogue. Boston: Museum of Fine Arts. 226 1982b Egypt’s Golden Age: The Art of Living in the New Kingdom 1558- 1085 B.C. A Picture Book. Boston: Museum of Fine Arts. FRIEDMAN, R.F. 1994 Predynastic Settlement Ceramics of Upper Egypt: A Comparative Study of the Ceramics of Hemamieh, Nagada, and Hierakonpolis. Ann Arbor: UMI Dissertation Services, Bell & Howell Company. 1999 Pots, Pebbles and Petroglyphs Part II: 1996 Excavations at Hierakonpolis Locality HK64, in Leahy, A. and J. Tait (eds) Studies on Ancient Egypt in Honour of H.S. Smith, Occasional Publication 13: 101-108. London: EES. 2004 Elephants at Hierakonpolis, in Hendrickx, S, R.F Friedman, K.M. _ _›_@ #__ ___ œ__ __›__ #% _ Z__•_ Egypt at its Origins. Studies in Memory of Barbra Adams. OLA 138: 131-168. Leuven: Peeters. GABALLA, G.A. 1976 Narrative in Egyptian Art. DAIK. Mainz: Philipp von Zabern. GAILLARD, C. and G. DARESSY 1905 La Faune Momifiée de L’Antique Égypte. CG. Cairo: IFAO. GALÁN, J.M. 2000 The Ancient Egyptian Sed-Festival and the Exemption from Corvée. JEA 59: 255-264. GAMER-WALLERT, I. 1970 Fische und Fischkulte im alten Ägypten. ÄA 21. GARDINER, A.H. 1931 The Chester Beatty Papyri, no. I. Oxford: Oxford University Press. 1932 Late Egyptian Stories. Bibliotheca Aegyptiaca I. Brussels: Édition de la foundation Égyptologique Reine Élisabeth. 1955 The Ramesseum Papyri. Oxford: Griffith Institute, the University Press. 1957 Egyptian Grammar. Being an Introduction to the Study of Hieroglyphs. 3 rd edition. Griffith Instituite. Oxford: Oxford University Press. GARSTANG, J. 1901 El Arábah. Egyptian Research Account 6. London: Bernard Quaritch. GAUTHIER, H. 1908 Rapport sur une campagne de fouilles à Drah Abou’l Neggah en 1906. BIFAO 6: 121-171. 1913 Cercueils anthropoïdes des prétres de Montou, Nos 41042 – 41072. CG. Cairo: IFAO. 1925- Dictionnaire de noms géographiques contenus dans les texts 1931 hiéroglyphiques. T. 1-7. Cairo: Societé Royale de Géographie d’Égypte. 227 GENTRY, A.W. 1971 Genus Gazella, in Meester J. and H.W. Setzer (eds), The Mammals of Africa: an Identification Manual, Part 15.1, 85-93. Washington: Smithsonian Institution Press. GERMOND, P. 1989 L’oryx, un mal-aime du bestiaire egyptien. BSEG 13: 51-55. GIVEON, R. 1984 Skarabäus. LÄ V: 969-981. GOEBS, K. 2001 Crowns, in Redford, D. B. (ed.) The Oxford Encyclopedia of Ancient Egypt 1, 321-326. New York: Oxford University Press. 2008 Crowns in Egyptian Funerary Literature: Royalty, Rebirth, and Desctruction. Oxford: Griffith Institute GOEDICKE, H. 1957 Das Verhältnis zwischen königlichen und privaten Darstellungen im Alten Reich. MDAIK 15: 57-67. 1971 Re-Used Blocks from the Pyramid of Amenemhet I at Lisht. Publications of the Metropolitan Museum of Art Egyptian Expedition, Volume XX. New York: The Metropolitan Museum of Art. GOLDWASSER, O. 1995 From Icon to Metaphor. Studies in the Semiotics of the Hieroglyphs. OBO 142. GOMAÀ, F. 1977 Komir. LÄ III: 684. GRAHAM, G. 2001 Insignias, in Redford, D.B. (ed.) The Oxford Encyclopedia of Ancient Egypt 2, 163-167. New York: Oxford University Press. GRAINDORGE-HÉREIL, C. 1994 Le Dieu Sokar à Thèbes au Nouvel Empire. Tome 1: Textes. Göttinger Orientforschungen IV Reihe Ägypten. Band 28,1. Wiesbaden: Harrassowitz Verlag. GRIFFITH, F.L. and P.E. NEWBERRY 1895 El-Bersheh II. Archaeological Survey of Egypt 4. London: EEF. GRIFFITHS, J. G. 1960 The Conflict of Horus & Seth. A Study in Ancient Mythology From Egyptian and Classical Sources. Liverpool Monographs in Archaeology and Oriental Studies. Liverpool: Liverpool University Press. 228 1980 The Origins of Osiris and His Cult. Studies in the History of Religions XL. Leiden: Brill. GUNDLACH, R. 1980 Mentuhotep IV. Und Min. SAK 8: 89-114. HABACHI, L. 1950 Was Anukis Considered as the Wife of Khnum or as His Daughter? ASAE 50: 501-507. 1957 The Graffiti and Works of the Viceroys of Kush in the Region of Aswan. KUSH V: 13-36. Khartoum: The Sudan Antiquities Service. 1977 Tavole d’offerta are e bacili da libagione n. 22001-22067. Catalogo del Museo Egizio di Torino II. Serie Seconda – Collezioni. Turin: Edizioni D’Arte Fratelli Pozzo. HABACHI, L. and W. KAISER 1985 Ein Friedhof der Maadikultur bei es-Saff. MDAIK 41: 43-46. HANNIG, R. 1995 Grosses Handwörterbuch Ägyptisch-Deutsch. Kulturgeschichte der Antiken Welt 64. Mainz: Philipp von Zabern. HARPUR, Y. 1987 Decoration in Egyptian Tombs of the Old Kingdom. Studies in Orientation and Scene Content. Studies in Egyptology. London/New York: Kegan Paul International. 2001 The Tombs of Nefermaat and Rahotep at Maidum. Discovery, Destruction and Reconstruction. Egyptian Tombs of the Old Kingdom: Volume One. Oxford: Oxford Expedition to Egypt. HARVEY, S.P. 2001 Tribute to a Conquering King. Battle Scenes at Abydos Honor a Pharaoh’s Triumph over Hyksos Occupiers and his Reunification of Egypt, Archaeology, New York 54, no. 4, pp. 52-55. HASSAN, F. A. 1992 Primeval Goddess to Divine King. The Mythogenesis of Power in the Early Egyptian State, in Friedman, R. and B. Adams (eds) The Followers of Horus. Studies dedicated to Michael Allen Hoffman, 307- 322. Egyptian Studies Association Publication no. 2. Oxford: Oxbow. HASSAN, S. 1938 Excavations at Saqqara 1937-1938. ASAE 38: 503-521. 1944 Excavations at Giza V 1933 -1934. Service des Antiquités de l’Égypte. Cairo: Government Press. 1948 Excavations at Giza VI:2. The Offering-List in the Old Kingdom. Text and Plates. Cairo: Government Press. 229 1951 Excavations at Giza VI:3 1934-1935. Service des Antiquités de l’Égypte. Cairo: Government Press. 1953 Excavations at Giza VIII: 1936-1937. The Great Sphinx and its Secrets. Historical Studies in the Light of Recent Excavations. Cairo: Government Press. 1975a The Mastaba of Neb-Kaw-Her. Excavations at Saqqara 1937- 1938, Volume I. Cairo: General Organisation for Government Printing Offices. 1975b Mastabas of Ny- c ankh-Pepy and Others. Excavations at Saqqara 1937-1938, Volume II. Cairo: General Organisation for Government Printing Offices. 1975c Mastabas of Princess Hemet-R c and Others. Excavations at Saqqara 1937-1938, Volume III. Cairo: General Organisation for Government Printing Offices. HAYES, W.C. 1953 The Scepter of Egypt I. From the Earliest Times to the End of the Middle Kingdom. New York: Harper & Brothers with the Metropolitan Museum of Art. 1959 The Scepter of Egypt II. The Hyksos Period and the New Kingdom (1675-1080 B.C.). New York/Cambridge: Harvard University Press HELCK, W. 1955 Urkunden der 18. Dynastie. Urkunden des aegyptischen Altertums IV:17 (Seite 1227-1645). Berlin: Akademie-Verlag. 1957 Urkunden der 18. Dynastie. Urkunden des aegyptischen Altertums IV:19 (Seite 1539-1775). Berlin: Akademie-Verlag. 1963 Materialen zur Wirtschaftsgeschichte des Neuen Reiches (Teil III). Wiesbaden: Otto Harrassowitz. 1968 Ritualszenen in Karnak. MDAIK 23: 117-137. 1977 Gaue. LÄ II: 385-408. HENDRICKX, S. 1996 The Relative Chronology of the Naqada Culture: Problems and Possibilities, in Spencer, A. J. (ed.) Aspects of Early Egypt, 36- 69. London: British Museum Press. HENEIN, N. 2001 Du disque de Hemaka au filet hexagonal du lac Manzala. Un example de pérennité des techniques de chasse antiques. BIFAO 101: 237-248. HICKMANN, H. 1949 Instruments de musique (Nos 69201-69852). CG. Cairo: IFAO. HODJASH, S. and O. BERLEV 1982 The Egyptian Reliefs and Stelae in the Pushkin Museum of Fine Arts, Moscow. Leningrad: Aurora Art Publishers. 230 HOFFMEIER, J.K. 1975 Hunting Desert Game with the Bow: a Brief Examination. JSSEA 6:2: 8-13. 1980 Comments on Unusual Royal Hunt Scenes from the New Kingdom. JSSEA 10:3: 195-200. HORNUNG, E. 1973 Bedeutung und Wirklichkeit des Bildes im alten Ägypten, in Kunst und Realität, Akademische Vorträge, gehalten an der Universtät Basel 8: 35-46. Basel: Verlag von Helbing und Lichtenhahn. 1990 The Valley of the Kings. Horizon of Eternity. (English transl. D. Warburton). New York/Zürich/Munich: Timken Publishers/Artemis Verlag. HORNUNG, E. and E. STAEHELIN 1976 Skarabäen und andere Siegelamulette aus Basler Sammlungen. Ägyptische Denkmäler in der Schweiz, Band I. Mainz: Philipp von Zabern. HOULIHAN, P.F. 1986 The Birds of Ancient Egypt. Cairo: The American University Press. 1996 The Animal World of the Pharaohs. London/New York: Thames and Hudson. 2002 Animals in Egyptian Art and Hieroglyphs HdO 64: 97-143. Leiden: E.J. Brill. IKRAM, S. 1991 Animal Mating Motifs in Egyptian Funerary Representations. GM 124: 51-68. 1995 Choice Cuts: Meat Production in Ancient Egypt. OLA 69. Leuven: Peeters. 2003a Death and Burial in Ancient Egypt. London: Longman. 2003b Hunting Hyenas in the Middle Kingdom: the Appropriation of a Royal Image?, in Grimal, N., A. Kamel and C. May-Sheikholeslami (eds), Hommage à Fayza Haikal, 141-147. BdE 138. IKRAM, S. and A. DODSON 1998 The Mummy in Ancient Egypt. Equipping the Dead for Eternity. London: Thames & Hudson. INCONNU-BOCQUILLON, D. 2001 Le mythe de la Déesse Lointaine à Philae. BdE 132. JACQUET-GORDON, H.K. 1962 Les noms des domains funéraires sous l’Ancien Empire Égyptien. BdE 34. Cairo: IFAO. 231 JANSSEN, R.M. and J.J. JANSSEN 1990 Growing up in Ancient Egypt. London: Rubicon. JAROŠ-DECKERT, B. 1984 Grabung im Asasif 1963-1970, vol. V. Das Grab des Jnj-jtj.f. Die Wandmalereien der XI. Dynastie. AV 12. JÉQUIER, G. 1938 Le monument funéraire de Pepi II, in Fouilles à Saqqarah 18:2, 1- 72. Cairo: IFAO. JUNKER, H. 1911 Der Auszug der Hathor-Tefnut aus Nubien. Berlin: Verlag der Königl. Akademie der Wissenschaften/Georg Reimer. 1934 Giza II. Grabungen auf dem Friedhof des Alten Reiches bei den Pyramiden von Giza. Die Mastaba der beginnenden V. Dynastie auf dem Westfriedhof. Akademie der Wissenschaften in Wien. Philosophisch-historische Klasse. Vienna/Leipzig: Hölder-Pichler- Tempsky A.G. 1938 Giza III. Grabungen auf dem Friedhof des Alten Reiches bei den Pyramiden von Giza. Die Mastabas der vorgeschrittenen V. Dynastie auf dem Westfriedhof. Akademie der Wissenschaften in Wien. Philosophisch-historische Klasse. Vienna/Leipzig: Hölder- Pichler-Tempsky A.G. 1950 Giza IX. Grabungen auf dem Friedhof des Alten Reiches bei den Pyramiden von Giza. Das Mittelfeld des Westfriedhofs. Akademie der Wissenschaften in Wien. Philosophisch-historische Klasse. Denkschriften, 73. Band, 2. Abhandlung. Vienna: Rudolf M. Rohrer. 1953 Giza XI. Grabungen auf dem Friedhof des Alten Reiches bei den Pyramiden von Giza. Der Friedhof südlich der Cheopspyramide, Ostteil. Akademie der Wissenschaften in Wien. Philosophisch- historische Klasse. Denkschriften, 74. Band, 2. Abhandlung. Vienna: Rudolf M. Rohrer. KÁKOSY, L. 1977 Horusstele. LÄ III: 60-62. 1998 A Horus Cippus with Royal Cartouches. Egyptian Religion the Last Thousand Years, Part I, in Clarysse, W., A. Schoors and H. Willems (eds) Studies Dedicated to the Memory of Jan Quaegebeur. OLA 84: 125-137. Leuven: Peeters. KAMPP, F. 1996 Die thebanischen Nekropole: Zum Wandel des Grabgedankens von der XVIII. Bis zur XX. Dynastie (= Theben 13). Teil 1, 2. Mainz am Rhein: Verlag Philipp von Zabern. 232 KANAWATI, N. 1980 The Rock Tombs of El-Hawawish. The Cemetery of Akhmim. Volume I. The Macquire Ancient History Association, Macquire University, Sydney. Warminster: Aris & Phillips. 1981 The Rock Tombs of El-Hawawish. The Cemetery of Akhmim. Volume II. The Macquire Ancient History Association, Macquire University, Sydney. Warminster: Aris & Phillips. 1987 The Rock Tombs of El-Hawawish. The Cemetery of Akhmim. Volume VII. The Ancient History Documentary Research Centre, Maquire University, Sydney. Warminster: Aris & Phillips. 1988 The Rock Tombs of El-Hawawish. The Cemetery of Akhmim. Volume VIII. The Ancient History Documentary Research Centre, Macquire University, Sydney. Warminster: Aris & Phillips. KANAWATI, N. and M. ABDER-RAZIQ 1998 The Teti Cemetery at Saqqara, Volume III. The Tombs of Neferseshemre and Seankhuiptah. ACE Reports 11. Sydney. 1999 The Teti Cemetery at Saqqara, Volume V. The Tomb of Hesi. ACE Reports 13. Sydney. KANAWATI, N. and A. MCFARLANE 1993 Deshasha. The tombs of Inti, Shedu and Others. ACE Reports 5. Sydney. KAPLONY, P. 1986 Zepter. LÄ VI: 1373-1389. KEEL, O. 1980 Böcklein in der Milch Seiner Mutter und Verwandtes. Im Lichte eines altorientalischen Bildmotivs. OBO 33. KEES, H. 1941 Der Götterglaube im alten Aegypten. Leipzig: J.C. Hinrichs Verlag. KEIMER, L. 1940 Sur un monument égyptien du musée du Louvre. Contribution à l’histoire de l’égyptologie. RdE IV: 45-65. 1954 Remarques sur les ”cuillers à fard” du type dit à la nageuse. ASAE 52: 59-72. KEMP, B. 2006 Ancient Egypt. Anatomy of a Civilization (second edition). London and New York: Routledge, Taylor & Francis Group. 233 KEPINSKI, C. 1982 L’arbre stylisé en Asie Occidentale au 2 e millénaire avant J.-C. Bibliothèque de la Délégation Archéologique Française en Iraq n o 1. Centre de Recherche d’Archéologie Orientale – Université de Paris I – n o 1. Volumes I-III. Paris: Éditions Recherche sur les Civilisations. KESSLER, D. 1989 Die Heiligen Tiere und der König. Teil I: Beiträge zu Organisation, Kult und Theologie der spätzeitlichen Tierfriedhöfe. ÄAT 16. KILLEN, G. 1994 Ancient Egyptian Furniture II. Boxes, Chests and Footstools. Warminster: Aris & Phillips. KINGDON, J. 1997 The Kingdon Field Guide to African Mammals. London: Academic Press, Harcourt Brace & Company. KLEBS, L. 1915 Reliefs des alten Reiches (2980-2475 v. Chr.), Material zur ägyptischen Kulturgeschichte. Abhandlungen der Heidelberger Akademie der Wissenschaften 3, Phil-hist. Kl. Heidelberg: Carl Winters Universitätsbuchhandlung. 1922 Die Reliefs und Malereien des mittleren Reiches (VII. – XVII. Dyanstie ca 2475-1580 v. Chr.). Abhandlungen der Heidelberger Akademie der Wissenschaften 6, Phil-hist. Kl. Heidelberg: Carl Winters Universitätsbuchhandlung. 1934 Die Rliefs und Malereien des neuen Reiches (XVIII.–XX. Dynastie, ca. 1580-110 v.Chr.). Abhandlungen der Heidelberger Akademie der Wissenschaften 9, Phil-hist. Kl. Heidelberg: Carl Winters Universitätsbuchhandlung. KOZLOFF A.P. and B.M. BRYAN 1992 Egypt’s Dazzling Sun. Amenhotep III and His World. Exhibition Catalogue. Cleveland: Indiana University Press. KUENTZ, C. 1981 Bassins et tables d’offrandes. Bulletin du centenaire, supplément au BIFAO 81: 243-282. LABROUSSE, A. and A. MOUSSA 2002 La chaussée du complexe funéraire du roi Ounas. BdE 134. LECA, A-P. 1971 La medicine égyptienne au temps des pharaohs. Paris: Dacosta. 234 LECLANT, J. 1954 Fouilles et travaux en Égypte, 1952-1953: 64-79 in Orientalia 23, Nova Series. Rome: Pontificium Institutum Biblicum. LEFEVBRE, M.G. 1924 Le Tombeau de Petosiris. Service des Antiquités de l’Égypte. Cairo: IFAO. LEIBOVITCH, J. 1939 Quelques Nouvelles Représentations di Dieu Rechef. ASAE 39: 145-160. LEITZ, C. et al 2002a Lexikon der ägyptischen Götter und Götterbezeichnungen. Band II: . OLA 111. Peeters. 2002b Lexikon der ägyptischen Götter und Götterbezeichnungen. Band VI: . OLA 115. Peeters. 2002c Lexikon der ägyptischen Götter und Götterbezeichnungen. Band VII: . OLA 116. Peeters. LEPSIUS, R. 1849- Denkmäler aus Aegypten und Aethiopien, Volumes I and II. Collection 59 publiée sous de l’égide du centre de documentations du monde orientale. Reprint 1972. Geneva: Belle-Lettres. LÉVI-STRAUSS, C. 1963 Totemism. Boston: Beacon Press. LICHTHEIM, M. 1976 Ancient Egyptian Litterature. A Book of Readings. Volume II: The New Kingdom. Berkely/Los Angeles/ London: University of California Press. LILYQUIST, C. 2003 The Tomb of Three Foreign Wives of Tuthmosis III. The Metropolitan Museum of Art. New York. New Haven/London: Yale University Press. LORTET, L-C. and C. GAILLARD 1903 Faune Momifiée de l’Ancienne Égypte I. Lyon: Muséum d’Histoire naturelle. MACRAMALLAH, R. 1935 Le Mastaba d’Idout. Fouilles à Saqqarah 16. Cairo: IFAO. MALAISE, M. 1976 Histoire et signification de la coiffure hathorique à plumes. SAK 4: 215-236. MALEK, J. 1993 The Cat in Ancient Egypt. London: British Museum Press. MANNICHE, L. 1988 Lost Tombs. A Study of Certain Eighteenth Dynasty Monuments in the Theban Necropolis. London/New York: Kegan Paul International. 235 MARIETTE, A. 1869 Abydos. Description des Fouilles I. Paris: Libraire A. Franck. MARTIN, K. 1984 Sedfest. LÄ V: 782-790. MARTÍN DEL RÍO ÁLVAREZ, C. and E. ALMENARA 2004 An Analysis of the Theriomorphic Representations on Combs and Hairpins from the Prenyastic Period in Hendrickx, S., R.F. Friedman, K.M. _ _›_@ #_____œ____›__ #% _Z__•_Egypt at its Origins. Studies in Memory of Barbara Adams. OLA 138: 881-889. Leuven: Peeters. MASPERO, G. 1889 Les momies royales de Déir el-Baharî. Mémoires publiés par les members de la Mission Archéologique Française au Caire, Tome 1, Fasc. 4: 511-788. Paris: Ernest Leroux. 1912 Art in Egypt. Ars Una: Species Mille. General History of Art. London: William Heinemann. MATHIEU, B. 1996 La poési amoureuse de l’Égypte ancienne. Reserches sur un genre littéraire au Nouvel Empire. BdE 115. Cairo: IFAO. MATOUK, F.S. 1977 Corpus du Scarabée Egyptien II. Analyse Thématique. Beirut: L’imprimerie catholique. MCARDLE, J.E. 1992 Preliminary Observations on the Mammalian Fauna from Predynastic Localities at Hierakonpolis in Friedman, R. and B. Adams (eds) The Followers of Horus. Studies dedicated to Michael Allen Hoffman, 53- 56. Egyptian Studies Association Publication no. 2. Oxford: Oxbow. MCLEOD, W. 1982 Self Bows and Other Archery Tackle from the Tomb of Tut’ankhamun. The Tut’ankhamun’s Tomb Series IV. Oxford: Griffith Institute. MEEKS, D. 1977 Hededet. LÄ II: 1076-1078. MEKHITARIAN, A. 1978 Egyptian Painting. London: MacMillan. MENDELSSOHN, H., Y. YOM-TOV and C.P. GROVES 1995 Gazella gazella. Mammalian Species 490: 1-7. The American Society of Mammalogists. 236 EL-METWALLY, E. 1992 Entwicklung der Grabdekoration in den altägyptischen Privatgräbern. Ikonographische Analyse der Totenkultdarstellungen von der Vorgeschichte bis zum Ende der 4. Dynastie. GOF IV/24. Wiesbaden de MEULENAERE. H. and L. LIMME 1988 Egypte in Musées royaux d’art et d’histoire, Bruxelles, 11-49. Musea Nostra. Brussels: Credit Communal. MIDANT-REYNES, B. 1987 Contribution à l’étude de la société prédynastique. SAK 14: 185-224. 1994 Égypte prédynastique et art rupestre in Berger, C., G. Clerc and N. Grimal (eds) Hommages à Jean Leclant IV: Varia: 229-235. BdE 106/4. 2000 The Prehistory of Egypt. From the First Egyptians to the First Pharaohs. Paris/Oxford: Blackwell. MILLET, N.B. 1990 The Narmer Macehead and Related Objects. JARCE XXVII: 53-59. MILWARD, A.J. 1982 Bowls. Egypt’s Golden Age: The Art of Living in the New Kingdom 1558-1058 B.C., ed. Brovarski et al, 141-145. Exhibition catalogue. Boston: Museum of Fine Arts. MOHR, H.T. 1943 The Mastaba of Hetep-her-akhti. Study on an Egyptian Tomb Chapel in the Museum of Antiquities Leiden in Mededeelingen en Verhandelingen N o 5 van het Vooraziatisch-Egyptisch Gezelschap ”Ex Oriente Lux”. Leiden: Brill. MONNET SALEH, J. 1983 Les représentations de temples sur plates-formes à pieux, de la poterie gerzéenne d’Égypte. BIFAO 83: 263-296. MONTET, P. 1937 Les reliques de l’art syrien dans l’Égypte du Nouvel Empire. Publications de la faculté des lettres de l’université de Strasbourg. Paris: Les Belles Lettres. MORENO GARCÍA, J. C. 2008 Estates (Old Kingdom), in Frood, E. and W. Wendrich (eds) UCLA Encyclopedia of Egyptology. Los Angeles. nelc/uee/1012 MORET, M. A. 1913 Sarcophages de l’époque bubastite a l’époque saïte, Nos 41001- 41041. CG. Cairo: IFAO. 237 DE MORGAN, J. et al. 1894 Catalogue des monuments et inscriptions de l’Égypte antique, Service des antiquités Volume 1. Vienna: Holzhausen. MOSTAFA, M.M.F. 1982 Untersuchungen zu Opfertafeln im Alten Reich. HÄB 17. MOUSSA, A.M. and H. ALTENMÜLLER 1977 Das Grab des Nianchchnum und Chnumhotep. Old Kingdom Tombs at the Causeway of King Unas at Saqqara. AV 21. MÜLLER, H.W. 1940 Die Felsengräber der Fürsten von Elephantine. ÄF 9. MULLIN, M.H. 1999 Mirrors and Windows: Sociocultural Studies of Human-Animal Relationships. Annual Review of Antrolopology 28: 201-242. MURRAY, M. A. 1905 Saqqara Mastabas I. Egyptian Research Account 10, Tenth Year. London: Bernard Quaritch. MUZZOLINI, A. 1986 L’art rupestre préhistorique des massifs centraux sahariens. Cambridge Monographs in African Archaeology 16. Oxford: BAR International Series 318. NAVILLE, E. 1891 Bubastis (1887-1889). Egypt Exploration Fund, Eighth Memoir. London: Kegan Paul, Trench, Trübner & Co. 1892 The Festival-Hall of Osorkon II in the Great Temple of Bubastis (1887- 1889). Egypt Exploration Fund 10. London: Kegan Paul, Trench, Trübner & Co. 1912 Papyrus Funéraires de la XXI e Dynastie. Le Papyrus hiéroglyphique de Kamara et Le Papyrus hiératique de Nesikhonsou Au Musée du Caire. Paris: Ernest Leroux. NAVILLE, E. and H.R. HALL 1913 The Xith Dynasty Temple at Deir el-Bahari Part III. Egypt Exploration Fund, Thirty-Second Memoir. London: EEF. NAVILLE, E. and H.R. HALL and E.R. AYRTON 1907 The Xith Dynasty Temple at Deir el-Bahari Part I. Egypt Exploration Fund, Twenty-Eighth Memoir. London: Paul, Trench, Trübner & Co. NEEDLER, W. 1984 Predynastic and Archaic Egypt in The Brooklyn Museum. New York: The Brooklyn Museum. 238 NEWBERRY, M.P.E. 1893 Beni Hassan I. Archaeological Survey of Egypt 1. London: EEF. 1894 Beni Hassan II. Archaeological Survey of Egypt 2. London: EEF. 1895 El-Bersheh I. The tomb of Tehuti-Hetep. Archaeological Survey of Egypt 3. London: EEF. 1906 Egyptian Antiquities – Scarabs. An Introduction to the Study of Egyptian Seals and Signet Rings. University of Liverpool. Institute of Archaeology. London: Archibald Constable and Co. O’CONNOR, D. 2002 Context, Function and Program: Understanding Ceremonial Slate Palettes. JARCE XXXIX: 5-25. Cairo. OSBORN, D. 1987 Corrections in the Identifications of the Alabaster Ibexes in Tutankhamun’s Treasures. JEA 73: 243-244. 1998 The Mammals of Ancient Egypt. The Natural History of Egypt: Vol. IV. Warminster: Aris & Phillips. OTTO, E. 1950 An Ancient Egyptian Hunting Ritual. JNES 9: 164-177. 1975a Anuket. LÄ I: 333-334. 1975b Ghnum. LÄ I: 950-754. PARIS 1981 Un siècle de fouilles françaises en Égypte 1880-1980. A l’occasion du centenaire de l’école du Caire (IFAO). Musée d’art et d’essai – Palais de Tokyo. Paris: École du Caire – Musée du Louvre. 1993 Rites et beauté: objets de toilette égyptiens. Musée du Louvre. Paris: Musée du Louvre. Département des antiquités égyptiennes. PECK, W.H. 1982 Spoons and Dishes. Egypt’s Golden Age: The Art of Living in the New Kingdom 1558-1058 B.C., ed. Brovarski et al, 212-214. Exhibition catalogue. Boston: Museum of Fine Arts. PÉCOIL, J-F. 1993 Les sources mythiques du Nil et le cycle de la crue. BSEG 17: 97-110. PETERSON, B.E.J. 1973 Zeichnungen aus einer Totenstadt. The Museum of Mediterranean and Near Eastern Antiquities, Bulletin 7-8. Stockholm. PETRIE, W.M.F. 1891 Illahun, Kahun and Gurob: 1889-90. London: David Nutt. 1892 Medum. London: David Nutt. 1898 Deshasheh: 1897. Egypt Exploration Fund 15. London: EEF. 239 1901 Diospolis Parva. The Cemeteries of Abadiyeh and Hu 1898-9. The Egypt Exploration Fund, the 20 th Memoir. London: EEF. 1903 Abydos II. Egypt Exploration Fund 24. London: EEF. 1907 Gizeh and Rifeh. British School of Archaeology in Egypt and Egyptian Research Account 13. London: Office of School of Archaeology, University College & Bernard Quaritch. 1920 Prehistoric Egypt. British School of Archaeology in Egypt and Egyptian Research Account 31. London: British School of Archaeology in Egypt, University College & Bernard Quaritch. 1921 Corpus of Prehistoric Pottery and Palettes. British School of Archaeology in Egypt and Egyptian Research Account 32. London: British School of Archaeology in Egypt, University College & Constable & Co. Ltd & Bernard Quaritch. 1925 Button and Design Scarabs. British School of Archaeology in Egypt 38. London: British School of Archaeology in Egypt, University College & Bernard Quaritch. 1953 Ceremonial Slate Palettes. British School of Archaeology LXVI A. London: PETRIE, W. M. F. and J.E. QUIBELL 1896 Naqada and Ballas 1895. British School of Egyptian Archaeology I. London: Bernard Quaritch. PINCH, G. 1993 Votive Offerings to Hathor. Oxford: Oxford University Press. VAN DER PLAS, D. 1986 L’hymne a la crue du Nil. Tome I: Traduction et commentaire. Leiden: Nederlands Instituut voor het Nabije Oosten. POO, M-C. 1995 Wine and Wine Offering in the Religion of Ancient Egypt. Studies in Egyptology. London and New York: Kegan Paul International. PORTER, B. and R.B. MOSS 1934 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. IV Lower and Middle Egypt. Oxford: The Griffith Institute, Oxford University Press. 1937 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. V Upper Egypt: Sites. Oxford: The Griffith Institute, Oxford University Press. 1939 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. VI Upper Egypt: Chief Temples (Excluding Thebes). Oxford: The Griffith Institute, Oxford University Press. 240 1951 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. VII Nubia, the Deserts, and Outside Egypt. Oxford: The Griffith Institute, Oxford University Press. 1960 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography I:1 Theban Necropolis, Private Tombs. 2 nd Edition. Oxford: The Griffith Institute, Oxford University Press. 1964 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography I:2 Theban Necropolis. Royal Tombs and Smaller Cemeteries. 2 nd Edition, Oxford: The Griffith Institute, Oxford University Press. 1972 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography II Theban Temples. 2 nd Edition. Oxford: The Griffith Institute, Oxford University Press. 1974 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography III:1 Memphis. Abû Rawâsh to Abûsîr. 2 nd Edition. Oxford: The Griffith Institute, Oxford University Press. 1978 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography III:2. Fasc. 1 Memphis. Saqqâra to Dashûr. 2 nd Edition. Oxford: The Griffith Institute, Oxford University Press. 1979 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography Memphis III:2. Fasc. 2 Memphis, Saqqâra to Dashûr. 2 nd Edition. Oxford: The Griffith Institute, Oxford University Press. 1981 Topographical Bibliography of Ancient Egyptian Hieroglyphic Texts, Reliefs, and Paintings. Topographical Bibliography Memphis III:2. Fasc. 3 Saqqâra to Dashûr. 2 nd edition. Oxford: The Griffith Institute, Oxford University Press. PUSCH, E., 1979 Das Senet-Brettspiel im Alten Ägypten. MÄS 38. QUAEGEBEUR, J. 1999 La Naine et le Bouquetin ou L’Énigme de la Barque en Albâtre de Toutankhamon. Leuven: Peeters. QUIBELL, J.E. 1900 Hierakonpolis I. Egyptian Research Account, Fourth Memoir. London: Bernard Quaritch. 1908 Tomb of Yuaa and Thuiu. CG 51001-51191. Cairo: IFAO. 1912 Excavations at Saqqara (1908-9, 1909-10). The Monastery of Apa Jeremias. Fouilles à Saqqarah 4. Cairo: IFAO. 241 QUIBELL, J.E. and F.W. GREEN 1902 Hierakonpolis II. Egyptian Research Account 5. London: Bernard Quaritch. RADOMSKA, B. 1991 Gedanken zum Lehnstuhl der Königstochter Sat-Amun (CG 51113) in Verhoeven, U. and E. Graefe (eds) Religion und Philosophie im alten Ägypten. Festgabe für Philippe Derchain zu seinem 65. Geburtstag am 24. Juli 1991. OLA 39: 269-275. RANKE, H. 1935 Die Ägyptischen Personenamen I. Verzeichnis der Namen. Glückstadt: Verlag von J.J. Augustin. REEVES, N. 1990 The Complete Tutankhamun. London: Thames & Hudson. RITNER, R.K. 1993 The Mechanics of Ancient Egyptian Magical Practice. SAOC 54. Chicago: University of Chicago Press. ROBINS, G. 1990 Problems in Interpreting Egyptian Art. DE 17: 45-58. 1997 The Art of Ancient Egypt. London: The British Museum Press. 1998 Piles of Offerings: Paradigms of Limitation and Creativity in Ancient Egyptian Art, in Eyre C. (ed.) The Proceedings of the Seventh International Congress of Egyptologists: Cambridge, 3-9 September 1995. OLA 82: 957-963. Leuven: Peeters. ROEDER, M.G. 1938 Der Felsentempel von Beit el-Wali. Les Temples Immergés de la Nubie 13. Cairo: IFAO. RÖSSLER-KÖHLER, U. 1982 Pap. Jumilhac. LÄ IV: 708-712. ROTH, A.M. 1995 A Cemetery of Palace Attendants. Giza Mastabas 6. Boston: Department of Egyptian and Near Eastern Art, Museum of Fine Arts. ROUBET, C. and M.N. EL-HADIDI 1981 20.000 ans d’environment préhistorique dans la vallée du Nil et le désert Égyptien, in Bulletin du centenaire, supplément au BIFAO 81: 445-470. Cairo. 242 ROWE, A. 1938 New Light on Objects belonging to the Generals Potasimto and Amasis in the Egyptian Museum. ASAE 38: 157-195. SAAD, Z. 1943 Preliminary Report on the Excavations of the Department of Antiquities at Saqqara 1942-43. ASAE 43: 449-457. SAUNERON, S. 1953 Représentation d’Horus-Ched à Karnak. BIFAO 52: 53- 55. 1968 Le temple d’Esna. Esna III. Cairo: IFAO. 1975 Le temple d’Esna. Esna VI 1 . Cairo: IFAO. SÄVE-SÖDERBERGH, T. 1953 On Egyptian Representations of Hippopotamus Hunting as a Religious Motive. Horae Soederblomianae III. Uppsala/Lund: C.W.K. Gleerup. 1957 Four Eighteenth Dynasty Tombs. Private Tombs at Thebes I. Oxford: The Griffith Institute, Oxford University Press. 1958 Eine Gastmahlsszene im Grabe des Schatzhausvorstehers Djehuti. MDAIK 16: 280-291. 1960 The Paintings in the Tomb of Djehuty-hetep at Debeira. KUSH 8: 25-44. SCHÄFER, H. 1974 Principles of Egyptian Art (English transl. by John Baines). Oxford: Griffith Institute. SCHEIL, V. 1894 Le Tombeau d’Aba. Mémoires publiés par les membres de la Mission Archéologique Française du Caire V: 624-656. Paris: A. Bourdin et Cie. SCHENKEL, W. 1965 Memphis – Herakleopolis – Theben. Die epigraphischen Zeugnisse der 7. -11. Dynastie der Ägyptens. ÄA 12. SCHIFF GIORGINI, M. 1998 Soleb V. Le temple. Bas-reliefs et inscriptions. Cairo: IFAO. SCHOFIELD, A.F. 1959 Aelian. On the Characters of Animals, Books VI-XI. London: William Heinemann Ltd/Cambridge: Harvard University Press. SCHULMAN, A.R. 1979 The Winged Reshep. JARCE XVI: 69-84. 243 SCHWEITZER, U. 1948 Löwe und Sphinx im alten Ägypten. ÄF 15. SCOTT, A. 1927 Notes on Objects from the Tomb of King Tutankhamen. Appendix IV, pp. 197-213, in The Tomb of Tutankhamen, Volume II. London/Toronto/Melbourne/Sydney: Cassell and Company. SEIPEL, W. et al. 2001 Gold der Pharaonen. Exhibition catalogue 27 th November 2001 – 17 th March 2002. Kunsthistorisches Museum. Vienna: Kunsthistorisches Museum/Milan: Skira editore. SETHE, K. 1907 Urkunden der 18. Dynastie, Dritter Band. Urkunden des aegyptischen Altertums IV:3 (Seite 625-936). Leipzig: J.C. Hinrichs’sche Buchhandlung. 1908 Altaegyptischen Pyramidentexte I:1; 2. Spruch 1-468 (Pyr. 1-905). Leipzig: J.C. Hinrichs’sche Buchhandlung 1910 Altaegyptischen Pyramidentexte II. Spruch 469-714 (Pyr. 906- 2217). Leipzig: J.C. Hinrichs’sche Buchhandlung. 1928 Dramatische Texte zu altaegyptischen Mysterienspielen. Der Dramatische Ramesseumpapyrus in Spiel zur Thronbesteigung des Königs. Untersuchungen zur Geschichte und Altertumskunde Ägyptens X,2. Leipzig: J.C. Hinrichs’sche Buchhandlung. SHAW, I. 2000 The Oxford History of Ancient Egypt. Oxford: Oxford University Press. SHIRUN-GRUMACH, I. 1993 Offenbarung, Orakel und Königsnovelle. ÄAT 24. SIMPSON, W.K. 1976 The Mastabas of Qar and Idu. Giza Mastabas 2. Boston: Department of Egyptian and Near Eastern Art, Museum of Fine Arts. 1980 The Mastabas of the Western Cemetery: Part I. Giza Mastabas 4. Boston: Department of Egyptian and Near Eastern Art, Museum of Fine Arts. 1984 Reschef. LÄ V: 244-246. SMITH, M.J. 1984 Sonnenauge. LÄ V: 1082- 1087. 244 SMITH, W. S. 1949 Egyptian Sculpture and Painting in the Old Kingdom. Museum of Fine Arts. Boston: Oxford University Press. 1965a Interconnections in the Ancient Near East. A Study of the Relationships between the Arts of Egypt, the Aegean, and Western Asia. New Haven and London: Yale University Press. 1965b The Art and Architecture of Ancient Egypt. Harmondsworth: Penguin Books Ltd. SONESSON, G. 1989 Pictorial Concepts. Inquiries into the semiotic heritage and its relevance to the interpretation of the visual world. Aris Nova Series 4. Lund: Lund University Press. SPALINGER, G. L. 1982 Metal Vessels. Egypt’s Golden Age: The Art of Living in the New Kingdom 1558-1058 B.C., ed. Brovarski et al, 116-125. Exhibition catalogue. Boston: Museum of Fine Arts. SPELEERS, L. 1921 “La Stèle de Maï du Musée de Bruxelles (E. 5300). RT 39: 113-144. SPENCER, A. J. 1982 Death in Ancient Egypt. Harmondsworth: Penguin Books. 1993 Early Egypt. The Rise of Civilisation in the Nile Valley. London: British Museum Press. 1996 Aspects of Early Egypt. London: British Museum Press. SPIESER, C. 2000 Le noms du Pharaon comme êtres autonomes au Nouvel Empire. OBO 174. STEINDORFF, G. 1913 Das Grab des Ti. Veröffentlichungen der Ernst von Sieglin Expedition in Aegypten, Band II. Leipzig: Hinrichs. STEINDORFF, G. and W. WOLF 1936 Die Thebanische Gräberwelt. LÄS 4. STERNBERG-EL HOTABI, H. 1992 Ein Hymnus an die Göttin Hathor und das Ritual ‘Hathor das Trankopfer darbringen’ nach den Tempeltexten der griechisch-römischen Zeit. Rites Egyptiens VII. Brussels: Fondation Égyptologique Reine Élisabeth. 245 1999 I: Textband. ÄA 62. 1999 II: Materialsammlung. ÄA 62. STOLBERG-STOLBERG, A. 2003 Untersuchungen zu Antilope, Gazelle und Steinbock im Alten Ägypten. Berlin: Mensch & Buch Verlag. STÖRCK, L. 1973 Antilope. LÄ I: 319-323. STRAUSS, E-C. 1974 Die Nunschale. Eine Gefässgruppe des Neuen Reiches. MÄS 30. SWAN HALL, E. 1986 The Pharaoh Smites his Enemies. A Comparative Study. MÄS 44. TEFNIN, R. 1979 Image et histoire. Réflexions sur l’usage documentaire de l’image égyptienne. CdE 54: 218-244. 1984 Discours et iconicite dans l’art égyptien. GM 79: 55-69. TOSI, M. 1988 Popular Cults at Deir el-Medina, in Donadoni Roveri, A. M. (ed.) Egyptian Civilization – Religious Beliefs: 162-177. Egyptian Museum of Turin. Milan: Electa. TROY, L. 1986 Patterns of Queenship in Ancient Egyptian Myth and History. Boreas 14. Acta Universitatis Upsaliensis. Uppsala: Department of Egyptology, Uppsala University. 1997 Mut Enthroned in van Dijk, J. (ed) Essays on Ancient Egypt in Honour of Herman te Velde: 300-315. Egyptological Memoirs 1. Groningen: Styx Publications. TUFNELL, O. 1984a Studies on Scarab Seals. Scarab Seals and Their Contribution to History in the Early Second Millennium B.C., Volume Two, Part 1. Warminster: Aris & Phillips. 1984b Studies on Scarab Seals. Scarab Seals and Their Contribution to History in the Early Second Millennium B.C., Volume Two, Part 2. Warminster: Aris & Phillips. 246 VALBELLE, D. 1981 Satis et Anoukis. DAIK. Mainz am Rhein: Philipp von Zabern. 1983 Deux hymnes aux divintés de Komir, Anoukis et Nephthys. BIFAO 83: 159-170. VANDIER, J. 1950 Mo’alla. La Tombe d’Ankhtifi et la Tombe de Sébekhotep. BdE XVIII. 1961 Le Papyrus Jumilhac. Paris: Centre National de la Recherche Scientifique. 1964 Manuel d’archéologie égyptienne IV. Bas-reliefs et peintures. Scènes de la vie quotidienne. Paris: Éditions A. et J. Picard. 1969 Manuel d’archéologie égyptienne V. Bas-reliefs et peintures. Scènes de la vie quotidienne. Paris: Éditions A. et J. Picard. VERHOEVEN, U. and P. DERCHAIN 1985 Le voyage de la déesse libyque. Ein Text aus dem “Mutritual” des Pap. Berlin 3053. Rites Egyptiens V. Brussels: Fondation Égyptologique Reine Élisabeth. VERNER, M. 1977 The Mastaba of Ptahshepses. Abusir I. Prague: Charles University. VAN DE WALLE, B. 1957 Remarques sur l’origine et le sens des défiles de domains dans les mastabas de l’ancien empire. MDAIK 15: 288-296. WALLERT, I. 1967 Der Verzierte Löffel. Seine Formgeschichte und Verwendung im alten Ägypten. ÄA 16. WARD, W. A. 1978 Studies on Scarab Seals. Pre -12 th Dynasty Scarab Amulets, Volume I. Warminster: Aris & Phillips. WEGNER, M. 1933 Stilentwickelung der Thebanischen Beamtengräber. MDAIK 4, Sonder-abdruck. WENGROW, D. 2006 The Archaeology of Early Egypt. Social Transformations in North-East Africa, 10,000 to 2650 BC. Cambridge: Cambridge University Press. WENTE, E.F. 1969 Hathor at the Jubilee. Studies in Honor of John A. Wilson, SAOC 35, 83-91. 1980 Translations of the Texts, in The Tomb of Kheruef, Theban Tomb 192, OIP 102: 30-77. Chicago: The Oriental Institute of the University of Chicago. WESTENDORF, W. 1968 Das Alte Ägypten. Baden-Baden: Holle Verlag. 247 WHITEHOUSE, H. 2002 A Decorated Knife Handle from the ‘Main Deposit’ at Hierakonpolis. MDAIK 58: 425-446. WIESE, A.B. 1996 Die Anfänge der Ägyptischen Stempelsiegel-Amulette. OBO 12. WILD, H. 1966 Le Tombeau de Ti. La Chapelle. MIFAO LXV:2. WILKINSON, A. 1971 Ancient Egyptian Jewellery. London: Methuen & Co. WILKINSON, J.G. 1878 The Manners and Customs of the Ancient Egyptians. Volume II. London: John Murray. WILKINSON, R.H. 1992 Reading Egyptian Art. A Hieroglyphic Guide to Ancient Egyptian Painting and Sculpture. London: Thames and Hudson. WILKINSON, T.A.H. 1999 Early Dynastic Egypt. London and New York: Routledge. WINLOCK, H.E. 1924 The Museum’s Expedition at Thebes, The Egyptian Expedition 1923- 1924 in BMMA Part II, December 1924: 5-33 New York: The Metropolitan Museum of Art. WRESZINSKI, W. 1923 Atlas zur altaegyptischen Kulturgeschichte, Volume 1. Leipzig: J.C. Hinrichs’sche Buchhandlung. 248 General Index Armant stela 63 Arrow 47, 49, 52, 53, 60, 61, 63, 64, 70, 71, 82, 84, 86, 87, 89, 90, 91, 92, 93, 94 Ba 163, 164 Birth 56, 57, 58, 59, 61, 62, 77, 86, 89, 93, 94 Boat and barks 6, 13, 33, 35, 50 73,141 Book of the Dead 12 Botanical garden 9 Bowl 148-152 Branch 47, 50, 69, 142, 149, 150, 151, 158 Bull of the Sky 132 Bush 47, 50, 51, n. 37, 56, 58, 61, 69, 81, 87, 91, 92, 99, 145, 150 Canopic jars 31 Cartouche 64, 69, 127, 154, 156 Ceremonial beard 53 Ceremonial 160 procession Chantress 134, 135 Chaos 26, 50, 51, 67, 89, 93, 94, 97, 99 Chariot 53, n. 40, 64, 65, 70, 71, 94 ‘Chimera’ 85 Clap-net 45 Clappers 131 Collar 48, 53, 57, 60, 68 Comb 37, 38, 130 Commemorative 63 scarab Concubine 136, 140 Coronation 165 Cosmetic oil 124 ‘Cosmetic spoon’ 153-157 Crown 21, 53, 136, 141 C-ware 34, 35 Dancers 34, 133, 134, n. 102 Daughter 132, 137, 138, 140, 144, 183, 184, 186 Desert See mountain Diadem 23, n. 15, 135- 140, 160, 186 Djed pillar 163, 164 Domestication 16, 19, 30, 161 Duat See D-ware 34, 35, 185 Enclosure 53, 55, n. 42, 87, 89, 90 Enemy 13, 42, 44, 51, 61, 65, 70, 99 Estates 101, 104-108, 115 Eye of Horus 163, 180, 182 Eye paint 124 False door 101, 102 Fattened (of 103 animals) Fence 55, 78, 87, 90, 93, 94 Fillet 138, 139, 140 Force feeding 103 Furniture 110 Goldwasser, A. 4, 6, 7, 23, 158 Goose Lakes 132 Grape 106 Hair pin 37, 38 Harpoon 42 Harp player 133 Harvest 56, 59, 80, 84 Heb-Sed 55, n. 42, 133, 134, 135, 165 249 Honey 56 Incense 124 Inundation 56 Iwn-mwtef 134 Juniper berry 168, 169 Ka 53, 61, 62, 63, 87, 101, 106, 132, 149 Khemmis 136, 190 Kingship 44, 93, 181 Nedit Lake of Jackal 131 Lake of 131 Netherworld (Duat) Lasso 47, 53, 60, 75, 76, 77, 81, 87, 92 Lector-priest 112 Lévi-Strauss 6, 7 Lick 40, 42, 59 Lily 151 Lotus 138, 143, 149, 150, 151, 154, 156 Maadi culture 91 Maat 21 Mace head 61 Marsh bowl 148, 149 Meal (funerary) 101 Menat 133, 138, 139, 140 Military activity 63, 65, 70 Milk 148, 149, 152, 153, 171, 182, 184, 186 Modium crown 136, 138, 139, 140 Mother 26, n. 19, 27, 28, 50, 59, 67, 76, 87, 99, 107, 115, 116, 151, 152, 160, 179, 180, 186 Mourners 34 Narmer macehead 14, 55, n. 42 Narmer palette 38 Nedit 166 Net 45, 59, 77, 94 New Year’s gift 152 Oars 35 Offering list 101, 124-126 Offering table 101, 106, 111, 124, 126-127, 146, 175, 176, 179 Opening of the 15 Mouth Pair 55, 58, 60, 61, 75, 76, 80, 81 Palette 18, 38, 61, 92, 130 Palm 147 Palmette 27, 58, 66, 68, 69, 142, 144- 148, 151, 162 Papyrus crown 136, 137 Pet 30, 31, 161, 185 Pictorial semiotics 4 Platform crown 134, 137 Pomegranate 106 Pond 148, 149, 150, 154, 156 Protome 23, n. 15, 134, 135, 136, 137, 138, 139, 140, 141, 143, 144, 162, 186 Prototype 52, 72, 90, 91 Pylon 69 Regeneration 62, 71, 97 Ritual 64, 101, 103, 124, 129, 154, 165 Rock drawing 18 Rosette 137 -sceptre 74 Side lock 140, 141, 142, 144, 155 Sistrum 131, 134, 135, 138, 139, 140 Slaughter 15, 30, 37, 51, 55, 103, 108, 133 Sokar festival 13 Solar daughter 159 Solar Eye 6, 136, 170, 180, 181, 183, 184, 186 250 Sphinx, female 66, 68 Unguent jar 68, 69 Stag protome 137 Unification 33 Staff 74, 75 Uraeus 136, 141, 144, Towns palette 18 159, 160, 168, Tree 50, 56, 144, 169, 180, 184, 145, 163, 164, 186 175 Ushebti 31 Two Ladies 136, 162 Vision 29, 98 Udjat 142, 143, 144, Votive mummy 178 -sceptre 130 190 -sceptre 130 Unguent 156, 163 Wine 127, 148 Mammals, birds, fish, reptitles, insects and mythological animals Addax (Addax 15, 16, 49, 53, nasomaculatus) 56, 57, 78, n. 59, 81, 109, 111, 162 Antelope 22, 61, 65, 73, 141, 144, 157, Ass, wild (Equus 158, 179 17, 18, 19, 52, asinus africanus) 65, 69, 80, 89, Aurochs (Bos 93, n. 73 15, 48, 53, 55, primigenus) 57, 63, 67, 69, 70, 77, 85, 86, 87, 90 Baboon 31 Baboon, mummy 31, n. 24, 178 Barbary goat 17, 53, 60, 91 (Ammotragus lervia) Bird 38, 45, 103, 104, 105, 107, 117, 119, 120, Bovini 156 22 -bull 134 Calf 1, 66, 103, 104, 105, 106, 114, 115, 117, 119, 122, 126, 127, Canidae 128 19, 49 Canine 36, n. 28, 42, 130 Caracal 49, 84 Cat 31, 91 Cattle (Bos Taurus) 15, 30, 125, 128 Cobra 136 Cow 1, 6, 26, 103, 106, 116, 128, 148, 149, 160 Crane 114 Crocodile 37, 141, 142, Dipodidae 143 49 Dog 28, 38, 47, 48 Donkey (Equus passim 17, 26 asinus asinus) Duck 153, 155 Elephant 63, 160, 161 Equidae 17 Falcon 1, 142, 143, 144 Fallow deer (Dama 16, n.8, 26, 39, mesopotamica) 49, 53, 73, 93, n. 73, 94, n. 75, Fennec (Fennecus 122 19 zerda) Fish 38, 52, 57, 73, 148, 149, 154, Fox, red (Vulpes 156 19, 39, 49, 60, vulpes) 73, 74, n. 57, 75, 76, 77, 80, 251 Fox, red (cont.) 85, 86, n. 69, 91 gazella (species) Gazella dama 9 Gazella dorcas 9, 60 Gazella leptoceros 9 Gazella rufifrons 9 Gazella 9 subguttorosa Soemmerring’s 9, 10, 11, 53, gazelle (Nanger 55, 56, 58, 59, soemmerringii) 60, 80, n. 64 and n. 65, 91, 92, 98, 122 gazelle, fawn 25, 67 gazelle, foaling Appendix III gazelle in basket Appendix III gazelle, mating Appendix III gazelle, mummy 31, 161, 178, 179 Gazelle, nursing 25, 26, 59, 61, 62, 66, 67, 68, 70, 71, 74, 76, 77, 78, 94, 99, 115, 116, Appendix III Genet 51, n. 37, 85, 86, n. 69, Giraffe 40 Goat (Capra hircus) 17, 26, 30, 122, 145 Goose 43, 114, 153. 155 Griffin 39, 40, 66, 68 Hare 19, 20, 27, 28, (Lepus capensis) 49, 50, 51, n. 37, 57, n. 45, 59, 64, 69, 73, 75, 76, 78, n. 59, 79, 85, 89, 91, 110, 120, 157 Hartebeest 14, 39, 40, 49, (Alcelaphus 53, 55, 59, 60, buselaphus) 64, 65, 69, 77, 78, n. 59, 81, 85, 86, 94 Hedgehog 20, 27, 28, 49, (Paraechinus 50, 55, 75, 76, aethiopicus) 77, 78, n. 59, Hedgehog (cont.) 79, 85, 86, 91, 99, 120, 157 Herd 24, 30, 36, 114 Hippopotamus 42, 43, 185 Hippotraginae 12, 15, 16 Hyena (hyena 5, 18, 42, 52, hyena) 53, 60, 64, 87, Ibex (Capra ibex 91, 94, 110, 125 11, 21, 22, 40, nubiana) 48, 49, 50, 53, 60, 64, 68, 69, 70, 73, 74, 75, 76, 77, 79, 81, 86, 89, 94, 110, 111, 115, 116, 122, 125, 126, 141, 145, 152, 154, 157 Ibis, mummy 178 Ichneumon 77, 80 Jackal 19, 86, 91, n. jerboa (Jaculus 71, 130, 131 27, 49, 50, 55, Jaculus) 59, 77, 85, 99 Jungle cat 49, 76 Leopard 28, 40, 76, n.58, 77, 84, 85, 89 Lion 28, 33, 39, 48, 57, 63, 64, 65, 66, 68, 69, 76, 77, 81, 82, 85, 86, 89, 141, 142, 157 Lion cub 48, n. 33 Lynx 84, 86 Monkey 31, 89 Oryx (Oryx 12, 13, 22, 40, dammah, oryx 48, 49, 52, 53, beisa) 55, 56, 57, 59, 60, 61, 62, 64, 69, 70, 77, 79, 81, 85, 89, 91, 94, 105, 109, 110, 111, 112- 113, 114, 115, 122, 125, 126, 141, 142, 152, 154, 157 Mullet 56 252 Ostrich (Struthio 20, 40, 56, 80, Roan antelope 17 camelus) 94, 110 (Hippotragus Ox 103, 120, 127 equinus) Paraechinus 20, n. 10 Sand or desert fox aethiopicus (Vulpes rueppelli) Paraechinus deserti 20, n. 10 19, n. 9 Paraechinus 20, n. 10 Scorpion 141, 142, 184, dorsalis 185 Otter 55, n. 41 Serpent 143, 168, 169 Panther 57 Serpopard 39, 40, 42 Persian gazelle 9 Serval 49, 84, 85 Porcupine 76 Snake 141, 142, 157 Ratel (Honey 55, n. 41, 57, n. Sheep (Ovis aries) 17, 30 badger, Mellivora 45, 74 Turtle 38 capensis) Vulture 136, 183, 186 Ram 38, 166 Weasel 55, n. 41 Gods and goddesses Anubis 168 Anukis 162, 173, 175, 176 Bes 68, 141, 143, 154 Ennead 164 Geb 144, 163, 166 Hathor 1, 22, 134, 135, 136, 138, 148, 151, 162, 168, 169, 176, 179, 180, 182, 183, 184 Hededet 185 Horus 131, 140, 141, 142, 143, 163, 164, 165, 168, 169, 180, 181, 182, 184, 186 Horus-Shed 140, 143, 144 Isis 1, 141, 144, 163, 164, 167, 168, 169, 179, 181, 182, 184, 185, 186 Khepri 158 Khonsu 178 Khnum 166, 167, 175 Min 171, 172 Montu 143, 144 Nefertum 142 Nekhbet 136, 162, 183 Nephthys 162, 164, 167, 169, 170, 180, 186 Nun 148 Nut 132, 144, 167, 172 Osiris 144, 162, 163, 164, 165, 166, 167, 168, 169, 173, 179, 180, 181, 182, 186 Pre-Harakhti 181, 182 Re 166, 180, 183, 184 Reshep 140, 141 Sakhmet 168 Satis 175 Seth 130, n. 99, 163, 164, 165, 168, 169, 180, 181, 253 Seth (cont.) 182, 184, 186 Shed 140 Shu 166 Taweret 37, 136 Royal names Akhenaton 30 Amenemhat I 171 Amenhotep II 53, n. 40, 93 Amenhotep III 63, 133, 136, 138, n. 104, 139, 146 Amosis 53, n. 40 Den 42 Hatshepsut 93, 150 Huni 72 Isetemkheb D 31, 178 Kawit 149 Kemsit 106 Khaefere 51, n. 37 Khufu 51, n. 37, 102 Maatkare (21st dyn.) 31, n. 24 Mentuhotep II 71, 149 Mentuhotep IV 170, 171 Merenre 132, 163 Neferhotep 173 Nefertiti 30 Nefer-neferu-aten 30 Niuserre 130, n. 99 Osorkon II 134 Pepi I 163 Tefnut 180, 183 Thoth 164, 182, 183, n. 138 Wadjit 136, 162, 190 Pepi II 163 Pinudjem II 31 Psamtek I 96 Psamtek II 167 Ramses II 20, 70, 134, 136, 140, 142, 145, 157 Ramses V 181 Satamun, KV 46 139, 140 Sesostris I 165 Sesostris III 173 Seti I 124 Sneferu 72, 102, 104 Teye 139, n. 105 Tutankhamun 13, 15, 18, 48 n. 30, 53 n. 40, 64, 68, 69, 70, 71, 75, 75 n. 75, 93, 98, 100, 130, 137 Tuthmosis III 63, 93, 136, 138, n. 104, 173, 174 Tuthmosis IV 138, n. 104 Userkaf 130, n. 99 Private names Akhet-hetep-her 145 Amenipet (daughter) 138, n. 104 Akhethotep (D 64a) 14, 107 Anen (TT 120) 31 Amenemhat (BH 2) 55, 120 Ankhmahor 101, n. 79, 103, Amenemhat (TT 20, 55 108, 112-113, 53) 116, n. 92 Amenemhat (TT 82) 10, 14, 106 Ankhshepenwepet 31 Amenemhat-Nebwia 102, n. 80 Ankhtifi 49 Amenemheb (TT 63 Atet 72, 73 85) Baqt III (BH 15) 83, 99 Amenipet (TT 276) 93, n. 74, 94, 98 Dagi (TT 103) 89 254 Djar (TT 366) 89 Djaty 103 Djau 82, 87, n. 70 Djehutihotep II 16, 49, 55, 70 Fetekta 50, n. 35, 55, n. 42 Hay, ostracon of 176, 177 Hekaib 53, n. 40 Hemaka 45 Hesi 103 Hetepherakhti 58, 121, n. 94 Horemheb (TT 78) 138, n. 104 Ibi, (6 th dyn.) 17, 49, n. 34, 82, 86, 87, n. Ibi, (26 th dyn., TT 70, 97 31, 49, n. 34, 36) 83, 96 Idu (G 7102) 21 Idut (princess) 10, 55, n. 42, 58, n. 47, 103, 108, 121, and n. 95, Ineni (TT 81) 10, 114 Intef (TT 155) 16, 42 Intef (TT 386) 49, 89, 92 Intefiker (TT 60) 49, 52, 89, 90, 92 Inti 133 Ip 91, 92, 98, 145 Ipuy (TT 217) 145 Isetemkheb D 31 Iteti 102 Kadua 26, 115-116, 116, n. 92 Kagemni (LS 10) 18, 26, 107, 108, 115, 116, n. 92 Ka-hep 145 Kai-swdjau 125, n. 98 Kaninseut I, (G 119 2155 = Vienna ÄS 8006 Kapi 48, 116, n. 92 Kapunesut (G 4651) 126 Kemsit (TT 308) 106 Kenamun (TT 93) 18, 152 Kha (TT 8) 146 Kheruef (TT 192) 133, 135 Khety (BH 17) 10, 83, 86, 87, Khety (BH 17) cont. n. 70, 99, 114 Khety (TT 311) 89 Khnumhotep III 15, 20, 21, 26, (BH 3) 49, 51, n. 37, 52, 53, n. 40, 84, 85, 86, 99, 109-110 Maiherperi (KV 36) 149-152 Menna (TT 69) 10, 118, 137, 138, n. 104, 139, 140 Menkheperraseneb 31 (TT 112) Mentu-iwiw 69, 93, n. 74 (TT 172) Meru (N 3737) 102, N. 81 Mereruka 15, n. 7, 18, 20, 23, 27, n. 22, 48, 49, 78 Meru 10 Meryre II 30 Meryteti 48, 58, n. 47, 78, 79, n. 61, 99, 121, n. 95 Methen 74, 102 Montuherkepeshef 18, 19, 26, n. (TT 20) 20, 52, 65, n. 51, 93, n. 75, 99 Nebamun (TT 90) 20, 138, n. 104 Nebemakhet 20, 116, n. 92, 121, n. 95 Neb-kau-her 101, n. 79 Neferhotep (TT 94, n. 75, 174, 216) 175 Nefermaat 19, 48, 72, 73, 74, n. 57, 77, 102 Nefer-seshem-ptah 10, 103, 108 Nehwet-Desher 120 Neskhons 166 Nesutnefer (G 4970) 118 Nesu-su-djehuty 96 Niankhkhnum and 10, 27, n. 22, Khnumhotep 48, 50, n. 35, 58, n. 47, 78, 99, 116, n. 93, 121, n. 95, Nimaatre (G 2097) 10, n. 3, 25, n. (‘Isesimernetjer’) 17, 55, n. 42, 255 79, 80, 98, 99 Pabasa (TT 279) 31 Pairy (TT 139) 138, 140 Pehenuka D 70 (LS 20, 21, 50, n. 15) 35, 76, 77, 78, 92, 116, n. 93, 145 Pepy-nakht Hekaib 53, n. 40; 82, n. 67 Perpaouty 146-147 Petosiris 23, 102, 122, 123 Ptahhotep II 15, n. 7, 19, 27, (D 64b) 48, 58, n. 47, 59, 65, n. 51, 77, 78, 92, 116, n. 93, 121, n. 94 and 95 Ptahshepshes 9 Puimre (TT 39) 16, n. 8, 26, 28, n. 23, 49, 93, n. 73, 94, n. 75, 98 Raemka (no. 80) 11, n. 4, 48, 50, (D3, S 903) n.35, 75, 98, 99 Rahotep 19, 72, 73 Ramose 142 Rawer II (G 5470) 26, 115, 116, n. 92 Rekhmire (TT 100) 11, n. 4, 49, 51, n. 37, 93, n. 74, 112 Sekhemankhptah 14 Sekhemka, (G 1029) 111 Sabu 103 Sabi Ibebi 23 Segerttaui 138, n. 104 Sema-ankh 103 Geographical locations Abu Ghurob 56, 121, n. 95 Sun temple, 10, n. 3, 25, 55, Niuserre n. 42, 56, 58, 59, 61, 65, 67, 77, 78, 79, 80, n. 64 and 66, Senbi (B 1) 11, n. 4, 14, 15, n. 7, 18, 26, n. 20, 53, n. 40, 65, n. 51, 87, 89, 92, 98, 111, n. 88 Senedjem (TT 1) 145, n. 108 Seshat-hotep (G 18, 117, 125 5150) Seshemnefer III (G 117-118 5170) Seshemnefer IV 15, n. 7, 25, n. (LG 53) 17, 48, 50, n. 35, 79, 80, 99, 105, 113 Shetui 109 Teti 127 Thefu 48, 76 Ti 17, 42, 121,n. 94 Tjetu/Kaninesut (G 101, n. 79 2001) Tournaroi, stela of 165, 166 Ukhhotep (B 2) 18, 25, n. 17, 53, n. 40, 87, 89, 98, 99, 111, n. 88, 121, 122, 126 Ukhhotep (C 1) 111, 118 User (TT 21) 19, 110 Userhat (TT 56) 53, n. 40, 69, 93, n. 74 Wernu 21 Zet 131 92, 98, 99, 121, n. 95, 145 Abusir 52 Mortuary temple, 10, n. 3, 14, 18, Sahure 51, 52, 55, 57, n. 45, 58, 59, 256 Sahure 60, 61, 62, 63, cont. 64, 67, 70, 71, 74, 80, n. 64 and n. 66, 87, 90, 92, 94, 97, 98, 99 Abydos 53, n. 40, 70, 124, 130 Amarna 30, 81, 153 Armant 161 Assiut 81 Ballas 161 Beit el-Wali 20 Beni Hassan 83, 84-86, 87, 91, n. 72, 99, 109, 114, 120 El- Bersheh 84, 110, 164 Biggeh 166 Bubastis 51, n. 37, 134, 135 Buhen 173, 174 Coptos 184, 185 Cyprus 145 Dashur 104 Deir el-Bahari 62, 106, 148, n. 111, 149 Bab el-Gasus 31, 166 (TT 320) Temple, 62, 63, 84, 99 Mentuhotep II Deir el-Gebrawi 81-83, 86, 87, n. 70 Deir el-Medina 142, 175 Delta 148 Dendera 166, 179, 183 Deshasheh 133 Dra’ Abû el-Naga’ 93, 179 Edfu 183 Elephantine 166, 172, 175 Eastern desert 24 Esna 166, 183 Gurob 149, 150, 151, 152 El-Hagandia 9, n. 2 Hawawish 84 Heliopolis 183 Hermopolis 179 Hierakonpolis 14, 21, n. 11, 38, 160 Tomb 100 44, 50, 52, 55, n. 42 Iraq 145 El-Kab 84, 134, 140, El-Kab (cont.) 183 Kafr al-Batrân 131 Karnak 143, 178 Khartoum 34 El-Khatara 161 Kom Abu Yasîn 167 Komir 162, 170, 178, 179, 180, 185 Kom Ombo 179, 183 Kush 183 KV 62 64-68 Malqata 153 Lisht 51, n. 37, 91, 102 Luxor 13, 34 El-Mahasna 161, n. 123 Mastaba S 3035 45 Matmar 161 Medinet Habu 13, 18, 65, 69, 70 Meidum 72, 102, 105, n. 85 Meir 84, 87, 90, 110, 118, 122, 126 El-Mo’alla 84 Mostagedda 161 Naqada 33, 34, 35, 38, 44, 161 Philae 167, 183 Qubbet el-Hawa 82, n. 67, 84 Qurnet Mura’i 94 Red Sea 24 El-Saff 84, 91, 92 El-Salhiya 137 Saqqara Mortuary temple, 13, 60, 62, 67 Pepi II Pyramid complex, 25, n. 17, 55, n. Unas 55, 59, 60, 62, 67, 77, 80, n. 64 and 65, 92, 98, 99, 116, n. 93 Sehel 175 257 Serabit el-Khadim 148, 151, 152 Tuna (Hermopolis 122 Sheikh Abd el- 106, 110, 112, Magna) Gurna 114, 118 Wadi Hammamat 170 Soleb 134, n. 102, 135 Wadi Qirud 136, 140 Thebes 84, 89, 90, 110, 14 th UE nome 87 148, 179 16 th UE nome 22, 84 Timna 148 17 th and 18 th UE 168 nomes Museum objects cited Berlin, Egyptian Museum Berlin 1128 105 Berlin 1132 76 Berlin 20036 56 Berlin 21783 52 Bologna, Museo Civico Archeologico KS 1970 58, 147 Brussels, Musée Royaux d’Art et d’Histoire E.2631 23 E.4989 62 E.5300 165, 166 Cairo, The Egyptian Museum CG 1419 23 CG 1435 162, n. 126 CG 1530 103 CG 1552 Appendix III Cairo 14238 18 Cairo 14265/64737 36 Cairo 14716 38 CG 24058/ JE33825 149 GG 28027 164 CG 28092 164 CG 43809 73 CG 41002 167, n. 130 CG 41006 167, n. 130 CG 41007 167, n. 130 CG 41044 167, n. 130 CG 44911/JE33211 145 CG 51113 139 CG 51188 145 CG 52672 3 CG 53262 25, 99, 145 CG 61088a 31, n. 24 CG 68005 145 CG 69246/JE 38972 130, 131 JE 26227 31, 178 JE 27271 145, n. 108 JE 31566 167 JE 43660 175 JE 44744 156 JE 47397 149 JE 61467 18, 64, 65, 69, 70, 71, 75, 93, 100, 130 JE 61481 48, n. 33 JE 61502 64, 70, 71, 130 JE 62119 15, 64, 68- 69, 71, 130 JE 62120 6 JE 62626 64, 66-68, 71, 94, n. 75, 98, 130, 137 JE 70104 45, 130 JE 70165 45 JE 72024 142, 145 T17.6.24.11 (?) 96, n. 76 T19.11.24.3G 73 Cambridge, Fitzwilliam Museum E.207.1900 102, n. 81 258 Chicago, Field Museum of Natural History no. 30177 58, 145 Copenhagen, Ny Carlsbergs Glyptotek ÆIN 1133 72 Durham, Oriental Museum N. 1460 58, 146 Leiden, National Museum of Antiquities 904/3.1 58 London, British Museum BM 5953 154 BM 5958 156 BM 20757 154 BM 20790, 20792 39,40, 98, n. 77 BM 32074 38, 43 BM 37980 120 London, Petrie Museum UC 15459 38 UC 16295 36, 37, 43 UC 30054 149, 151 Moscow, Puskhin Museum Pushkin I.1.a4467 142 Pushkin I.1.a4491 143 Munich, State Museum of Egyptian Art ÄS 5633 149 New York, American Friends of Israel Museum AFIM 1990.35 156 New York , Brooklyn Museum 37.608E 156 09.889.118 36 New York, Metropolitan Museum of Art L13-14: 315 51, n. 38 MMA 1950.50.85 141, 185 MMA 1908.201.1 75 MMA 26.2.47 154 MMA 26.7.1281 36 MMA 26.7.1292 156 MMA 26.8.99 10, 136 MMA 68.136.1 16, n. 8, 23, n. 15, 137 MMA 68.139.1 3 Oxford, Ashmolean Museum E 1890.1137 149, 150 E 1895.935 38 E 1895.943 38 E 1910.635 72 E 1912.57 149, 151 E 1923.622 13 E 3631 14 E 3924 38, 40 Oxford, Pitt River’s Museum Knife handle, No? 36 Paris, Louvre E 3217 13 E 11043 154 E 11123 154 E 11124 12 E 11254 39, 40, 98, n. 77 E 11517 36 E 12659 11, 152 N 1725A 155 N 1725C 155 Philadelphia, Pennsylvania University Museum E.16141 73 259 Stockholm, Medelhavsmuseet EM 6000 37, n. 29, 42, 43 MM 14011 176 Toledo, Museum of Art 53.152 13 Texts cited Aelian XI, 23 184-185 Book of the Dead Chapter 17 166, 182 Chapter 112 12, 166 Chapter 181 165 Coffin Texts VII, 37q-38a 164, 167, n. 130 Esna no. 312, 7 173, 178 no. 516, 6 178 Papyrus Chester Beatty I (Love poem) 2,1-2,5 29 (Contendings of 181-182 Horus and Seth) 10,1- 11 Papyrus Leiden I 384 (Myth of the Solar Eye 21, 3 183 21, 7-10 183 21, 22 183 Papyrus dém. Louvre N 2430c Funerary text 179 Turin, Museo Egizio Cat.1601/ CGT 50066 142 Vienna, Kunsthistorisches Museum ÄS 8006 119 Papyrus Jumilhac, Louvre E. 17110 III, 7-8 168 III, 10-12 168 IX, 1-2 169 IX, 6 169 XIII, 10-15 169 XXIII, 12 169 Pap. Ramesseum B Cols 136-139 165 Philadelphia Archives XXIV 179 Philae, temple of Hathor Second southern 183 column Pyramid texts § 372b-c 131 § 469a 21 § 806c 12 § 972a-c 12, 163, 164 § 1032c-1033b 163, 164 § 1801a-c 167, n. 130 § 1082b 132 § 1083a-b 132 § 1164b 132 § 1432b 132 § 1485a-1491b 163, 164 § 1530a 132 260 (Pyramid Texts, cont.) § 1799a-b 12, 163 § 1801a-c § 2170a 132 Urkunden IV 893: 14-15 63 1245: 14-15 63 1738-1740 63-64 Egyptian words cited 132 56 15 78, 190 17 11, 12 182 182 15 17 132 19 17 142 171, 172 # 162, 170 162, 170, 178, 184, 185 12, 21, 22, 53, 103, 112, 114, 115 20, 21 75 15, 16, 109 115, 116 175 176 11, 12, 86 15 103 passim, 128 153, 158 16, 17 17 Wadi Hammamat M 110 26, n. 19, 170, 172 M 113 170, 171 M 191 171, 172 M 192a 170, 171 M 192b 171, 172 101, 112 140 20 20 176 173, 178 21 127 18, 125 139, 142, 163, 164, 170, 171, 176, 181 157 15, 103, 112, 119 136, 137, 138, 140 72 72 139 19 132 132 15 132 19 132 56 14 # 172 15 9, 21, 22, 57, 75, 83, 86, 103, 261 (cont.) 108, 109, 111, 75, 168 113, 114, 115, ! " 131 116, 125, 126, ! " 131, 166 127, 176, 178 168, 170, 171, 9, 23, 57, 83, 181, 182, 183, 86, 171, 173, n. 139 182, 183 10, 55, n. 42, 91 22, 183 262
https://www.scribd.com/document/56724102/The-Gazelle-in-ancient-Egyptian-art
CC-MAIN-2017-47
refinedweb
98,346
73.37
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). On 19/03/2017 at 20:11, xxxxxxxx wrote: Hi,all. In Xpresso,there is a node called "smple node",is ti possible to create it with python tag?for example,how to use the falloff of a plain effector to control a lot of cubes' filter(as the screenshot below). I have achieved it via Xpresso setup,but I want to do it via python tag,How to do achieve this?somebody has an example code? any help would be very appreciated! I want to achieve this goal via python tag ,is it possible? I tried this code below,but not work,maybe it is the cause that I don't know how to use the FalloffDataData. import c4d from c4d.modules.mograph import FalloffDataData def main() : null = op.GetObject() cubes = null.GetChildren() FalloffDataData = doc.SearchObject('plain') for cube in cubes() : mg = cube.GetMg() FalloffDataData.mat = mg if FalloffDataData.strength >= 0: cube[c4d.PRIM_CUBE_DOFILLET] = 1 else: cube[c4d.PRIM_CUBE_DOFILLET] = 0 Best Wishes! John. On 20/03/2017 at 05:59, xxxxxxxx wrote: Hi, can you perhaps describe the scenario in more detail? The cubes you want to filter are just cubes or are they created by a cloner (maybe even MoGraph Cloner)? Perhaps the Python Effector is much more, what you are looking for? On 20/03/2017 at 22:40, xxxxxxxx wrote: Hi,Andreas. I am sorry!I have re-edited my post . my question is that how I can achieve the effect in the screenshot via python tag or python effector .Thank you! Bset wishes! On 22/03/2017 at 10:09, xxxxxxxx wrote: I'm afraid I have no good news on this topic. There's currently no way to achieve this in Python. The point is, the effector only gets "executed", if it's part of a MoGraph generator (cloner,...). So the Python Effector code (or also the Plain Effector) won't get run at all in the scenario shown in your screenshot. The Sample node in Xpresso uses special internal messages to force execution of the Effector and to sample the falloff in order to get the desired result. These messages (and there data types) are not available in Python. Sorry. On 22/03/2017 at 22:41, xxxxxxxx wrote: Hi,Andreas. Thank you all the same! I'll keep it mind. I have another question that how to use the "FalloffDataData" function,for example, FalloffDataData.mat function, or this class function is only used in plugingdata? I am confused about this class,would you help me understanding this function?thank you ! On 24/03/2017 at 09:35, xxxxxxxx wrote: The C++ docs contain a bit more info on FalloffDataData. It's needed, when writing custom FalloffData plugins. On 27/03/2017 at 09:45, xxxxxxxx wrote: Ooopsy, sorry, I need to correct myself a bit or at least add some information. While it's not possible to sample the falloff of an effector in Python in the above described scenario, in C++ there's at least the C4D_Falloff class. This can be used to add falloffs to for example a deformer or generator. With this you can set up your own falloff and sample it to your liking. Of course neither in Python (yet) nor exactly what was asked for. But on the other hand, it's at least an option to sample a falloff. On 28/06/2017 at 13:28, xxxxxxxx wrote: Just wanted to put in a request to be able to Sample an arbitrary falloff. Specifically, I'm looking to sample the falloff data of an effector linked via userdata. On 29/06/2017 at 09:57, xxxxxxxx wrote: Hi Donovan, though I can't make any promises, chances aren't that bad, that this will be possible in one of the future releases.
https://plugincafe.maxon.net/topic/10026/13493_sample-node-with-python
CC-MAIN-2022-05
refinedweb
679
76.11
I am writing an app that has multiple classes that function as Users (for example, a School Account and a Staff account). I'm trying to use Flask-Login to make this easy but I'm not quite sure how to make it, so that when a user logs in I can have my app check to see whether or not the username belongs to a School account or Staff account, and then log in appropriately. I know how to figure out which type of account it belongs to (since all usernames must be unique). But after that I'm not sure how to tell the app that I want it to login that specific user. Right now, I only have one universal login page. Is it easier if I make separate login pages for Staff accounts and School accounts? I'm using a MySQL database through Flask-SQLAlchemy. You can define each User with a specific role. For example, user 'x' can be SCHOOL while user 'y' can be 'STAFF'. class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(80),unique=True) pwd_hash = db.Column(db.String(200)) email = db.Column(db.String(256),unique=True) is_active = db.Column(db.Boolean,default=False) urole = db.Column(db.String(80)) def __init__(self,username,pwd_hash,email,is_active,urole): self.username = username self.pwd_hash = pwd_hash self.email = email self.is_active = is_active self.urole = urole def get_id(self): return self.id def is_active(self): return self.is_active def activate_user(self): self.is_active = True def get_username(self): return self.username def get_urole(self): return self.urole Flask-login however does not have the concept of user roles yet and I wrote my own version of login_required decorator to override that. So you might want to use something like: def login_required(role="ANY"): def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): if not current_user.is_authenticated(): return current_app.login_manager.unauthorized() urole = current_app.login_manager.reload_user().get_urole() if ( (urole != role) and (role != "ANY")): return current_app.login_manager.unauthorized() return fn(*args, **kwargs) return decorated_view return wrapper Then, you can use this decorator on a view function like: @app.route('/school/') @login_required(role="SCHOOL") def restricted_view_for_school(): pass @codegeek i found this very useful, thanks. I had to modify the code a bit to get it working for me, so i figured i'd drop it here in case it can help anyone else: from functools import wraps login_manager = LoginManager() ... def login_required(role="ANY"): def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): if not current_user.is_authenticated(): return login_manager.unauthorized() if ((current_user.role != role) and (role != "ANY")): return login_manager.unauthorized() return fn(*args, **kwargs) return decorated_view return wrapper
https://pythonpedia.com/en/knowledge-base/15871391/implementing-flask-login-with-multiple-user-classes
CC-MAIN-2020-40
refinedweb
448
54.08
Introduction Every now and then, I demo my Spotifinder Ext JS app. It’s a really cool app that connects to LastFm and Spotify. I created it, to demo Ext JS concepts in my training classes. It also shows off the great theming capabilities in Ext JS. This year, I presented advanced theming at SenchaCon and I received lots of questions about how I created the Spotifinder app theme. So I decided to write a tutorial on how to create a really cool, good looking dark theme. You can use this tutorial to help you build your theme for the Sencha Application Theming Contest. The first prize winner gets $2,500! The tutorial files I used for this tutorial can be found here. It’s basically just a simple Ext JS app (view) with many components, like a grid, and some other components. You can use any other Ext JS (4, 5 or 6) application as well, but I used this as a reference point, and I used Ext JS 6. What’s great about theming an “all-component” -app, is that you see on the fly how your new theme looks like, without clicking through a real-life app. Another prerequisite: Sencha Cmd needs to run on your command line. Test with this command: sencha which. It should output a version number – for Ext JS 6, the Cmd version should be 6.x. Ext JS themes use Sass, which stands for syntactically awesome stylesheets, and yes, it’s indeed awesome. Its a more dynamic way to write CSS code. For example, you can use variables and calculations in your stylesheets. A browser doesn’t understand Sass, only CSS. Therefore, these Sass themes need to be compiled to production-ready CSS code, so your browser can understand it. The compilation process of themes in Ext JS apps runs via Sencha Cmd. Ext JS ships with a couple of out-of-the-box themes. You can directly switch to one of these themes and use it, or you can extend one of them and modify it. That’s how you create custom themes. The best theme to modify is Neptune or the new Triton. It provides lots of variables you can use to change the look and feel, and because it’s color background and white text on the front, it’s the ideal theme to use to create good looking dark themes. Alright, enough theory, let’s try it out. We’ll start by generating a new theme. We’ll just generate a theme package, so you can reuse it in other projects. Open Sencha Cmd and run the following command: sencha generate theme theme-spotifext This will generate a theme package, in my workspace packages/local folder. It will contain a sass/var folder, which will contain a Sass stylesheet with variables. It will be first in the compile order), and it will also contain a sass/src folder, which is the folder that contains Sass stylesheets with mixins and CSS rules. These files will be compiled last, so the pre-defined variables are used. The theme package also contains a resources folder – it can be handy to save assets such as images or fonts in this folder. The package will also contain a package.json file. It has meta info for your theme package. For example, it sets the type of the package to a “theme”. Also, you can write your contact information and description. There is one thing here that you’ll need to change. To create a theme variant of the new Triton theme, change the extend line to: "extend": "theme-triton", Note that themes in Ext JS 6 don’t have the "ext-" prefix anymore. Now, to see your variant of the Triton theme in the theming demo app, you need to wire it up the correct way. Switching Themes I mentioned “the correct way” on purpose because in traditional web design you would change stylesheets by opening the index.html page and swapping the ‹style› tags. It doesn’t work like this in Ext JS applications – you swap your themes via the app.json file. What’s happening here is that the Ext JS microloader loads the correct stylesheet for you, via the bootstrap.css file, which is included in your index.html. The bootstrap.css points to a CSS build version of your Sass theme. This way of serving themes has a huge advantage; all your paths to images and fonts will be all the same across any environment: development, test, or production. You can wire up your new Spotifext theme by opening app.json of the demo app and changing the "theme" line to: "theme": "theme-spotifext" The next step is to build your application with sencha app build or sencha app build development (which only builds the theme instead of the full app), and you’re good to go. In case you’re running a universal app and you want to use the Spotifext theme for the classic toolkit, you should wire up the theme to a build profile. For example: "builds": { "myclassicprofile": { "toolkit": "classic", "theme": "theme-spotifext" }, "mymodernprofile": { "toolkit": "modern", "theme": "theme-cupertino" } }, Variables The first thing you’ll need to do is create some files. You can create the following file structure, in your package folder (packages/local/theme-spotifext): sass/var/_config.scss sass/var/Component.scss sass/var/button/Button.scss sass/var/form/field/Base.scss sass/var/grid/Panel.scss sass/var/tab/Panel.scss Notice the naming of the files. Everything, except _config.scss, maps to the framework components. Component.scss – > Ext.Component, and grid/Panel.scss to Ext.grid.Panel.scss. This mapping is set up in the app.json file as a sass namespace. You don’t need to change that. An important feature of Sass is the ability to define variables. Do you remember when you used to use plain old CSS? You coded a full stylesheet and by the end of the week someone in your company wanted you to change one of the application colors. It was a huge problem because you had to find and replace all those color values, including all the color codes with lighter or darker contrasts. With Sass, this is not a big deal anymore. You just define a variable at the top of your file. Later in your CSS rules, you point to those pre-defined variables. Because a Sass stylesheet is compiled, it makes your stylesheet a lot more dynamic. Try this out. In the Component.scss file, you will include your own color configuration sheet (that’s the _config.scss file). Just write the following line at the top of var/Component.scss: @import ‘_config.scss’; Now in the _config.scss file, define a couple of vars which you can use though the full stylesheet. You can define these variables at the top of the file: //my own variables $dark-bg: #000; $dark-bg2: #121314; $dark-bg3: #222326; $dark-bg4: darken(#88898C, 15%); $front-color: #adafb2; $front-color2: #fff; $highlight-color: $base-color; $highlight-color2: lighten($highlight-color, 20%); $highlight-color3: darken($highlight-color, 20%); $font-family: 'Montserrat', helvetica , arial , verdana , sans-serif; $font-size: 12px; Note the $highlight-color2 and 3, these use built-in Sass functions to change the highlight-color to a 20% lighter or darker tone of the color. We understand that Sass variables are an extremely important feature of Sass, so Ext JS uses Sass variables as well. There are actually two types of variables: Global variables and Component variables. Global Variables The first variable you’ll set is the $base-color – it’s a global Ext JS Sass variable. When you change this variable, it will affect everything in the global scope. Many other colors will be calculated based on the $base-color. You can find all the Global variables in the API docs by searching for Global_CSS. Or, even better, you can use Sencha App Inspector – see below for more information. For your theme, you can use these global vars and put them in var/Component.scss: $base-color: #639000; $body-background-color: $dark-bg3; $color: $front-color; $enable-font-smoothing: true; Component Variables Inside Component.scss, I have set a bunch of component variables too. Take a look at my files in the packages/local/theme-spotifext/sass/var/ folder in Git. I moved some of these component variables to their own scss file, as I did for grid/Panel.scss. That’s just so I can maintain smaller files. By using variables, you’ll notice that I styled about 80% of my application, and I don’t have any problems with CSS overrides. You can find Component Sass variables in the API docs for the component you want to style. For example, search for grids and then click on the CSS vars button. There are a lot of variables to choose from. Before Ext JS 6, you had to use trial and error. But, with Ext JS 6 and App Inspector, it’s a piece of cake to figure out which variable you should use. Sencha Inspector Sencha Inspector is a new stand-alone tool. With this tool, you’re able to inspect your Ext JS code, including your MVVM patterns. You can inspect applications, running in any browser or device, even apps that are running in Sencha Web Application Manager. Not only are you able to inspect your JavaScript code, you can inspect all your Ext JS Sass variables. Together with Fashion, the new way of compiling Ext JS Styleheets, this is super powerful. For this tutorial, you can try out the awesome theming feature. Download Sencha Inspector Early Access version. When you search for an Ext JS 6 component in the theme panel, it will expose all the available Sass variables. This will save you from manually browsing through all the docs. With Fashion (read more below), you can enter values for all these variables, and you’ll see the result immediately on your screen. This is great for testing when you don’t know which Sass variable you need to use. Because you no longer need to wait for app builds or theme compilations, this really speeds up your theme development time. I work with my IDE and Inspector on one screen, and my application running in a browser on another monitor. As soon as I find the right Sass variable with Sencha Inspector, I copy it over to my theme package. Take a moment and browse through the sass/var code in my package on Github. Within a couple of hours, I finished 80% of my theme. To get this up and running, you’ll need to have Inspector installed along with Sencha Cmd. See the docs. Within Sencha Cmd, you’ll run the built-in webserver (it’s a Jetty web server). Open Sencha Cmd and run the following command: sencha app watch After sencha app watch starts the web server (by default it’s on port 1841), Sencha Cmd polls for changes. Next, open the following URL in your browser: Once the app is loaded and finishes compiling the theme for the first time, you’ll have to copy and paste the following bookmarklet in your browser console to create a connection between App Inspector and your app. javascript:!function(a,b){var a=a||3e3,b=b||"",c=b+":"+a+"/inspector.js",d=function(a,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,document.addEventListener("load",function(){"undefined"!=typeof Ext&&"undefined"!=typeof Ext.onReady&&Ext.onReady(function(){if(window.SenchaInspector){var a=document.head.getAttribute("data-senchainspectorport");SenchaInspector.init(b+":"+a)}})},!0),c?document.head.insertBefore(d,document.head.firstChild):document.body.appendChild(d)};document.head.setAttribute("data-senchainspectorport",a),d(c,!0)}(); If you’re interested in what’s going on under the hood, App Inspector uses WebSockets. The App inspector script is running on port 3000. That’s how the standalone app can inspect your application code. Now, we’ll look at compiling the themes. Fashion I mentioned the word Fashion above. And no, I am not talking about the latest style of clothing. This is a new way of compiling themes that is built into Sencha Cmd. To compile a theme in Ext JS, you use Sencha Cmd and run either: sencha app build [development] or sencha app watch [toolkit] The difference here is that watch is polling for changes, and compiles on the fly, while sencha app build only compiles manually. You can see why I am so happy about Fashion. With Fashion, you can compile your themes on top of JavaScript. It’s so fast that when I change a line of code on my left monitor, it’s already changed on the right monitor before I can turn my head. I don’t need to wait for the compilation (except when starting the server), and I don’t need to refresh my browser window. The magic all happens under the hood. Sencha Cmd is running PhantomJS in the background, which is basically a headless browser that you can run from the command line. It will run your application, compile the theme, and put it all into one big JavaScript function. Every change you make – whether it’s in your IDE/editor, in the classic or modern toolkit, or with Sencha Inspector – is handled by JavaScript which changes the styling in the DOM. There are many more advantages. For example you can extend on top of Fashion and create your own styling functions (like Sass functions), and you can debug your stylesheet code. You can see these the big advantages on your development machine while you’re designing your theme. To get this up and running, you’ll need to run sencha app watch classic from your command line and run the following arguments in your URL: ?platformTags=fashion:true and then you are good to go: Coming Up There are a few more things I did in my spotifext theme to make it look awesome. I wrote some CSS rules to animate the button hovers, used custom fonts, and created my own button and tab panel variants to make it look unique. In part 2 of this article, I will explain mixins versus css overrides as well as fonts and icons. With this information, you should be able to create good looking themes. Sign up for the Sencha Application Theming Contest. The first prize winner gets $2,500! Resources: Sencha Theming Guide My SenchaCon Presentation Download Sencha App Inspector Early Access Tutorial demo files How to Create a Dark Ext JS Theme – Part 2 Excelente article, I’ll waiting for the next steps. I found the 2nd part of this tutorial here: for those who didn’t find it There is an error in the link: document.head.getAttribute(“data-senchainspectorport”) The first double-quote is not a regular quote and causes the console to throw “VM691:2 Uncaught SyntaxError: Unexpected token ILLEGAL(…)” @Kristian – thanks for catching that error. It’s been fixed. This tutorial demonstrates a couple bad practices that will lead to build headaches: 1. The misc color swatches should go in theme/sass/etc/all.scss, not this custom _config.scss that gets manually included all over 2. theme/sass/var/Component.scss is full of variables for other components like Panel that should be in separate scss files targeting those components. Hi Chris, Thank you for your comment, and spending time on this tutorial. Honestly, these aren’t “bad” practices, just some personal (and valid) techniques being discussed. 1. One of the things we added (forget what release) is a “var/all.scss” file (see) that is similar to the _config.scss. The use of @import may “hide” the file from app watch but having it in the var path would resolve that. Apart from that, since the Sass will be compiled, and we are only using it for setting variables, there won’t be anything double in the final stylesheet. 2. This is completely up to the developer, and the best practice depends per project (size). Everything in sass/var/Component.scss could be considered as “global”, since every view component in Sencha extends from Ext.Component. When you don’t have a large project / stylesheet, it’s completely fine to put a few variables/ styles for let’s say “border splitters” in Component.scss instead of creating a whole new scss file for the. It’s just what the developer personally prefers. You were mentioning “build headaches, because it’s manually included all over.” – I don’t really know what you mean by that. – In case you mean you have build errors. I’m curious to hear more. – This example, supposed to compile fine. Feel free to email me. Hope this explains it well. Cheers, Lee
https://www.sencha.com/blog/how-to-create-a-dark-ext-js-theme-part-1/
CC-MAIN-2019-39
refinedweb
2,818
64.81
Sage on Jupyter with ipywidgets, matplotlib Hi all, I've spent about two days now trying to get Sage to work nicely on Jupyter. Still, I have the following two problems: 1. ipywidgets (and I have found no docu on the web that would hint to this problem) does not show any output and fails on commands like interact(f,x=10) 2. backend support for matplotlib (I've tried all the "solutions" that come up on a google search, I have tk/tcl installed on my system, sage compiled from scratch with $SAGE_MATPLOTLIB_GUI="yes" but it does not find TKInter for tk support, not to mention that the sage pyqt4 package fails compiling) concerning 1. I ran the following code on jupyter with Sage 6.9 kernel from __future__ import print_function; from ipywidgets import interact; def f(x): return(x); interact(f,x=10); this gives (besides various traceback output) ValueError: 10 cannot be transformed to a Widget I have the following version: sage -installed | grep ipywidgets ipywidgets.............................. 4.0.2 concerning 2. I've tried to recompile sage -f matplotlib after export SAGE_MATPLOTLIB_GUI="yes" BUILDING MATPLOTLIB matplotlib: yes [1.4.3] python: yes [2.7.9 (default, Dec 3 2015, 20:58:38) [GCC 4.8.4]] platform: yes [linux2] ... OPTIONAL BACKEND EXTENSIONS macosx: no [Mac OS-X only] qt5agg: no [PyQt5 not found] qt4agg: no [PyQt4 not found] pyside: no [PySide not found] gtk3agg: no [Requires pygobject to be installed.] gtk3cairo: no [Requires cairocffi or pycairo to be installed.] gtkagg: no [Requires pygtk] tkagg: no [TKAgg requires Tkinter.] wxagg: no [requires wxPython] gtk: no [Requires pygtk] agg: yes [installing] cairo: no [cairocffi or pycairo not found] windowing: no [Microsoft Windows only] running on: > uname -a Linux host 3.16.0-53-generic #72~14.04.1-Ubuntu SMP Fri Nov 6 18:17:23 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux > locate libtk8.6.so /usr/lib/x86_64-linux-gnu/libtk8.6.so > locate libtcl8.6.so /usr/lib/x86_64-linux-gnu/libtcl8.6.so > locate Tkinter.py /usr/lib/python2.7/lib-tk/Tkinter.py /usr/lib/python2.7/lib-tk/Tkinter.pyc Furthermore, (on another machine for some magic reason I could not figure out, I have TKAgg as backend available), it seems I cannot use %matplotlib inline as with a python kernel. The only option seems to have the plots in a new window. Can anybody help? I'm frustrated to the point that I'm nearly planning on using the Python kernel and running the needed sage code via exec. But, quite honestly, that would be horrendous ;-) have you read question 11347 if you don't have time, do plt.savefig('test.pdf')(instead of plt.show()); it creates the file in the project's working directory.
https://ask.sagemath.org/question/31326/sage-on-jupyter-with-ipywidgets-matplotlib/
CC-MAIN-2018-39
refinedweb
464
64.3