text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringlengths 9
15
⌀ | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
---|---|---|---|---|---|
I can quite understand the dismay that an assert error can cause to the new programmer. Here's your program doing, mostly, what you want, and then bang! an assert.
So let's examine asserts and why they're there and what we can learn from them. I should stress that this article discusses how MFC handles asserts.
The verb "assert" has 4 senses in WordNet. 1. assert, asseverate, maintain -- (state categorically) 2. affirm, verify, assert, avow, aver, swan, swear -- (to declare or affirm solemnly and formally as true; "Before God I swear I am innocent") 3. assert, put forward -- (insist on having one's opinions and rights recognized; "Women should assert themselves more!") 4. insist, assert -- (assert to be true; "The letter asserts a free society")All of the above meanings apply in this instance but meaning 4 is the most literally accurate in the context of asserts. An assert states that the condition being asserted is true. If it isn't true the program is in serious trouble and you, the programmer, should be warned of this.
void CMyClass::MyFunc(LPCTSTR szStringPtr) { if (*szStringPtr == '7') DoSomething(); }The function reads the memory the pointer points to so it had better be pointing at valid memory. Otherwise you're going to crash! One of the many things that can go wrong when calling the function is if you were to pass it a
NULLpointer. Now if it happens that the pointer is in fact
NULLand your program crashes you don't have a lot of information to work with. Just a message box with a code address and the information that you tried to read memory at location 0x00000000. Relating the code address to the actual line in your code isn't a trivial task, especially if you're new to the game.
So let's rewrite the function a little.
void CMyClass::MyFunc(LPCTSTR szStringPtr) { ASSERT(szStringPtr); if (*szStringPtr == '7') DoSomething(); }What this does is test
szStringPtr. If it's
NULLit crashes right away. Hmmm... it crashes? Yes, that's right. But it crashes in a controlled way if you're running a debug build of your program. MFC has some built-in plumbing to take a controlled crash and connect it to a copy of the debugger. If you were running a debug build of this program and the assert failed you'll see a messagebox similar to this one.
This shows you which file and which line triggered the assertion. You can abort, which stops the program, or you can try to ignore the error, which sometimes works, or you
can retry, which invokes the debugger and takes you right to the line that failed. This works even if you're running the program stand-alone provided there's a debugger
installed on the computer.
ASSERT(...). If you're building a release version the
ASSERTitself and all the code inside the parentheses disappears. The assumption is that you've tested your debug builds and caught all likely errors. If you're unlucky and missed an error and release a buggy version of your program the hope is that it'll limp along even though it failed a test that an assert would have caught. Sometimes optimism is a good thing!
It might happen that you want, in a debug build, to assert that something is true and the something you're asserting is code that must be compiled into your program
whether it's a debug build or a release build. That's where the
VERIFY(...) macro comes to the rescue.
VERIFY in a debug build includes
the extra plumbing MFC provides to let you jump into the debugger in the event that the condition isn't satisfied. In a release build the extra plumbing is omitted
from your program but the code inside the
VERIFY(...) statement is still included in your executable. For example.
VERIFY(MoveFile(szOriginalFilename, szNewFileName));will cause a debug assert if, for whatever reason, the
MoveFile()function fails in debug builds. Regardless of what kind of build the
MoveFile()call will be included in your program. But in a release build the failure of the call is simply ignored. Contrast this with
ASSERT(MoveFile(szOriginalFilename, szNewFileName));In debug builds the
MoveFile()will be compiled and executed. In release builds the line completely disappears and no file move is attempted. This can lead to some puzzled head-scratching.
The first thing to remember is that it's not very likely to be caused by a bug in MFC. I don't deny the existence of bugs in MFC but in the dozen years I've been using MFC I've never had an ASSERT happen due to a bug in MFC.
The second thing to remember is that the ASSERT is there for a reason. You need to examine the line of code that triggered the assert, and understand what it was testing.
For example, quite a few classes in MFC are wrappers around Windows controls. In many cases the wrapper function simplifies your code by converting a
SendMessage call into something that looks like a function. For example, the
CTreeCtrl::SortChildren() function takes a handle to a
tree item and sorts the children of that handle within the control. In your code it might look like this.
m_myTreeCtrl.SortChildren(hMyNode);That's what you write. Internally the class really sends a message to the tree control. You get to call a nice easy function based interface and MFC takes care of moving the parameters around in the way the message requires. Here's the reformatted function from MFC source code.
_AFXCMN_INLINE BOOL CTreeCtrl::SortChildren(HTREEITEM hItem) { ASSERT(::IsWindow(m_hWnd)); return (BOOL)::SendMessage(m_hWnd, TVM_SORTCHILDREN, 0, (LPARAM)hItem); }The first thing it does is assert that the underlying window handle in your
CTreeCtrlobject is a valid window! Now I really don't know if bad things will happen to your system if you try and send the
TVM_SORTCHILDRENmessage to a non-existent window. What I do know is that I want to be told if I'm trying to do it! The assert here alerts me immediately if I'm doing something that has no chance of succeeding.
So if you were calling such a function and got an assert error you'd look at the failed line and see that it's asserting that the window handle is an existing window. That's the only thing it's asserting. If it fails the only thing that can be wrong is that the window with that handle doesn't exist. That's your clue to tracking down the bug. From there you would look at the function calling this one and try to determine why the window that you thought existed no longer exists.
So that's a very very brief overview of how MFC uses asserts and how you go about determing why MFC asserted in your project. Now let's look at how we can use assert in our own code.
NULL. We can actually do a good deal better than that. Both MFC and Windows itself provide us with a bunch of functions we can use to determine if a pointer is pointing at valid memory. To refresh your memory here's the original function again, and our first draft at improving it.
void CMyClass::MyFunc(LPCTSTR szStringPtr) { if (*szStringPtr == '7') DoSomething(); }and the first draft of improvements...
void CMyClass::MyFunc(LPCTSTR szStringPtr) { ASSERT(szStringPtr); if (*szStringPtr == '7') DoSomething(); }This will alert you to just one kind of error, passing a
NULLpointer. It'd be nice if we could also test that the pointer is pointing at valid memory instead of just being a non NULL garbage value. We can do it like this.
void CMyClass::MyFunc(LPCTSTR szStringPtr) { ASSERT(szStringPtr); ASSERT(AfxIsValidString(szStringPtr)); if (*szStringPtr == '7') DoSomething(); }This adds a check that
szStringPtris pointing at valid memory. The test checks that you have read access to the memory and that the memory includes the string terminator. A related function is
AfxIsValidAddressthat lets you check if you have access to a memory block of a particular size as specified in the call. You can also check if you have read access to the block, or if you have write access to it.
IsWindow()and memory validation checks it's possible to assert that an object passed to a function is of a particular type. If you're writing a program that deals with both
CEmployeeobjects and
CProductobjects it's not terribly likely that those objects will be interchangeable. So it makes sense to verify that functions which work on
CEmployeeobjects are passed only those types of objects. In MFC you do it like this.
void CMyClass::AnotherFunc(CEmployee *pObj) { ASSERT(pObj); // Our old friend, it can't be a NULL ASSERT_KINDOF(CEmployee, pObj); }As before, we first assert that the pointer isn't NULL. Then we assert that it's an object pointer of type
CEmployee. You can only do this with classes that are derived from
CObjectand you need to add some runtime support. Fortunately the runtime support is really trivial.
You must have declared the object as being at least dynamic. Let me explain. In MFC you can declare that a class contains runtime class information. You do this by
including the
DECLARE_DYNAMIC(ClassName) macro in the class declaration and including the
IMPLEMENT_DYNAMIC(ClassName, BaseClassName)
somewhere in the implementation.
The class definition.
class CMyReallyTrivialClass : public CObject { DECLARE_DYNAMIC(CMyReallyTrivialClass) public: // Various class members and functions... };and the implementation file
IMPLEMENT_DYNAMIC(CMyReallyTrivialClass, CObject); . . . // Other class functions...If all you want to do is use the
ASSERT_KINDOFmacro those two lines are all that's needed. Now, when you write your program, you use the
ASSERT_KINDOFmacro anywhere that an object pointer is passed to you and it will be tested to see if it does indeed point to an object of that kind. If it doesn't your program crashes in the controlled way mentioned before and up comes the debugger pointing at the failed assertion. From there... well we've already covered that ground.
If your object already contains the
DECLARE_DYNCREATE macro or the
DECLARE_SERIAL macro you don't need to use
DECLARE_DYNAMIC
because both those macros include the runtime class information required by
ASSERT_KINDOF.
In recent years I've been using (perhaps overusing) asserts as runtime checks in my code. It's become automatic to pepper my code with assertions that pointers are valid and point to the kind of object my code is expecting. I find it pays off. It's a rare occurence these days that I have to cope with a crash caused by a NULL pointer or a pointer to the wrong kind of object.
12 Mar, 2004 - Initial version
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/cpp/assertisyourfriend.aspx
|
crawl-002
|
refinedweb
| 1,800 | 63.29 |
Feature #14473closed
Add Range#subrange?
Added by greggzst (Grzegorz Jakubiak) over 3 years ago. Updated almost 3 years ago.
Description
Hi there,
I'd like to propose a method that returns true when a range that the method gets called on is a subrange of a range passed in as an argument.
Example:
(2..4).subrange?(1...4) => true (-2..2).subrange?(-1..3) => false
Files
Updated by duerst (Martin Dürst) over 3 years ago
- Backport deleted (
2.3: UNKNOWN, 2.4: UNKNOWN, 2.5: UNKNOWN)
- Tracker changed from Bug to Feature
Updated by greggzst (Grzegorz Jakubiak) over 3 years ago
- Subject changed from Range#subrange? to Add Range#subrange?
Updated by owst (Owen Stephens) over 3 years ago
+1 for this suggestion - we have a similar method in our code base, implemented approximately as follows:
Range.class_exec do def subset?(other) raise ArgumentError unless other.is_a?(Range) first >= other.first && last <= other.last end end
As a
Range represents a set of elements, should there also be
proper_subset?,
superset? and
proper_superset? methods (and perhaps their operator aliases) similar to those on
Set ()?
Updated by owst (Owen Stephens) over 3 years ago
So, something like (naive implementation in Ruby):
Range.class_exec do def subset?(other) raise ArgumentError unless other.is_a?(Range) first >= other.first && last <= other.last end def proper_subset?(other) raise ArgumentError unless other.is_a?(Range) self != other && subset?(other) end def superset?(other) raise ArgumentError unless other.is_a?(Range) first <= other.first && last >= other.last end def proper_superset?(other) raise ArgumentError unless other.is_a?(Range) self != other && superset?(other) end end require 'minitest/autorun' class TestRange < MiniTest::Test def test_subset assert_equal true, (1..10).subset?(1..10) assert_equal true, (2..9).subset?(1..10) assert_equal true, (1..9).subset?(1..10) assert_equal true, (2..10).subset?(1..10) assert_equal false, (0..11).subset?(1..10) assert_equal false, (0..10).subset?(1..10) assert_equal false, (1..11).subset?(1..10) assert_raises(ArgumentError) { (1..10).subset?('not a range') } end def test_proper_subset assert_equal false, (1..10).proper_subset?(1..10) assert_equal true, (2..9).proper_subset?(1..10) assert_equal true, (1..9).proper_subset?(1..10) assert_equal true, (2..10).proper_subset?(1..10) assert_equal false, (0..11).proper_subset?(1..10) assert_equal false, (0..10).proper_subset?(1..10) assert_equal false, (1..11).proper_subset?(1..10) assert_raises(ArgumentError) { (1..10).proper_subset?('not a range') } end def test_superset assert_equal true, (1..10).superset?(1..10) assert_equal false, (2..9).superset?(1..10) assert_equal false, (1..9).superset?(1..10) assert_equal false, (2..10).superset?(1..10) assert_equal true, (0..11).superset?(1..10) assert_equal true, (0..10).superset?(1..10) assert_equal true, (1..11).superset?(1..10) assert_raises(ArgumentError) { (1..10).superset?('not a range') } end def test_proper_superset assert_equal false, (1..10).proper_superset?(1..10) assert_equal false, (2..9).proper_superset?(1..10) assert_equal false, (1..9).proper_superset?(1..10) assert_equal false, (2..10).proper_superset?(1..10) assert_equal true, (0..11).proper_superset?(1..10) assert_equal true, (0..10).proper_superset?(1..10) assert_equal true, (1..11).proper_superset?(1..10) assert_raises(ArgumentError) { (1..10).proper_superset?('not a range') } end end
For the record, I'd be interested in taking a stab at implementing this in MRI, if the proposal is accepted.
Updated by nobu (Nobuyoshi Nakada) over 3 years ago
It should consider
exclude_end? too.
Updated by owst (Owen Stephens) over 3 years ago
- File 0001-range.c-add-subset-superset-methods.patch 0001-range.c-add-subset-superset-methods.patch added
Thank you nobu, I came to the same realisation when writing the tests for my attempt at an implementation (patch attached).
Please let me know what you think, when you have time. This is my first "proper" MRI patch, so all comments gratefully received!
Updated by duerst (Martin Dürst) over 3 years ago
As long as we only consider ranges starting and ending with integers, concepts such as subset and superset make sense. But ranges can also be constructed from other numbers, and other objects in general.
What e.g. should be the result of
(5..10).subset?(5.5..7.9)?
Or what if we introduce something like
Range.new(1, 10, step: 2), which would produce
[1, 3, 5, 7, 9] when converted to an
Array?
Updated by owst (Owen Stephens) over 3 years ago
Good questions duerst. I wonder if I should have stuck with the
subrange naming rather than
subset, due to the Numeric behaviour.
What e.g. should be the result of (5..10).subset?(5.5..7.9)?
The implementation I have used in my patch is equivalent to:
(5.5..7.9).cover?((5..10).min) && (5.5..7.9).cover?((5..10).max)
which is false, but means
(6..7).subset?(5.5..8.5)
is true as both
(5.5..8.5).cover?(6) and
(5.5..8.5).cover?(7) are true.
I think this result is what I would expect - what do you think?
Or what if we introduce something like Range.new(1, 10, step: 2), which would produce [1, 3, 5, 7, 9] when converted to an Array?
Assuming the implementation in terms of
cover? (and using the
subrange? naming) I think this would still make sense:
(2..4).subrange?(Range.new(1, 5, step: 2)) # => true
Updated by owst (Owen Stephens) over 3 years ago
- File v2-0001-range.c-add-subset-superset-methods.patch v2-0001-range.c-add-subset-superset-methods.patch added
Attached updated patch, the former had a syntax error (a missing
)).
Updated by al2o3cr (Matt Jones) over 3 years ago
Minor point: IMO a "Range with steps" isn't a Range, it's something else. It doesn't seem relevant to the discussion.
Bigger point: the tests on improper ranges in the patch seem to imply some odd consequences:
range_1 = "g".."f" range_2 = "b".."e" range_1.subset?(range_2) # => true range_2.any? { |el| range_1.include? el } # => false
So
range_1 claims to be a subset of
range_2, but no elements of
range_2 are included in
range_1.
range_3 = "d".."a" range_1.subset?(range_3) # => true range_3.subset?(range_1) # => true
Generally,
a <= b and
b <= a implies
a == b. In this case, however, the early return in
range_subset means that any improper range passed to
subset? will return
true.
min and
max also have bad performance characteristics for exclusive ranges that
linear_object_p returns
false for, as they need to generate all the intermediate elements using
succ. For instance, attempting to evaluate
("aaaaaaaaaa"..."zzzzzzzzzz").max ran for over a minute before I gave up and aborted it. There's also explicit code (see
discrete_object_p and callsites) that makes exclusive ranges of
Time objects raise
TypeError if you call
max on them.
Updated by vo.x (Vit Ondruch) over 3 years ago
Why not modify Range#include? to accept Range object. Anyway, there is missing any justification for the RFE.
Updated by owst (Owen Stephens) over 3 years ago
Thanks for your thoughts al2o3cr, your "bigger point" is interesting:
So range_1 claims to be a subset of range_2, but no elements of range_2 are included in range_1.
My thinking here was that the empty set is a subset of all sets, so similar behaviour seemed reasonable for empty/invalid Ranges, i.e. phrase the subset "definition" as: "all elements of range_1 are covered by range_2", which is vacuously true.
You're right about the implication for
<= so maybe it's a bad idea to treat "empty"/invalid ranges as if they were empty sets (and thus all equivalent). However, the same thing is true for exclusive/inclusive ranges that contain the same elements (when considered as sets):
> (1..2).subset?(1...3) => true > (1...3).subset?(1..2) => true > (1..2) == (1...3) => false > Set.new((1..2)) == Set.new((1...3)) => true
With
.. vs
... we can have non-equal Range representations of the same set of elements. I'm not sure what to suggest here. It doesn't quite feel right to restrict
subset? to only allow an argument with the same
exclude_end? value.
min and max also have bad performance characteristics for exclusive ranges that linear_object_p returns false for,
Yes, I didn't like this myself, I'm glad you've brought it up. An option would be to prevent such calls from occurring, which doesn't seem nice, but is probably preferable to performance issues?
Updated by owst (Owen Stephens) over 3 years ago
Good point v.ox, I did consider implementing
subset? as an overloading of
include? (or possibly
cover? ?), as one can't have a range-of-ranges (so there is no ambiguity).
How would you distinguish between strict/non-strict - a
strict: kwarg, perhaps? Something like:
(1..3).cover?((1..3)) # => true (1..3).cover?((1..3), strict: false) # => true (1..3).cover?((1..3), strict: true) # => false (1..3).cover?((1..2), strict: true) # => true
I'm not sure the level of justification required for a method to be included in the stdlib, but I can provide an example where we would (and do) use
Range#subset?: we have products that have a range of allowed values, and in some circumstances we restrict products to a dynamically-generated range of allowed values, and want to make sure that range is compatible with the product range, something like:
raise ArgumentError unless dynamic_value_range.subset?(product_value_range)
The other methods (
strict_subset?, and the
*superset? methods) were only added for symmetry.
Updated by owst (Owen Stephens) about 3 years ago
Are there any further thoughts on my latest patch? Based on the discussion above, I think I should rename the added methods:
s/set/range/ and perhaps also prevent the "bad performance" cases where either range has
exclude_end? true and
linear_object_p false?
Updated by owst (Owen Stephens) about 3 years ago
- File v3-0001-range.c-add-subrange-superrange-methods.patch v3-0001-range.c-add-subrange-superrange-methods.patch added
I've attached an updated patch; it includes the renamed (by
s/set/range/) methods and a performance improvement for
strict_subset? (before, we would calculate
max on the receiver twice, which is potentially slow when the receiver is an exclude_end Range of non-Numeric objects, now it's only calculated once).
Any comments would be gratefully received!
Updated by matz (Yukihiro Matsumoto) about 3 years ago
- Status changed from Open to Feedback
Any (real-world) use-case?
Matz.
Updated by owst (Owen Stephens) about 3 years ago
Hi Matz!
A slightly contrived example - imagine we want to filter candidates for a new job position and harshly reject any who have a salary requirement that is not covered by our predetermined position salary range:
Candidate = Struct.new(:name, :desired_salary_range) candidates = [ Candidate.new('Andrew', (15_000..20_500)), Candidate.new('John', (25_000..35_000)), Candidate.new('Owen', (15_000..17_500)), Candidate.new('Zack', (5_000..9_000)), ] position_salary_range = (10_000..20_000) acceptable, unacceptable = candidates.partition { |c| c.desired_salary_range.subrange?(position_salary_range) } puts "Unacceptable: #{unacceptable.map(&:name).join(',')}" # => Unacceptable: Andrew, John, Jack puts "Acceptable: #{acceptable.map(&:name).join(',')}" # => Acceptable: Owen
Looks like I've got the job, as no-one else is acceptable! :-)
As a more serious example, in my job, we offer loans of between £1000 and £8000. We allow certain customers to top-up their loans with an additional advance (chosen from a range of possible advances), if the new loan (the top-up is considered as a new loan) will pay-off their existing loan and cover all possible additional advances. Therefore, to check if someone can top-up their loan we do something similar to:
class Range def offset(n) (first + n..last + n) end end VALID_LOAN_VALUE_RANGE = (1000..8000) TOP_UP_RANGE = (1..5) # For example; very unrealistic numbers def top_up_message(existing_loan_settlement_value) top_up_value_range = TOP_UP_RANGE.offset(existing_loan_settlement_value) if top_up_value_range.subrange?(VALID_LOAN_VALUE_RANGE) puts "you may top-up your loan with between £#{TOP_UP_RANGE.first} and £#{TOP_UP_RANGE.last}!" else puts "sorry, at this stage we can't top-up your loan" end end puts top_up_message(7995) # => you may top-up... puts top_up_message(7999) # => sorry...
N.b. this adds another useful Range method, Range#offset (which probably only makes sense for numeric ranges), would you accept a new Feature to add this method?
Finally, regarding naming, I think I now prefer overriding
cover? to accept a Range - when I described this feature to my colleague I used the phrase "does one range cover the other?" as an intuition, and indeed, that is how it's implemented.
Please let me know your thoughts.
Updated by shevegen (Robert A. Heiler) about 3 years ago
I have no particular opinion (neither pro nor con) on the issue itself.
On the comment:
[..] this adds another useful Range method, Range#offset (which probably only makes sense for
numeric ranges), would you accept a new Feature to add this method?
I think it would be best to add a new issue for Range#offset; you can then link into the
issue here too, from that other issue. It makes it easier for other people to comment
on it and, I think, also easier to approve it, if it is useful.
Updated by tarui (Masaya Tarui) almost 3 years ago
As real-world use-case,
I want it(include,cover version) for guarding NArray's Index arguments.
NArray#[] can accept Integer and Range.
Currently, to limit the access range, We have to write complex code.
def check(idx,range) case idx when Integer range.include?(idx) when Range range.begin < idx.begin && ( (!range.exclude_end? && !idx.exclude__end? || range.exclude_end?) ? range.end >=idx.end : range.end > idx.end) end end
I want to write simply
range.include?(idx)
Updated by marcandre (Marc-Andre Lafortune) almost 3 years ago
Not directly related, but if your ranges are such that begin <= end, then I think you can use
range.max > idx.max for the last part.
Updated by znz (Kazuhiro NISHIYAMA) almost 3 years ago
How about
Range#{<,<=,>,>=} like
Hash#{<,<=,>,>=} for method names?
Updated by matz (Yukihiro Matsumoto) almost 3 years ago
- Status changed from Feedback to Open
The method name
subrange? may cause confusion that which includes which.
I propose
cover? to accept ranges.
Matz.
Updated by tarui (Masaya Tarui) almost 3 years ago
- Assignee set to tarui (Masaya Tarui)
- Status changed from Open to Assigned
Updated by owst (Owen Stephens) almost 3 years ago
- File v4-0001-range.c-allow-cover-to-accept-Range-argument.patch v4-0001-range.c-allow-cover-to-accept-Range-argument.patch added
Thank you for your proposal Matz, having thought about it over the last few months, I agree.
I have updated my patch accordingly (which has greatly simplified/improved it), I welcome any comments.
Updated by tarui (Masaya Tarui) almost 3 years ago
Thank you for your patch owst.
I reviewed it and feel the behavior below is strange.
$ ruby -e 'p (1..3.1).cover?(1...3)' true $ ruby -e 'p (1..3.1).cover?(1...4)' Traceback (most recent call last): 1: from -e:1:in `<main>' -e:1:in `cover?': can't iterate from Float (TypeError)
At
(a..b).cover?(c...d) with
b < d,
is it reasonable to use
(c...d).max(but ignore exception) for comparison with
b?
Updated by owst (Owen Stephens) almost 3 years ago
- File v5-0001-range.c-allow-cover-to-accept-Range-argument.patch v5-0001-range.c-allow-cover-to-accept-Range-argument.patch added
Hi tarui, thank you for reviewing and your suggestion/question.
In fact, with my v4 patch in the case you describe there is a bug:
(1..3).cover?(1.0...4.0) is
true not
false. This is prevented using
b >= (c...d).max as you suggest, but I see two issues:
First, the performance of
Range#max is very bad in certain cases (as al2o3c pointed out above) e.g. on my machine (Macbook Pro, 2.8 GHz i5) I now have:
$ time ruby -e "p ('aaaaa'..'zzzzz').cover?('aaaaa'...'zzzzz')" true ruby -e "p ('aaaaa'..'zzzzz').cover?('aaaaa'...'zzzzz')" 0.19s user 0.05s system 92% cpu 0.256 total $ time ruby -e "p ('aaaaa'..'zzzzy').cover?('aaaaa'...'zzzzz')" true ruby -e "p ('aaaaa'..'zzzzy').cover?('aaaaa'...'zzzzz')" 8.12s user 0.07s system 98% cpu 8.329 total
Second, we have the following strange behaviour that is similar to that in your comment:
$ ruby -e "p (1..4).cover?(1.0...4.0)" true $ ruby -e "p (1..3).cover?(1.0...4.0)" Traceback (most recent call last): 2: from -e:1:in `<main>' 1: from -e:1:in `cover?' -e:1:in `max': cannot exclude non Integer end value (TypeError)
I have attached an updated patch, which uses
max, but does not address either of the above issues. Can you see an alternative that addresses these issues in a straightforward way?
Updated by Anonymous almost 3 years ago
Thank you for the new patch.
At the first issue, I understood max method has performance issue at that case.
But how often will we encounter it? I think it is a very rare case.
Or please show the application.
At the second issue, as I already said 'ignore exception',
I think that it should return false rather than raising an exception.
Updated by owst (Owen Stephens) almost 3 years ago
- File v6-0001-range.c-allow-cover-to-accept-Range-argument.patch v6-0001-range.c-allow-cover-to-accept-Range-argument.patch added
I agree that the max performance issue is likely to be a rare case; I am happy to leave it as-is.
Apologies on the second issue - I originally misunderstood "ignore" to mean "don't rescue".
I've attached another updated patch - it rescues the TypeError raised by
max, and also fixes the handling of endless/empty ranges.
Updated by tarui (Masaya Tarui) almost 3 years ago
I am happy that match opinion with you.
I will commit based on your patch. It'll take a little while.
Updated by owst (Owen Stephens) almost 3 years ago
Great, thank you tarui
Updated by tarui (Masaya Tarui) almost 3 years ago
- Status changed from Assigned to Closed
Applied in changeset trunk|r64640.
range.c: Range#cover? accepts Range object. [Feature #14473]
* range.c (range_cover): add code for range argument. If the argument is a Range, check it is or is not covered by the reciver. If it can be treated as a sequence, this method treats it that way. * test/ruby/test_range.rb (class TestRange): add tests for this feature. This patch is written by Owen Stephens. thank you!
Also available in: Atom PDF
|
https://bugs.ruby-lang.org/issues/14473?tab=notes
|
CC-MAIN-2021-25
|
refinedweb
| 3,069 | 61.02 |
I’m confused about what’s going on in one of my integration tests, if I coud just see the component being rendered and clicked that would help trmemendously. Is there a way I can either capture a screenshot of the component to see its state, or have non-headless chrome so that I can view the test ?
You can run your tests in your browser with
ember test --server. After that starts up you can view/run the tests by visiting
You can also use the
pauseTest helper from ember-test-helpers to pause your test:
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, pauseTest } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | foo-bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { await render(hbs`{{foo-bar}}`); await pauseTest(); assert.equal(this.element.textContent.trim(), 'template block text'); }); });
You can also check the “Development Mode” checkbox in the test runner in your browser to view the component in a full-screen-screen kinda view.
Thanks for the example! You pointed me in the right direction. My problem is that I’m using ember-mocha , so while I’m able to see the test being run at localhost:7357 they run super fast and I can’t see what’s going on, and there is no
development mode or any other option when I run tests in the browser. All I see is this:
I tried using
pauseTest but when I include
import { render, pauseTest } from '@ember/test-helpers'; The tests simply do not run.
Hello @GregWeb, are you using the new testing API? which version of
ember-mocha are you on?
If you want to use
pauseTest from
import { pauseTest } from '@ember/test-helpers'; you will need to use the new testing API and
ember-mocha must be =>
v0.14.0-beta.1
If you’re on
ember-mocha <
0.13.1 then you can simply do:
it('renders', function(done) { this.timeout(30000); //... this.render(); setTimeout(() => done(), 30000); //... });
Hi @esbanarango thanks for the tip. we’re using ember
2.18.1 with
ember-mocha: 0.12.0. I will make a note to update. But what do you mean by the new test API? You mean in the post ember 3 changes?
@GregWeb Yeah, the new testing API is basically based on these RFCs 232 and 268. You can check the migration guide for mocha here:.
But since you’re on
ember-mocha: 0.12.0 you can simply use
this.timeout(xx); and
setTimeout(() => done(), xx); as I showed before.
The new testing APIs aren’t tied to any particular ember version – you can update your tests to the new format whenever you want to, or keep a mix of old-style and new-style tests if there’s stuff you don’t want to change.
Thanks again, got your example to work, however it required changing the global timeout in
test-helper.js.
However I gotta say it’s a little silly to do it this way IMHO for what should just be a simple
wait() or
pause() or
sleep(). I feel like if such a basic thing is lacking in ember-mocha there might be other simple issues we might run into in the long run, might as well switch back to qunit.
@GregWeb Great! You may want to read this thread
Why does rwjblue like Qunit so much more than Mocha?
|
https://discuss.emberjs.com/t/how-can-i-visually-see-an-integration-test/14761
|
CC-MAIN-2022-33
|
refinedweb
| 579 | 71.85 |
changequoteis Evil
$<in Ordinary Make Rules
make macro=valueand Submakes
SHELL
make -k
VPATHand Make
VPATH
VPATHand Double-colon Rules
$<Not Supported in Explicit Rules
AC_LIBOBJvs.
LIBOBJS
AC_ACT
_IFELSEvs.
AC_TRY_ACT
#defineInstallation Directories?
This manual (24 April 2012) is for GNU Autoconf (version 2.69), a package for creating scripts to configure source code packages using templates and an M4 macro
Programming in M4sh
Writing Autoconf Macros
Dependencies Between Macros
Portable Shell Programming
Portable Make Programming
VPATH and Make
Portable C and C++ Programming
Integer Overflow
nature of God. “Surely a Physicist,” said the physicist, “because
early in the Creation, God made Light; and you know, Maxwell's
equations, the dual nature of electromagnetic waves, the relativistic Pos.
Those who do not understand Autoconf are condemned to reinvent it, poorly. The primary goal of Autoconf is making the user's life easier; making the maintainer's life easier is only a secondary goal. Put another way, the primary goal is not to make the generation of configure automatic for package maintainers (although patches along that front are welcome, since package maintainers form the user base of Autoconf); rather, the goal is to make configure painless, portable, and predictable for the end user of each autoconfiscated package. And to this degree, Autoconf is highly successful at its goal — most complaints to the Autoconf list are about difficulties in writing Autoconf input, and not in the behavior of the resulting configure. Even packages that don't use Autoconf will generally provide a configure script, and the most common complaint about these alternative home-grown scripts is that they fail to meet one or more of the GNU Coding Standards (see Configuration) that users have come to expect from Autoconf-generated configure scripts..
Autoconf does not solve all problems related to making portable software packages—for a more complete solution, it should be used in concert with other GNU build tools like Automake and Libtool. These other tools take on jobs like the creation of a portable, recursive makefile with all of the standard targets, linking of shared libraries, and so on. See The GNU Build System, for more information.
Autoconf imposes some restrictions on the names of macros used with
#if in C programs (see Preprocessor Symbol Index).
Autoconf requires GNU M4 version 1.4.6 or later in order to generate the scripts. It uses features that some versions of M4, including GNU M4 1.3, do not have. Autoconf works better with GNU M4 version 1.4.14 or later, though this is not required.
See Autoconf 1, for information about upgrading from version 1. See History, for the story of Autoconf's development. See FAQ, for answers to some common questions about Autoconf.
See the Autoconf web page for up-to-date information, details on the mailing lists, pointers to a list of known bugs, etc.
Mail suggestions to the Autoconf mailing list. Past suggestions are archived.
Mail bug reports to the Autoconf Bugs mailing list. Past bug reports are archived.
If possible, first check that your bug is not already solved in current development versions, and that it has not been reported yet. Be sure to include all the needed information and a short configure.ac that demonstrates the problem.
Autoconf's development tree is accessible via git; see the Autoconf Summary for details, or view the actual repository. Anonymous CVS access is also available, see README for more details. Patches relative to the current git version can be sent for review to the Autoconf Patches mailing list, with discussion on prior patches archived; and all commits are posted in the read-only Autoconf Commit mailing list, which is also archived.
Because of its mission, the Autoconf package itself includes only a set of often-used macros that have already demonstrated their usefulness. Nevertheless, if you wish to share your macros, or find existing ones, see the Autoconf Macro Archive, which is kindly run by Peter Simons.
Autoconf solves an important problem—reliable discovery of system-specific build and runtime its numerous limitations. Its lack of
support for automatic dependency tracking, recursive builds in
subdirectories, reliable timestamps (e.g., for network file systems),
builds the
hello program, and
make install installs free software packages. Its components are typically shared at the source level, rather than being a library that gets built, installed, and linked against. The idea is to copy files from Gnulib into your own source tree. There is no distribution tarball; developers should just grab source modules from the repository. The source files are available online, under various licenses, mostly GNU GPL or GNU LGPL.
Gnulib modules typically contain C source code along with Autoconf
macros used to configure the source code. For example, the Gnulib
stdbool module implements a stdbool.h header that nearly
conforms to C99, even on old-fashioned hosts that lack stdbool.h.
This module contains a source file for the replacement header, along
with an Autoconf macro that arranges to use the replacement header on
old-fashioned systems. without Automake, otherwise quickly find yourself putting lots of effort into reinventing the services that the GNU build tools provide, and making the same mistakes that they once made and overcame. (Besides, since you're already learning Autoconf, Automake is a piece of cake.)
There are a number of places that you can go to for more information on the GNU build tools.
The project home pages for Autoconf, Automake, Gnulib, and Libtool.
See Automake, for more information on Automake.
The book GNU Autoconf, Automake and Libtool1 describes the complete GNU build environment. You can also find the entire book on-line.
The configuration scripts that Autoconf produces are by convention called configure. When run, configure creates several files, replacing configuration parameters in them with appropriate values. The files that configure creates are:
#definedirectives (see Configuration Headers); can distribute the generated file
config.h.in with the package.
Here is a diagram showing how the files that can be used in configuration are produced. Programs that are executed are suffixed by ‘*’. Optional files are enclosed in square brackets (‘[]’). autoconf and autoheader also read the installed Autoconf macro files (by reading autoconf.m4).
Files used in preparing a software package for distribution, when using just Autoconf:
your source files --> [autoscan*] --> [configure.scan] --> configure.ac configure.ac --. | .------> autoconf* -----> configure [aclocal.m4] --+---+ | `-----> [autoheader*] --> [config.h.in] [acsite.m4] ---' Makefile.in
Additionally, if you use Automake, the following additional productions come into play:
[acinclude.m4] --. | [local macros] --+--> aclocal* --> aclocal.m4 | configure.ac ----' configure.ac --. +--> automake* --> Makefile.in Makefile.am ---'
Files used in configuring a software package:
.-------------> [config.cache] configure* ------------+-------------> config.log | [config.h.in] -. v .-> [config.h] -. +--> config.status* -+ +--> make* Makefile.in ---' `-> Makefile ---'
To produce a configure script for a software package, create a file called configure.ac that contains invocations of the Autoconf macros that test the system features your package needs or can use. Autoconf macros already exist to check for many features; see Existing Tests, for their descriptions. For most other features, you can use Autoconf template macros to produce custom checks; see Writing Tests, for information about them. For especially tricky or specialized features, configure.ac might need to contain some hand-crafted shell commands; see Portable Shell Programming. The autoscan program can give you a good start in writing configure.ac (see autoscan Invocation, for more information).
Previous versions of Autoconf promoted the name configure.in, which is somewhat ambiguous (the tool needed to process this file is not described by its extension), and introduces a slight confusion with config.h.in and so on (for which ‘, even in 2008, where shells without any function support are far and few between, there are pitfalls to avoid when making use of them. Also, finding a Bourne shell that accepts shell functions is not trivial, even though there is almost always one on interesting porting targets. differs from many other computer languages because it treats actual code the same as plain text. Whereas in C, for instance, data and instructions have different syntactic status, in Autoconf their status is rigorously the same. Therefore, we need a means to distinguish literal strings from text to be expanded: quotation.
When calling macros that take arguments, there must not be any white space between the macro name and the open parenthesis.
AC_INIT ([oops], [1.0]) # incorrect AC_INIT([hello], [1.0]) # good
Arguments should be enclosed within the quote characters ‘[’ and ‘]’, and be separated by commas. Any leading blanks or newlines in arguments are ignored, unless they are quoted. You should always quote an argument that might contain a macro name, comma, parenthesis, or a leading blank or newline. This rule applies recursively for every macro call, including macros called from other macros. For more details on quoting rules, see Programming in M4.
For instance:
AC_CHECK_HEADER([stdio.h], [AC_DEFINE([HAVE_STDIO_H], [1], [Define to 1 if you have <stdio.h>.])], [AC_MSG_ERROR([sorry, can't do anything for you])])
is quoted properly. You may safely simplify its quotation to:
AC_CHECK_HEADER([stdio.h], [AC_DEFINE([HAVE_STDIO_H], 1, [Define to 1 if you have <stdio.h>.])], [AC_MSG_ERROR([sorry, can't do anything for you])])
because ‘1’ cannot contain a macro call. Here, the argument of
AC_MSG_ERROR must be quoted; otherwise, its comma would be
interpreted as an argument separator. Also, the second and third arguments
of ‘AC_CHECK_HEADER’ must be quoted, since they contain
macro calls. The three arguments ‘HAVE_STDIO_H’, ‘stdio.h’,
and ‘Define to 1 if you have <stdio.h>.’ do not need quoting, but
if you unwisely defined a macro with a name like ‘Define’ or
‘stdio’ then they would need quoting. Cautious Autoconf users
would keep the quotes, but many Autoconf users find such precautions
annoying, and would rewrite the example as follows:
AC_CHECK_HEADER(stdio.h, [AC_DEFINE(HAVE_STDIO_H, 1, [Define to 1 if you have <stdio.h>.])], [AC_MSG_ERROR([sorry, can't do anything for you])])
This is safe, so long as you adopt good naming conventions and do not define macros with names like ‘HAVE_STDIO_H’, ‘stdio’, or ‘h’. Though it is also safe here to omit the quotes around ‘Define to 1 if you have <stdio.h>.’ this is not recommended, as message strings are more likely to inadvertently contain commas.
The following example is wrong and dangerous, as it is underquoted:
AC_CHECK_HEADER(stdio.h, AC_DEFINE(HAVE_STDIO_H, 1, Define to 1 if you have <stdio.h>.), AC_MSG_ERROR([sorry, can't do anything for you]))
In other cases, you may have to use text that also resembles a macro
call. You must quote that text even when it is not passed as a macro
argument. For example, these two approaches in configure.ac
(quoting just the potential problems, or quoting the entire line) will
protect your script in case autoconf ever adds a macro
AC_DC:
echo "Hard rock was here! --[AC_DC]" [echo "Hard rock was here! --AC_DC"]
which results in this text in configure:
echo "Hard rock was here! --AC_DC" echo "Hard rock was here! --AC_DC"
When you use the same text in a macro argument, you must therefore have an extra quotation level (since one is stripped away by the macro substitution). In general, then, it is a good idea to use double quoting for all literal string arguments, either around just the problematic portions, or over the entire argument:
AC_MSG_WARN([[AC_DC] stinks --Iron Maiden]) AC_MSG_WARN([[AC_DC stinks --Iron Maiden]])
However, the above example triggers a warning about a possibly unexpanded macro when running autoconf, because it collides with the namespace of macros reserved for the Autoconf language. To be really safe, you can use additional escaping (either a quadrigraph, or creative shell constructs) to silence that particular warning:
echo "Hard rock was here! --AC""_DC" AC_MSG_WARN([[AC@&t@_DC stinks --Iron Maiden]])
You are now able to understand one of the constructs of Autoconf that has been continually misunderstood... The rule of thumb is that whenever you expect macro expansion, expect quote expansion; i.e., expect one level of quotes to be lost. For instance:
AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [], [AC_MSG_ERROR([you lose])])
is incorrect: here, the first argument of
AC_LANG_SOURCE is
‘char b[10];’ and is expanded once, which results in
‘char b10;’; and the
AC_LANG_SOURCE is also expanded prior
to being passed to
AC_COMPILE_IFELSE. ;
likewise, the intermediate
AC_LANG_SOURCE macro should be quoted
once so that it is only expanded after the rest of the body of
AC_COMPILE_IFELSE is in place:
AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [], [AC_MSG_ERROR([you lose])])
Voilà, you actually produce ‘char b[10];’ this time!
On the other hand, descriptions (e.g., the last parameter of
AC_DEFINE or
AS_HELP_STRING) are not literals—they
are subject to line breaking, for example—and should not be double quoted.
Even if these descriptions are short and are not actually broken, double
quoting them yields weird results.
Some macros take optional arguments, which this documentation represents as [arg] (not to be confused with the quote characters). You may just leave them empty, or use ‘[]’ to make the emptiness of the argument explicit, or you may simply omit the trailing commas. The three lines below are equivalent:
AC_CHECK_HEADERS([stdio.h], [], [], []) AC_CHECK_HEADERS([stdio.h],,,) AC_CHECK_HEADERS([stdio.h]) ‘#’. For example, it is helpful to begin configure.ac files with a line like this:
# Process this file with autoconf to produce a configure script.
The order in which configure.ac calls the Autoconf macros is not
important, with a few exceptions. Every configure.ac must
contain a call to
AC_INIT before the checks, and a call to
AC_OUTPUT at the end (see Output). Additionally, some macros
rely on other macros having been called first, because they check
previously set values of some variables to decide what to do. These
macros are noted in the individual descriptions oconf requirements
AC_INIT(package
,version
,bug-report-address
)information on the package checks for programs checks for libraries checks for header files checks for types checks for structures checks for compiler characteristics checks for library functions checks for system services
AC_CONFIG_FILES([file...]
)
AC_OUTPUT Configuration Headers). You might
also have to change or add some
#if directives to your program in
order to make it work with Autoconf (see ifnames Invocation, for
information about a program that can help with that job).
When using autoscan to maintain a configure.ac, simply consider adding its suggestions. The file autoscan.log contains, one or more blanks, and the Autoconf macro to output if that symbol is encountered. Lines starting with ‘#’ are comments.
autoscan accepts the following options: autoscan Invocation)..
Because autoconf uses autom4te behind the scenes, it
displays a back trace for errors, but not for warnings; if you want
them, just pass -W error. See autom4te Invocation, for some
examples.
The format is a regular string, with newlines if desired, and
several special escape codes. It defaults to ‘$f:$l:$n:$%’; see
autom4te Invocation,:
$ autoconf -t AC_SUBST configure.ac:2:AC_SUBST:ECHO_C configure.ac:2:AC_SUBST:ECHO_N configure.ac:2:AC_SUBST:ECHO_T More traces deleted
The example below highlights the difference between ‘$@’, ‘$*’, and ‘$%’.
$ cat configure.ac AC_DEFINE(This, is, [an [example]]) $ autoconf -t 'AC_DEFINE:@: $@ *: $* %: $%' @: [This],[is],[an [example]] *: This,is,an [example] %: This:is:an [example]
The format gives you a lot of freedom:
$ autoconf -t 'AC_SUBST:$$ac_subst{"$1"} = "$f:$l";' $ac_subst{"ECHO_C"} = "configure.ac:2"; $ac_subst{"ECHO_N"} = "configure.ac:2"; $ac_subst{"ECHO_T"} = "configure.ac:2"; More traces deleted
A long separator can be used to improve the readability of complex structures, and to ease their parsing (for instance when no single character is suitable as a separator):
$ autoconf -t 'AM_MISSING_PROG:${|:::::|}*' ACLOCAL|:::::|aclocal|:::::|$missing_dir AUTOCONF|:::::|autoconf|:::::|$missing_dir AUTOMAKE|:::::|automake|:::::|$missing_dir More traces deleted AUTOM4TE,.
Autoconf-generated configure scripts need some information about how to initialize, such as how to find the package's source files and about the output files to produce. The following sections describe the initialization and the creation of output files.
Every configure script must call
AC_INIT before doing
anything else that produces output. Calls to silent macros, such as
AC_DEFUN, may also occur prior to
AC_INIT, although these
are generally used via aclocal.m4, since that is implicitly
included before the start of configure.ac. The only other
required macro is
AC_OUTPUT (see Output).
Process any command-line arguments and perform initialization and verification.
Set the name of the package and its version. These are typically used in --version support, including that of configure. The optional argument bug-report should be the email to which users should send bug reports. The package tarname differs from package: the latter designates the full package name (e.g., ‘GNU Autoconf’), while the former is meant for distribution tar ball names (e.g., ‘autoconf’). It defaults to package with ‘GNU ’ stripped, lower-cased, and all characters other than alphanumerics and underscores are changed to ‘-’. If provided, url should be the home page for the package.
The arguments of
AC_INITmust be static, i.e., there should not be any shell computation, quotes, or newlines, but they can be computed by M4. This is because the package information strings are expanded at M4 time into several contexts, and must give the same text at shell time whether used in single-quoted strings, double-quoted strings, quoted here-documents, or unquoted here-documents. It is permissible to use
m4_esyscmdor
m4_esyscmd_sfor computing a version string that changes with every commit to a version control system (in fact, Autoconf does just that, for all builds of the development tree made between releases).
The following M4 macros (e.g.,
AC_PACKAGE_NAME), output variables (e.g.,
PACKAGE_NAME), and preprocessor symbols (e.g.,
PACKAGE_NAME), are defined by
AC_INIT:
AC_PACKAGE_NAME,
PACKAGE_NAME
- Exactly package.
AC_PACKAGE_TARNAME,
PACKAGE_TARNAME
- Exactly tarname, possibly generated from package.
AC_PACKAGE_VERSION,
PACKAGE_VERSION
- Exactly version.
AC_PACKAGE_STRING,
PACKAGE_STRING
- Exactly ‘package version’.
AC_PACKAGE_BUGREPORT,
PACKAGE_BUGREPORT
- Exactly bug-report, if one was provided. Typically an email address, or URL to a bug management web page.
AC_PACKAGE_URL,
PACKAGE_URL
- Exactly url, if one was provided. If url was empty, but package begins with ‘GNU ’, then this defaults to ‘’, otherwise, no URL is assumed.
If your configure script does its own option processing, it
should inspect ‘$@’ or ‘$*’ immediately after calling
AC_INIT, because other Autoconf macros liberally use the
set command to process strings, and this has the side effect
of updating ‘$@’ and ‘$*’. However, we suggest that you use
standard macros like
AC_ARG_ENABLE instead of attempting to
implement your own option processing. See Site Configuration..69]).69’. One potential use of this macro is for writing conditional fallbacks based on when a feature was added to Autoconf, rather than using
AC_PREREQtowould trigger the expansion of that macro during rescanning, and change the version string to be different than what you intended to check.
The following macros manage version numbers for configure scripts. Using them is optional.
State that, in addition to the Free Software Foundation's copyright on the Autoconf macros, parts of your configure are covered by the copyright-notice.
The copyright-notice shows up in both the head of configure and in ‘configure --version’.
unique-file-in-source-dir is some file that is in the package's source directory; configure checks for this file's existence to make sure that the directory that it is told contains the source code in fact does. Occasionally people accidentally specify the wrong directory with --srcdir; this is a safety check. See configure Invocation, for more information.
Packages that do manual configuration or use the install program
might need to tell configure where to find some other shell
scripts by calling
AC_CONFIG_AUX_DIR, though the default places
it looks are correct for most cases.
Use the auxiliary build tools (e.g., install-sh, config.sub, config.guess, Cygnus make have a rule that creates install from it if there is no makefile.
The auxiliary directory is commonly named build-aux. If you need portability to DOS variants, do not name the auxiliary directory aux. See File System Conventions.
Declares that file is expected in the directory defined above. In Autoconf proper, this macro does nothing: its sole purpose is to be traced by third-party tools to produce a list of expected auxiliary files. For instance it is called by macros like
AC_PROG_INSTALL(see Particular Programs) or
AC_CANONICAL_BUILD(see Canonicalizing) to register the auxiliary files they need.
Similarly, packages that use aclocal should declare where
local macros can be found using
AC_CONFIG_MACRO_DIR.
Specify dir as the location of additional local Autoconf macros. This macro is intended for use by future versions of commands like autoreconf that trace macro calls. It should be called directly from configure.ac so that tools that install macros for aclocal can find the macros' declarations.
Note that if you use aclocal from Automake to generate aclocal.m4, you must also set
ACLOCAL_AMFLAGS = -Idir in your top-level Makefile.am. Due to a limitation in the Autoconf implementation of autoreconf, these include directives currently must be set on a single line in Makefile.am, without any backslash-newlines._ITEMS(tag..., [commands], [init-cmds])
where the arguments are:
You are encouraged to use literals as tags. In particular, you should avoid
... && my_foos="$my_foos fooo" ... && my_foos="$my_foos foooo" AC_CONFIG_ITEMS([$my_foos])
and use this instead:
... && AC_CONFIG_ITEMS([fooo]) ... && AC_CONFIG_ITEMS([foooo])
The macros
AC_CONFIG_FILES and
AC_CONFIG_HEADERS use
special tag values: they may have the form ‘output’ or
‘output:inputs’. The file output is instantiated
from its templates, inputs (defaulting to ‘output.in’).
‘AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])’, for example, asks for the creation of the file Makefile that contains the expansion of the output variables in the concatenation of boiler/top.mk and boiler/bot.mk.
The special value ‘-’ might be used to denote the standard output when used in output, or the standard input when used in the inputs. You most probably don't need to use this in configure.ac, but it is convenient when using the command line interface of ./config.status, see config.status Invocation, for more details.
The inputs may be absolute or relative file names. In the latter
case they are first looked for in the build tree, and then in the source
tree. Input files should be text files, and a line length below 2000
bytes should be safe.
The variables set during the execution of configure are not available here: you first need to set them via the init-cmds. Nonetheless the following variables are precomputed:
srcdir
ac_top_srcdir
ac_top_build_prefix
ac_srcdir
tmp
The current directory refers to the directory (or pseudo-directory) containing the input part of tags. For instance, running
AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [...], [...])
with --srcdir=../package produces the following values:
# Argument of --srcdir srcdir='../package' # Reversing deep/dir ac_top_build_prefix='../../' # Concatenation of $ac_top_build_prefix and srcdir ac_top_srcdir='../../../package' # Concatenation of $ac_top_srcdir and deep/dir ac_srcdir='../../../package/deep/dir'
independently of ‘in/in.in’.
var. init-cmds is typically used by configure to give config.status some variables it needs to run the commands.
You should be extremely cautious in your variable names: all the init-cmds share the same name space and may overwrite each other in unpredictable ways. Sorry...
All these macros can be called multiple times, with different tag values, of course!
Be sure to read the previous section, Configuration Actions.
Make
AC_OUTPUTcreate each file by copying an input file (by default file.in), substituting the output variable values. This macro is one of the instantiating macros; see Configuration Actions. See Makefile Substitutions, for more information on using output variables. See Setting Output Variables, for more information on creating them. This macro creates the directory that the file is in if it doesn't exist. Usually, makefiles are created this way, but other files, such as .gdbinit, can be specified as well.
Typical calls to
AC_CONFIG_FILESlook DOS variants, or to prepend and/or append boilerplate to the file..
Some output variables are preset by the Autoconf macros. Some of the
Autoconf macros set additional output variables, which are mentioned in
the descriptions for those macros. See Output Variable Index, for a
complete list of output variables. See Installation Directory Variables, for the list of the preset ones related to installation
directories. Below are listed the other preset ones, many of which are
precious variables (see Setting Output Variables,
AC_ARG_VAR).
The preset variables which are available during config.status (see Configuration Actions) may also be used during configure tests. For example, it is permissible to reference ‘$srcdir’ when constructing a list of directories to pass via option -I during a compiler feature check. When used in this manner, coupled with the fact that configure is always run from the top build directory, it is sufficient to use just ‘$srcdir’ instead of ‘$top_srcdir’.
Debugging and optimization options for the C compiler. If it is not set in the environment when configure runs, the default value is set when you call
AC_PROG_CC(or empty if you don't). configure uses this variable when compiling or linking programs to test for C features.
If a compiler option affects only the behavior of the preprocessor (e.g., -Dname), it should be put into
CPPFLAGSinstead. If it affects only the linker (e.g., -Ldirectory), it should be put into
LDFLAGSinstead. If it affects only the compiler proper,
CFLAGSis the natural home for it. If an option affects multiple phases of the compiler, though, matters get tricky. One approach to put such options directly into
CC, e.g.,
CC='gcc -m64'. Another is to put them into both
CPPFLAGSand
LDFLAGS, but not into
CFLAGS.
However, remember that some Makefile variables are reserved by the GNU Coding Standards for the use of the “user”—the person building the package. For instance,
CFLAGSis one such variable.
Sometimes package developers are tempted to set user variables such as
CFLAGSbecause. If the package developer needs to add switches without interfering with the user, the proper way to do that is to introduce an additional variable. Automake makes this easy by introducing
AM_CFLAGS(see Flag Variables Ordering), but the concept is the same even if Automake is not used.
A comment saying that the file was generated automatically by configure.
Preprocessor options for the C, C++, Objective C, and Objective C++ preprocessors and compilers. If it is not set in the environment when configure runs, the default value is empty. configure uses this variable when preprocessing or compiling programs to test for C, C++, Objective C, and Objective C++ features.
This variable's contents should contain options like -I, -D, and -U that affect only the behavior of the preprocessor. Please see the explanation of
CFLAGSfor what you can do if an option affects other phases of the compiler as well.
Currently, configure always links as part of a single invocation of the compiler that also preprocesses and compiles, so it uses this variable also when linking programs. However, it is unwise to depend on this behavior because the GNU Coding Standards do not require it and many packages do not use
CPPFLAGSwhen linking programs.
See Special Chars in Variables, for limitations that
CPPFLAGSmight run into.
Debugging and optimization options for the C++ compiler. It acts like
CFLAGS, but for C++ instead of C.
-D options to pass to the C compiler. If
AC_CONFIG_HEADERSis called, configure replaces ‘@DEFS@’ with -DHAVE_CONFIG_H instead (see Configuration Headers). This variable is not defined while configure is performing its tests, only when creating the output files. See Setting Output Variables, for how to check the results of previous tests.
How does one suppress the trailing newline from echo for question-answer message pairs? These variables provide a way:echo $ECHO_N "And the winner is... $ECHO_C" sleep 100000000000 echo "${ECHO_T}dead."
Some old and uncommon echo implementations offer no means to achieve this, in which case
ECHO_Tis set to tab. You might not want to use it.
Debugging and optimization options for the Erlang compiler. If it is not set in the environment when configure runs, the default value is empty. configure uses this variable when compiling programs to test for Erlang features.
Debugging and optimization options for the Fortran compiler. If it is not set in the environment when configure runs, the default value is set when you call
AC_PROG_FC(or empty if you don't). configure uses this variable when compiling or linking programs to test for Fortran features.
Debugging and optimization options for the Fortran 77 compiler. If it is not set in the environment when configure runs, the default value is set when you call
AC_PROG_F77(or empty if you don't). configure uses this variable when compiling or linking programs to test for Fortran 77 features.
Options for the linker. If it is not set in the environment when configure runs, the default value is empty. configure uses this variable when linking programs to test for C, C++, Objective C, Objective C++, Fortran, and Go features.
This variable's contents should contain options like -s and -L that affect only the behavior of the linker. Please see the explanation of
CFLAGSfor what you can do if an option also affects other phases of the compiler.
Don't use this variable to pass library names (-l) to the linker; use
LIBSinstead.
-l options to pass to the linker. The default value is empty, but some Autoconf macros may prepend extra libraries to this variable if those libraries are found and provide necessary functions, see Libraries. configure uses this variable when linking programs to test for C, C++, Objective C, Objective C++, Fortran, and Go features.
Debugging and optimization options for the Objective C compiler. It acts like
CFLAGS, but for Objective C instead of C.
Debugging and optimization options for the Objective C++ compiler. It acts like
CXXFLAGS, but for Objective C++ instead of C++.
Debugging and optimization options for the Go compiler. It acts like
CFLAGS, but for Go instead of C.
The relative name of the top level of the current build tree. In the top-level directory, this is the same as
builddir.
The relative name of the top level of the current build tree with final slash if nonempty. This is the same as
top_builddir, except that it contains zero or more runs of
../, so it should not be appended with a slash for concatenation. This helps for make implementations that otherwise do not treat ./file and file as equal in the toplevel build directory.
The name of the top-level source code directory for the package. In the top-level directory, this is the same as
srcdir.
The following variables specify the directories for package installation, see Variables for Installation Directories, for more information. Each variable corresponds to an argument of configure; trailing slashes are stripped so that expressions such as ‘${prefix}/lib’ expand with only one slash between directory names. See the end of this section for details on when and how to use these variables.
The directory for installing idiosyncratic read-only architecture-independent data.
The root of the directory tree for read-only architecture-independent data files.
The installation prefix for architecture-dependent files. By default it's the same as
prefix. You should avoid installing anything directly to
exec_prefix. However, the default value for directories containing architecture-dependent files should be relative to
exec_prefix.
The directory for installing locale-dependent but architecture-independent data, such as message catalogs. This directory usually has a subdirectory per locale.
The common installation prefix for all files. If
exec_prefixis defined to a different value,
prefixis used only for architecture-independent files.
Most of these variables have values that rely on
prefix or
exec_prefix. It is deliberate that the directory output
variables keep them unexpanded: typically ‘@datarootdir@’ is
replaced by ‘${prefix}/share’, not ‘/usr/local/share’, and
‘@datadir@’ is replaced by ‘${datarootdir}’.
This behavior is mandated by the GNU Coding Standards, so that when the user runs:
In order to support these features, it is essential that
datarootdir remains defined as ‘${prefix}/share’,
so that its value can be expanded based
on the current value of
prefix.
A corollary is that you should not use these variables except in
makefiles. For instance, instead of trying to evaluate
datadir
in configure and hard-coding it in makefiles using
e.g., ‘AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])’,
you should add
-DDATADIR='$(datadir)' to your makefile's definition of
CPPFLAGS (
AM_CPPFLAGS if you are also using Automake).
Similarly, you should not rely on
AC_CONFIG_FILES to replace
bindir and friends in your shell scripts and other files; instead,
let make manage their replacement. For instance Autoconf
ships templates of its shell scripts ending with ‘.in’, and uses a
makefile snippet similar to the following to build scripts like
autoheader and autom4te:
edit = sed \ -e 's|@bindir[@]|$(bindir)|g' \ -e 's|@pkgdatadir[@]|$(pkgdatadir)|g' \ -e 's|@prefix[@]|$(prefix)|g' autoheader autom4te: Makefile rm -f $@ [email protected] srcdir=''; \ test -f ./[email protected] || srcdir=$(srcdir)/; \ $(edit) $${srcdir}[email protected] >[email protected] chmod +x [email protected] chmod a-w [email protected] mv [email protected] $@ autoheader: $(srcdir)/autoheader.in autom4te: $(srcdir)/autom4te.in
Some details are noteworthy:
VPATHshould not contain shell metacharacters or white space. See Special Chars in Variables.
edituses values that depend on the configuration specific values (
prefix, etc.) and not only on
VERSIONand so forth, the output depends on Makefile, not configure.ac.
autoconf autoheader: Makefile .in: rm -f $@ [email protected] $(edit) $< >[email protected] chmod +x [email protected] mv [email protected] $@
See Single Suffix Rules, for details.
For the more specific installation of Erlang libraries, the following variables are defined:
The common parent directory of Erlang library installation directories. This variable is set by calling the
AC_ERLANG_SUBST_INSTALL_LIB_DIRmacro in configure.ac.
The installation directory for Erlang library library. This variable is set by using the ‘AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR’ macro in configure.ac.
See Erlang Libraries, for details.. If you are upgrading from an earlier Autoconf version, you may need to adjust your files to ensure that the directory variables are substituted correctly (see Defining Directories), and that a definition of datarootdir is in place. For example, in a Makefile.in, adding
datarootdir = @datarootdir@
is usually sufficient. If you use Automake to create Makefile.in, it will add this for you.
To help with the transition, Autoconf warns about files that seem to use
datarootdir without defining it. In some cases, it then expands
the value of
$datarootdir in substitutions of the directory
variables. The following example shows such a warning:
$ cat configure.ac AC_INIT AC_CONFIG_FILES([Makefile]) AC_OUTPUT $ cat Makefile.in prefix = @prefix@ datadir = @datadir@ $ autoconf $ configure configure: creating ./config.status config.status: creating Makefile config.status: WARNING: Makefile.in seems to ignore the --datarootdir setting $ cat Makefile prefix = /usr/local datadir = ${prefix}/share
Usually one can easily change the file to accommodate both older and newer Autoconf releases:
$ cat Makefile.in prefix = @prefix@ datarootdir = @datarootdir@ datadir = @datadir@ $ configure configure: creating ./config.status config.status: creating Makefile $ cat Makefile prefix = /usr/local datarootdir = ${prefix}/share datadir = ${datarootdir}
In some cases, however, the checks may not be able to detect that a suitable
initialization of
datarootdir is in place, or they may fail to detect
that such an initialization is necessary in the output file. If, after
auditing your package, there are still spurious configure warnings about
datarootdir, you may add the line
AC_DEFUN([AC_DATAROOTDIR_CHECKED])
to your configure.ac to disable the warnings. This is an exception
to the usual rule that you should not define a macro whose name begins with
AC_ (see Macro Names).
can do this. Most other recent make programs can do this as
well, though they may have difficulties and it is often simpler to
recommend GNU make (see VPATH and Make). Older
make programs do not support
VPATH; when using them, the
source code must be in the same directory as the object files.
If you are using GNU Automake, the remaining details in this
section are already covered for you, based on the contents of your
Makefile.am. But if you are using Autoconf in isolation, then
supporting
VPATH requires the following in your
Makefile.in:
srcdir = @srcdir@ VPATH = @srcdir@
Do not set
VPATH to the value of another variable (see Variables listed in VPATH.
configure substitutes the correct value for
srcdir when
it produces Makefile.
Do not use the make variable
$<, which expands to the
file name of the file in the source directory (found with
VPATH),
except in implicit rules. (An implicit rule is one such as ‘.c.o’,
which tells how to create a .o file from a .c file.) Some
versions of make do not set
$< in explicit rules; they
expand it to an empty value.
Instead, Make command lines should always refer to source files by prefixing them with ‘$ ‘$(srcdir)/’ prefix is included because of limitations in the
VPATH mechanism.
The stamp- files are necessary because the timestamps of config.h.in and config.h are not changed if remaking them does not change their contents. This feature avoids unnecessary recompilation. You should include the file stamp-h.in in your package's distribution, so that make considers config.h.in up to date. Don't use touch (see Limitations of Usual Tools); instead, use echo (using need to convert the indented lines to start with the tab character.)
In addition, you should use
AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
so config.status ensures that config.h is considered up to
date. See Output, for more information about
AC_OUTPUT.
See config.status Invocation, for more examples of handling configuration-related dependencies..
The autoheader program can create a template file of C
‘#define’ statements for configure to use.
It searches for the first invocation of
AC_CONFIG_HEADERS in
configure sources to determine the name of the template.
(If the first call of
AC_CONFIG_HEADERS specifies more than one
input file name, autoheader uses the first one.)
It is recommended that only one input file is used. If you want to append
a boilerplate code, it is preferable to use
‘AH_BOTTOM([#include <conf_post.h>])’.
File conf_post.h is not processed during the configuration then,
which make things clearer. Analogically,
AH_TOP can be used to
prepend a boilerplate code.
In order to do its job, autoheader needs you to document all
of the symbols that you might use. Typically this is done via an
AC_DEFINE or
AC_DEFINE_UNQUOTED call whose first argument
is a literal symbol and whose third argument describes the symbol
(see Defining Symbols). Alternatively, you can use
AH_TEMPLATE (see Autoheader Macros), or you can supply a
suitable input file for a subsequent configuration header file.
Symbols defined by Autoconf's builtin tests are already documented properly;
you need to document only those that you
define yourself.
You might wonder why autoheader is needed: after all, why would configure need to “patch” a config.h.in to produce a config.h instead of just creating config.h from scratch? Well, when everything rocks, the answer is just that we are wasting our time maintaining autoheader: generating config.h directly is all that is needed. When things go wrong, however, you'll be thankful for the existence of autoheader.
The fact that the symbols are documented is important in order to check that config.h makes sense. The fact that there is a well-defined list of symbols that should be defined (or not) is also important for people who are porting packages to environments where configure cannot be run: they just have to fill in the blanks.
But let's come back to the point: the invocation of autoheader...
If you give autoheader an argument, it uses that file instead of configure.ac and writes the header file to the standard output instead of to config.h.in. If you give autoheader an argument of -, it reads the standard input instead of configure.ac and writes the header file to the standard output.
autoheader accepts the following options: template for a symbol is created
by autoheader from
the description argument to an
AC_DEFINE;
see Defining Symbols.
For special needs, you can use the following macros.
Tell autoheader to.])
generates
Tell autoheader to include the template as-is in the header template file. This template is associated with the key, which is used to sort all the different templates and guarantee their uniqueness. It should be a symbol that can be defined via
AC_DEFINE.
Please note that text gets included “verbatim” to the template file, not to the resulting config header, so it can easily get mangled when the template is processed. There is rarely a need for something other than
AH_BOTTOM([#include <custom.h>])
You can execute arbitrary commands before, during, and after
config.status is run. The three following macros accumulate the
commands to run when they are called multiple times.
AC_CONFIG_COMMANDS replaces the obsolete macro
AC_OUTPUT_COMMANDS; see Obsolete Macros, for details.
Specify additional shell commands to run at the end of config.status, and shell commands to initialize any variables from configure. Associate the commands with tag. Since typically the cmds create a file, tag should naturally be the name of that file. If needed, the directory hosting tag is created. This macro is one of the instantiating macros; see Configuration Actions.
Here is an unrealistic example:fubar=42 AC_CONFIG_COMMANDS([fubar], [echo this is extra $fubar, and so on.], [fubar=$fubar])
Here is a better one:AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
The following two macros look similar, but in fact they are not of the same breed: they are executed directly by configure, so you cannot use config.status to rerun them.
Execute the cmds right before creating config.status.
This macro presents the last opportunity to call
AC_SUBST,
AC_DEFINE, or
AC_CONFIG_ITEMS macros.
You may find it convenient to create links whose destinations depend upon
results of tests. One can use
AC_CONFIG_COMMANDS but the
creation of relative symbolic links can be delicate when the package is
built in a directory different from the source directory.
Make
AC_OUTPUTlink each of the existing files source to the corresponding link name dest. Makes a symbolic link if possible, otherwise a hard link if possible, otherwise a copy. The dest and source names should be relative to the top level source or build directory. This macro is one of the instantiating macros; see ‘.’ for dest is invalid: it makes it impossible for ‘config.status’ to guess the links to establish.
One can then run:./config.status host.h object.h
to create the links..
Several tests depend upon a set of header files. Since these headers are not universally available, tests actually have to provide a set of protected includes, such as:
#ifdef TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # ifdef HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif
Unless you know exactly what you are doing, you should avoid using unconditional includes, and check the existence of the headers you include beforehand (see Header Files).
Most generic macros use the following macro to provide the default set of includes:
Expand to include-directives if defined, otherwise to:#include <stdio.h> #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #ifdef HAVE_SYS_STAT_H # include <sys/stat.h> #endif #ifdef STDC_HEADERS # include <stdlib.h> # include <stddef.h> #else # ifdef HAVE_STDLIB_H # include <stdlib.h> # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include <memory.h> # endif # include <string.h> #endif #ifdef HAVE_STRINGS_H # include <strings.h> #endif #ifdef HAVE_INTTYPES_H # include <inttypes.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif
If the default includes are used, then check for the presence of these headers and their compatibility, i.e., you don't need to run
AC_HEADER_STDC, nor check for stdlib.h etc.
These headers are checked for in the same order as they are included. For instance, on some systems string.h and strings.h both exist, but conflict. Then
HAVE_STRING_His defined, not
HAVE_STRINGS.
Check for
gawk,
mawk,
nawk, and
awk, in that order, and set output variable
AWKto the first one that is found. It tries
gawkfirst because that is reported to be the best implementation. The result can be overridden by setting the variable
AWKor the cache variable
ac_cv_prog_AWK.
Using this macro is sufficient to avoid the pitfalls of traditional awk (see Limitations of Usual Tools).
Look for the best available
grepor
ggrepthat accepts the longest input lines possible, and that supports multiple -e options. Set the output variable
GREPto whatever is chosen. See Limitations of Usual Tools, for more information about portability problems with the grep command family. The result can be overridden by setting the
GREPvariable and is cached in the
ac_cv_path_GREPvariable.
Check whether
$GREP -Eworks, or else look for the best available
egrepor
gegrepthat accepts the longest input lines possible. Set the output variable
EGREPto whatever is chosen. The result can be overridden by setting the
EGREPvariable and is cached in the
ac_cv_path_EGREPvariable.
Check whether
$GREP -Fworks, or else look for the best available
fgrepor
gfgrepthat accepts the longest input lines possible. Set the output variable
FGREPto whatever is chosen. The result can be overridden by setting the
FGREPvariable and is cached in the
ac_cv_path_FGREPvariable.
Set output variable
INSTALLto the name of a BSD-compatible install program, if one is found in the current PATH. Otherwise, set
INSTALLto ‘dir/install-sh -c’, checking the directories specified to
AC_CONFIG_AUX_DIR(or its default directories) to determine dir (see Output). Also set the variables
INSTALL_PROGRAMand
INSTALL_SCRIPTto ‘${INSTALL}’ and
INSTALL_DATAto ‘${INSTALL} -m 644’.
‘@INSTALL@’ is special, as its value may vary for different configuration files.. Further, this macro requires install to be able to install multiple files into a target directory in a single invocation.
Autoconf comes with a copy of install-sh that you can use. If you use
AC_PROG_INSTALL, you must include either install-sh or install.sh in your distribution; otherwise configure produces.
The result of the test can be overridden by setting the variable
INSTALLor the cache variable
ac_cv_path_install.
Set output variable
MKDIR_Pto a program that ensures that for each argument, a directory named by this argument exists, creating it and its parent directories if needed, and without race conditions when two instances of the program attempt to make the same directory at nearly the same time.
This macro uses the ‘mkdir -p’ command if possible. Otherwise, it falls back on invoking install-sh with the -d option, so your package should contain install-sh as described under
AC_PROG_INSTALL. An install-sh file that predates Autoconf 2.60 or Automake 1.10 is vulnerable to race conditions, so if you want to support parallel installs from different packages into the same directory you need to make sure you have an up-to-date install-sh. In particular, be careful about using ‘autoreconf -if’ if your Automake predates Automake 1.10.
This macro is related to the
AS_MKDIR_Pmacro (see Programming in M4sh), but it sets an output variable intended for use in other files, whereas
AS_MKDIR_Pis intended for use in scripts like configure. Also,
AS_MKDIR_Pdoes not accept options, but
MKDIR_Psupports the -m option, e.g., a makefile might invoke
$(MKDIR_P) -m 0 dirto create an inaccessible directory, and conversely a makefile should use
$(MKDIR_P) -- $(FOO)if FOO might yield a value that begins with ‘-’. Finally,
AS_MKDIR_Pdoes not check for race condition vulnerability, whereas
AC_PROG_MKDIR_Pdoes.
‘@MKDIR_P@’ is special, as its value may vary for different configuration files.
The result of the test can be overridden by setting the variable
MKDIR_Por the cache variable
ac_cv_path_mkdir.
If
flexis found, set output variable
LEXto ‘flex’ and
LEXLIBto -lfl, if that library is in a standard place. Otherwise set
LEXto ‘lex’ and
LEXLIBto -ll, if found. If neither variant is available, set
LEXto ‘:’; for packages that ship the generated file.yy.c alongside the source file.l, this default allows users without a lexer generator to still build the package even if the timestamp for file.l is inadvertently changed.
Define
YYTEXT_POINTERif
yytextdefaults to ‘char *’ instead of to ‘char []’. Also set output variable
LEX_OUTPUT_ROOTto the base of the file name that the lexer generates; usually lex.yy, but sometimes something else. These results vary according to whether
lexor
flexis being used.
You are encouraged to use Flex in your sources, since it is both more pleasant to use than plain Lex and the C source it produces is portable. In order to ensure portability, however, you must either provide a function
yywrapor, if you don't use it (e.g., your scanner has no ‘#include’-like feature), simply include a ‘ "x$LEX" != xflex; then LEX="$SHELL $missing_dir/missing flex" AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy]) AC_SUBST([LEXLIB], ['']) fi
The shell script missing can be found in the Automake distribution.
Remember that the user may have supplied an alternate location in LEX, so if Flex is required, it is better to check that the user provided something sufficient by parsing the output of ‘$LEX --version’ than by simply relying on
test "x$LEX" = xflex.
To ensure backward compatibility, Automake's
AM_PROG_LEXinvokes (indirectly) this macro twice, which causes an annoying but benign “
AC_PROG_LEXinvoked multiple times” warning. Future versions of Automake will fix this issue; meanwhile, just ignore this message.
As part of running the test, this macro may delete any file in the configuration directory named lex.yy.c or lexyy.c.
The result of this test can be influenced by setting the variable
LEXor the cache variable
ac_cv_prog_LEX.
If ‘ln -s’ works on the current file system (the operating system and file system support symbolic links), set the output variable
LN_Sto ‘ln -s’; otherwise, if ‘ln’ works, set
LN_Sto ‘ln’, and otherwise set it to ‘cp -pR’.
If you make a link in a directory other than the current directory, its meaning depends on whether ‘ln’ or ‘ln -s’ is used. To safely create links using ‘$(LN_S)’, either find out which form is used and adjust the arguments, or always invoke
lnin the directory where the link is to be created.
In other words, it does not work to do:$(LN_S) foo /x/bar
Instead, do:(cd /x && $(LN_S) foo bar)
Set output variable
RANLIBto ‘ranlib’ if
ranlibis found, and otherwise to ‘:’ (do nothing).
Set output variable
SEDto a Sed implementation that conforms to Posix and does not have arbitrary length limits. Report an error if no acceptable Sed is found. See Limitations of Usual Tools, for more information about portability problems with Sed.
The result of this test can be overridden by setting the
SEDvariable and is cached in the
ac_cv_path_SEDvariable.
If
bisonis found, set output variable
YACCto ‘bison -y’. Otherwise, if
byaccis found, set
YACCto ‘byacc’. Otherwise set
YACCto ‘yacc’. The result of this test can be influenced by setting the variable
YACCor the cache variable
ac_cv_prog_YACC.
These macros are used to find programs not covered by the “particular” test macros. If you need to check the behavior of a program as well as find out whether it is present, you have to write your own test for it (see$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
You are strongly encouraged to declare the variable passed to
AC_CHECK_PROG etc. as precious. See Setting Output Variables,
AC_ARG_VAR, for more details.
Check whether program prog-to-check-for exists in. The result of this test can be overridden by setting the variable variable or the cache variable
ac_cv_prog_variable.
Check for each program in the blank-separated list progs-to-check-for existing in the path. If one. The result of this test can be overridden by setting the variable variable or the cache variable
ac_cv_prog_variable.
Like
AC_CHECK_PROG, but first looks for prog-to-check-for with a prefix of the target type as determined by
AC_CANONICAL_TARGET, followed by a dash (see Canonicalizing). If the tool cannot be found with a prefix, and if the build and target types are equal, then it is also searched for without a prefix.
As noted in Specifying Target Triplets, the target is rarely specified, because most of the time it is the same as the host: it is the type of system for which any compiler tool in the package produces code. What this macro looks for is, for example, a tool (assembler, linker, etc.) that the compiler driver (gcc for the GNU C Compiler) uses to produce objects, archives or executables.
Like
AC_CHECK_PROG, but first looks for prog-to-check-for with a prefix of the host type as specified by --host, followed by a dash. For example, if the user runs ‘configure --build=x86_64-gnu --host=i386-gnu’, then this call:AC_CHECK_TOOL([RANLIB], [ranlib], [:])
sets
RANLIBto i386-gnu-ranlib if that program exists in path, or otherwise to ‘ranlib’ if that program exists in path, or to ‘:’ if neither program exists.
When cross-compiling, this macro will issue a warning if no program prefixed with the host type could be found. For more information, see Specifying Target Triplets.
Like
AC_CHECK_TARGET_TOOL, each of the tools in the list progs-to-check-for are checked with a prefix of the target type as determined by
AC_CANONICAL_TARGET, followed by a dash (see Canonicalizing). If none of the tools can be found with a prefix, and if the build and target types are equal,.
Like
AC_CHECK_TOOL, each of the tools in the list progs-to-check-for are checked with a prefix of the host type as determined by
AC_CANONICAL_HOST, followed by a dash (see Canonicalizing)..
When cross-compiling, this macro will issue a warning if no program prefixed with the host type could be found. For more information, see Specifying Target Triplets.
Like
AC_CHECK_PROG, but set variable to the absolute name of prog-to-check-for if found. The result of this test can be overridden by setting the variable variable. A positive result of this test is cached in the
ac_cv_path_variable variable.
Like
AC_CHECK_PROGS, but if any of progs-to-check-for are found, set variable to the absolute name of the program found. The result of this test can be overridden by setting the variable variable. A positive result of this test is cached in the
ac_cv_path_variable variable.
This macro was introduced in Autoconf 2.62. If variable is not empty, then set the cache variable
ac_cv_path_variable to its value. Otherwise, check for each program in the blank-separated list progs-to-check-for existing in path. For each program found, execute feature-test with
ac_path_variable set to the absolute name of the candidate program. If no invocation of feature-test sets the shell variable
ac_cv_path_variable, then action-if-not-found is executed. feature-test will be run even when
ac_cv_path_variable is set, to provide the ability to choose a better candidate found later in path; to accept the current setting and bypass all further checks, feature-test can execute
ac_path_variable
_found=:.
Note that this macro has some subtle differences from
AC_CHECK_PROGS. It is designed to be run inside
AC_CACHE_VAL, therefore, it should have no side effects. In particular, variable is not set to the final value of
ac_cv_path_variable, nor is
AC_SUBSTautomatically run. Also, on failure, any action can be performed, whereas
AC_CHECK_PROGSonly performs variable
=value-if-not-found.
Here is an example, similar to what Autoconf uses in its own configure script. It will search for an implementation of m4 that supports the
indirbuiltin, even if it goes by the name gm4 or is not the first implementation on PATH.AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4], [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4], [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4` test "x$m4out" = x0 \ && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]], [AC_MSG_ERROR([could not find m4 that supports indir])])]) AC_SUBST([M4], [$ac_cv_path_M4])
Like
AC_CHECK_TARGET_TOOL, but set variable to the absolute name of the program if it is found.
Like
AC_CHECK_TOOL, but set variable to the absolute name of the program if it is found.
When cross-compiling, this macro will issue a warning if no program prefixed with the host type could be found. For more information, see Specifying Target Triplets.
You might also need to check for the existence of files. Before using these macros, ask yourself whether a runtime. The result of this test is cached in the
ac_cv_file_file variable, with characters not suitable for a variable name mapped to underscores.
Executes
AC_CHECK_FILEonce for each file listed in files. Additionally, defines ‘HAVE_file’ (see Standard Symbols) for each file found. The results of each test are cached in the
ac_cv_file_file variable, with characters not suitable for a variable name mapped to underscores.
The following macros check for the presence of certain C, C++, Fortran, or always requires additions. A much more complete list is maintained by the Gnulib project (see Gnulib), covering Current Posix Functions, Legacy Functions, and Glibc Functions. Please help us keep the gnulib list as complete as possible.
exit
exitreturned
int. This is because
exitpredates
void, and there was a long tradition of it returning
int.
On current hosts, the problem more likely is that
exit is not
declared, due to C++ problems of some sort or another. For this reason
we suggest that test programs not invoke
exit, but return from
main instead.
free
free (NULL)does nothing, but some old systems don't support this (e.g., NextStep).
isinf
isnan
isinfand
isnanare macros. On some systems just macros are available (e.g., HP-UX and Solaris 10), on some systems both macros and functions (e.g., glibc 2.3.2), and on some systems only functions (e.g., IRIX 6 and Solaris 9). In some cases these functions are declared in nonstandard headers like
<sunmath.h>and defined in non-default libraries like -lm or -lsunmath.
The C99
isinf and
isnan macros work correctly with
long double arguments, but pre-C99 systems that use functions
typically assume
double arguments. On such a system,
isinf incorrectly returns true for a finite
long double
argument that is outside the range of
double.
The best workaround for these issues is to use gnulib modules
isinf and
isnan (see Gnulib). But a lighter weight
solution involves code like the following.
#include <math.h> #ifndef isnan # define isnan(x) \ (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ : sizeof (x) == sizeof (double) ? isnan_d (x) \ : isnan_f (x)) static inline int isnan_f (float x) { return x != x; } static inline int isnan_d (double x) { return x != x; } static inline int isnan_ld (long double x) { return x != x; } #endif #ifndef isinf # define isinf(x) \ (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ : sizeof (x) == sizeof (double) ? isinf_d (x) \ : isinf_f (x)) static inline int isinf_f (float x) { return !isnan (x) && isnan (x - x); } static inline int isinf_d (double x) { return !isnan (x) && isnan (x - x); } static inline int isinf_ld (long double x) { return !isnan (x) && isnan (x - x); } #endif
Use
AC_C_INLINE (see C Compiler) so that this code works on
compilers that lack the
inline keyword. Some optimizing
compilers mishandle these definitions, but systems with that bug
typically have many other floating point corner-case compliance problems
anyway, so it's probably not worth worrying about.
malloc
malloc (0)is implementation dependent. It can return either
NULLor a new non-null pointer. The latter is more common (e.g., the GNU C Library) but is by no means universal.
AC_FUNC_MALLOCcan be used to insist on non-
NULL(see Particular Functions).
putenv
setenvto
putenv; among other things,
putenvis not required of all Posix implementations, but
setenvis.
Posix specifies that
putenv puts the given string directly in
environ, but some systems make a copy of it instead (e.g.,
glibc 2.0, or BSD). And when a copy is made,
unsetenv might
not free it, causing a memory leak (e.g., FreeBSD 4).
On some systems
putenv ("FOO") removes ‘FOO’ from the
environment, but this is not standard usage and it dumps core
on some systems (e.g., AIX).
On MinGW, a call
putenv ("FOO=") removes ‘FOO’ from the
environment, rather than inserting it with an empty value.
realloc
realloc (NULL, size)is equivalent to
malloc (size), but some old systems don't support this (e.g., NextStep).
signalhandler
signaltakes a handler function with a return type of
void, but some old systems required
intinstead. Any actual
intvalue returned is not used; this is only a difference in the function prototype demanded.
All systems we know of in current use return
void. The
int was to support K&R C, where of course
void is not
available. The obsolete macro
AC_TYPE_SIGNAL
(see AC_TYPE_SIGNAL) can be used to establish the correct type in
all cases.
In most cases, it is more robust to use
sigaction when it is
available, rather than
signal.
snprintf
snprintfand
vsnprintftruncate the output and return the number of bytes that ought to have been produced. Some older systems return the truncated length (e.g., GNU C Library 2.0.x or IRIX 6.5), some a negative value (e.g., earlier GNU C Library versions), and some the buffer length without truncation (e.g., 32-bit Solaris 7). Also, some buggy older systems ignore the length and overrun the buffer (e.g., 64-bit Solaris 7).
sprintf
sprintfand
vsprintfreturn the number of bytes written. On some ancient systems (SunOS 4 for instance) they return the buffer pointer instead, but these no longer need to be worried about.
sscanf
sscanfrequires that its input string be writable (though it doesn't actually change it). This can be a problem when using gcc since it normally puts constant strings in read-only memory (see Incompatibilities of GCC). Apparently in some cases even having format strings read-only can be a problem.
strerror_r
strerror_rreturns an
int, but many systems (e.g., GNU C Library version 2.2.4) provide a different version returning a
char *.
AC_FUNC_STRERROR_Rcan detect which is in use (see Particular Functions).
strnlen
strnlen ("foobar", 0) = 0 strnlen ("foobar", 1) = 3 strnlen ("foobar", 2) = 2 strnlen ("foobar", 3) = 1 strnlen ("foobar", 4) = 0 strnlen ("foobar", 5) = 6 strnlen ("foobar", 6) = 6 strnlen ("foobar", 7) = 6 strnlen ("foobar", 8) = 6 strnlen ("foobar", 9) = 6
sysconf
_SC_PAGESIZEis standard, but some older systems (e.g., HP-UX 9) have
_SC_PAGE_SIZEinstead. This can be tested with
#ifdef.
unlink
unlinkcauses the given file to be removed only after there are no more open file handles for it. Some non-Posix hosts have trouble with this requirement, though, and some DOS variants even corrupt the file system.
unsetenv
unsetenvis not available, but a variable ‘FOO’ can be removed with a call
putenv ("FOO="), as described under
putenvabove.
va_copy
va_copyfor copying
va_listvariables. It may be available in older environments too, though possibly as
__va_copy(e.g., gcc in strict pre-C99 mode). These can be tested with
#ifdef. A fallback to
memcpy (&dst, &src, sizeof (va_list))gives maximum portability.
va_list
va_listis not necessarily just a pointer. It can be a
struct(e.g., gcc on Alpha), which means
NULLis not portable. Or it can be an array (e.g., gcc in some PowerPC configurations), which means as a function parameter it can be effectively call-by-reference and library routines might modify the value back in the caller (e.g.,
vsnprintfin the GNU C Library 2.1).
>>
>>right shift of a signed type replicates the high bit, giving a so-called “arithmetic” shift. But care should be taken since Standard C doesn't require that behavior. On those few processors without a native arithmetic shift (for instance Cray vector systems) zero bits may be shifted in, the same as a shift of an unsigned type.
/ section documents some collected knowledge about common headers, and the problems they cause. By definition, this list always requires additions. A much more complete list is maintained by the Gnulib project (see Gnulib), covering Posix Headers and Glibc Headers. Please help us keep the gnulib list as complete as possible.
LLONG_MIN,
LLONG_MAX, and
ULLONG_MAX, but many almost-C99 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not define them.
AC_CHECK_HEADERS([sys/socket.h]) AC_CHECK_HEADERS([net/if.h], [], [], [#include <stdio.h> #ifdef STDC_HEADERS # include <stdlib.h> # include <stddef.h> #else # ifdef HAVE_STDLIB_H # include <stdlib.h> # endif #endif #ifdef HAVE_SYS_SOCKET_H # include <sys/socket.h> #endif ])
AC_CHECK_HEADERS([sys/socket.h]) AC_CHECK_HEADERS([netinet/if_ether.h], [], [], [#include <stdio.h> #ifdef STDC_HEADERS # include <stdlib.h> # include <stddef.h> #else # ifdef HAVE_STDLIB_H # include <stdlib.h> # endif #endif #ifdef HAVE_SYS_SOCKET_H # include <sys/socket.h> #endif ])
AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [], [[#include <X11/Xlib.h> ]])
These macros check for particular system header files—whether they exist, and in some cases whether they declare certain symbols.
Check whether stdbool.h exists and conforms to C99, and cache the result in the
ac_cv_header_stdbool_hvariable. If the type
_Boolis defined, define
HAVE__BOOLto 1.
This macro is intended for use by Gnulib (see Gnulib) and other packages that supply a substitute stdbool.h on platforms lacking a conforming one. The
AC_HEADER_STDBOOLmacro is better for code that explicitly checks for stdbool.h.
Check whether to enable assertions in the style of assert.h. Assertions are enabled by default, but the user can override this by invoking configure with the --disable-assert option.
Check for the following header files. For the first one that is found and defines ‘DIR’, define the listed C preprocessor macro:
The directory-library declarations in your source code should look something like the following:#include <sys/types.h> #ifdef HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen ((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) ((dirent)->d_namlen) # ifdef HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # ifdef HAVE_SYS_DIR_H # include <sys/dir.h> # endif # ifdef HAVE_NDIR_H # include <ndir.h> # endif #endif
Using.
This macro is obsolescent, as all current systems with directory libraries have
<dirent.h>. New programs need not use this macro.
Also see
AC_STRUCT_DIRENT_D_INOand
AC_STRUCT_DIRENT_D_TYPE(see Particular Structures).
If sys/types.h does not define
major,
minor, and
makedev, but sys/mkdev.h does, define
MAJOR_IN_MKDEV; otherwise, if sys/sysmacros.h does, define
MAJOR_IN_SYSMACROS.
Checks for header resolv.h, checking for prerequisites first. To properly use resolv.h, your code should contain something like the following:#ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> /* inet_ functions / structs */ #endif #ifdef HAVE_ARPA_NAMESER_H # include <arpa/nameser.h> /* DNS HEADER struct */ #endif #ifdef HAVE_NETDB_H # include <netdb.h> #endif #include <resolv.h>
If the macros
S_ISDIR,
S_ISREG, etc. defined in sys/stat.h do not work properly (returning false positives), define
STAT_MACROS_BROKEN. This is the case on Tektronix UTekV, Amdahl UTS and Motorola System V/88.
This macro is obsolescent, as no current systems have the bug. New programs need not use this macro.
If stdbool.h exists and conforms to C99, define
HAVE_STDBOOL_Hto 1; if the type
_Boolis defined, define
HAVE__BOOLto 1. To fulfill the C99 requirements, your program could contain the following code:#ifdef HAVE_STDBOOL_H # include <stdbool.h> #else # ifndef HAVE__BOOL # ifdef __cplusplus typedef bool _Bool; # else # define _Bool signed char # endif # endif # define bool _Bool # define false 0 # define true 1 # define __bool_true_false_are_defined 1 #endif
Alternatively you can use the ‘stdbool’ package of Gnulib (see Gnulib). It simplifies your code so that it can say just
#include <stdbool.h>, and it adds support for less-common platforms.
This macro caches its result in the
ac_cv_header_stdbool_hvariable.
This macro differs from
AC_CHECK_HEADER_STDBOOLonly in that it defines
HAVE_STDBOOL_Hwhereas
AC_CHECK_HEADER_STDBOOLdoes not.
Define
STDC_HEADERSif the system has C header files conforming to ANSI C89 (ISO C90). Specifically, this macro checks for stdlib.h, stdarg.h, string.h, and float.h; if the system has those, it probably has the rest of the C89 the C standard requires.
If you use this macro, your code can refer to
STDC_HEADERSto determine whether the system has conforming header files (and probably C library functions).
This macro caches its result in the
ac_cv_header_stdcvariable.
This macro is obsolescent, as current systems have conforming header files. New programs need not use this macro.
Nowadays string.h is part of the C standard and declares functions like
strcpy, and strings.h is standardized by Posix and declares BSD functions like
bcopy; but historically, string functions were a major sticking point in this area. If you still want to worry about portability to ancient systems without standard headers, there is so much variation that it is probably easier to declare the functions you use than to figure out exactly what the system header files declare. Some ancient systems contained a mix of functions from the C standard and from BSD; some were mostly standard but lacked ‘memmove’; some defined the BSD functions as macros in string.h or strings.h; some had only the BSD functions but string.h; some declared the memory functions in memory.h, some in string.h; etc. It is probably sufficient to check for one string function and one memory function; if the library had the standard versions of those then it probably had most of the others. If you put the following in configure.ac:# This example is obsolescent. # Nowadays you can omit these macro calls. AC_HEADER_STDC AC_CHECK_FUNCS([strchr memcpy])
then, in your code, you can use declarations like this:/* This example is obsolescent. Nowadays you can just #include <string.h>. */ #ifdef STDC_HEADERS # include <string.h> #else # ifndef HAVE_STRCHR # define strchr index # define strrchr rindex # endif char *strchr (), *strrchr (); # ifndef HAVE_MEMCPY # define memcpy(d, s, n) bcopy ((s), (d), (n)) # define memmove(d, s, n) bcopy ((s), (d), (n)) # endif #endif
If you use a function like
memchr,
memset,
strtok, or
strspn, which have no BSD equivalent, then macros don't suffice to port to ancient hosts; you must provide an implementation of each function. An easy way to incorporate your implementations only when needed (since the ones in system C libraries may be hand optimized) is to, taking
memchrfor example, put it in memchr.c and use ‘AC_REPLACE_FUNCS([memchr])’.
If sys/wait.h exists and is compatible with Posix, define
HAVE_SYS_WAIT_H. Incompatibility can occur if sys/wait.h does not exist, or if it uses the old BSD
union waitinstead of
intto store a status value. If sys/wait.h is not Posix compatible, then instead of including it, define the Posix macros with their usual interpretations. Here is an example:#include <sys/types.h> #ifdef HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif
This macro caches its result in the
ac_cv_header_sys_wait_hvariable.
This macro is obsolescent, as current systems are compatible with Posix. New programs need not use this macro.
_POSIX_VERSION is defined when unistd.h is included on
Posix systems. If there is no unistd.h, it is definitely
not a Posix system. However, some non-Posix systems do
have unistd.h.
The way to check whether the system supports Posix is:
#ifdef HAVE_UNISTD_H # include <sys/types.h> # include <unistd.h> #endif #ifdef _POSIX_VERSION /* Code for Posix systems. */ #endif
If a program may include both time.h and sys/time.h, define
TIME_WITH_SYS_TIME. On some ancient systems, sys/time.h included time.h, but time.h was not protected against multiple inclusion, so programs could not explicitly include both files. This macro is useful in programs that use, for example,
struct timevalas well as
struct tm. It is best used in conjunction with
HAVE_SYS_TIME_H, which can be checked for using
AC_CHECK_HEADERS([sys/time.h]).#ifdef TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # ifdef HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif
This macro caches its result in the
ac_cv_header_timevariable.
This macro is obsolescent, as current systems can include both files when they exist. New programs need not use this macro.
If the use of
TIOCGWINSZrequires <sys/ioctl.h>, then define
GWINSZ_IN_SYS_IOCTL. Otherwise
TIOCGWINSZcan be found in <termios.h>.
Use:#ifdef HAVE_TERMIOS_H # include <termios.h> #endif #ifdef Writing Tests).
If the system header file header-file is compilable, execute shell commands action-if-found, otherwise execute action-if-not-found. If you just want to define a symbol if the header file is available, consider using
AC_CHECK_HEADERSinstead.
includes is decoded to determine the appropriate include directives. If omitted or empty, configure will check for both header existence (with the preprocessor) and usability (with the compiler), using
AC_INCLUDES_DEFAULTfor the compile test. If there is a discrepancy between the results, a warning is issued to the user, and the compiler results are favored (see Present But Cannot Be Compiled). In general, favoring the compiler results means that a header will be treated as not found even though the file exists, because you did not provide enough prerequisites.
Providing a non-empty includes argument allows the code to provide any prerequisites prior to including the header under test; it is common to use the argument
AC_INCLUDES_DEFAULT(see Default Includes). With an explicit fourth argument, no preprocessor test is needed. As a special case, an includes of exactly ‘-’ triggers the older preprocessor check, which merely determines existence of the file in the preprocessor search path; this should only be used as a last resort (it is safer to determine the actual prerequisites and perform a compiler check, or else use
AC_PREPROC_IFELSEto make it obvious that only a preprocessor check is desired).
This macro caches its result in the
ac_cv_header_header-file variable, with characters not suitable for a variable name mapped to underscores.
For each given system header file header-file in the blank-separated argument list that exists, define
HAVE_header-file (in all capitals). If action-if-found is given, it is additional shell code to execute when one of the header files is found. You can give it a value of ‘break’ to break out of the loop on the first match. If action-if-not-found is given, it is executed when one of the header files is not found.
includes is interpreted as in
AC_CHECK_HEADER, in order to choose the set of preprocessor directives supplied before the header under test.
This macro caches its result in the
ac_cv_header_header-file variable, with characters not suitable for a variable name mapped to underscores. (see Present But Cannot Be Compiled). If you need to check whether a header is preprocessable,
you can use
AC_PREPROC_IFELSE (see Running the Preprocessor).
Actually requiring a header to compile improves the robustness of the test, but it also requires that you make sure that headers that must be included before the header-file be part of the includes, (see Default Includes). If looking for bar.h, which requires that foo.h be included before if it exists, we suggest the following scheme:
AC_CHECK_HEADERS([foo.h]) AC_CHECK_HEADERS([bar.h], [], [], [#ifdef HAVE_FOO_H # include <foo.h> #endif ])
The following variant generates smaller, faster configure
files if you do not need the full power of
AC_CHECK_HEADERS.
For each given system header file header-file in the blank-separated argument list that exists, define
HAVE_header-file (in all capitals). This is a once-only variant of
AC_CHECK_HEADERS. It generates the checking code at most once, so that configure is smaller and faster; but the checks cannot be conditionalized and are always done once, early during the configure run. Thus, this macro is only safe for checking headers that do not have prerequisites beyond what
AC_INCLUDES_DEFAULTprovides.).
There are no specific macros for declarations.
These macros are used to find declarations not covered by the “particular” test macros.
If symbol (a function, variable, or constant) is not declared in includes and a declaration is needed, run the shell commands action-if-not-found, otherwise action-if-found. includes is a series of include directives, defaulting to
AC_INCLUDES_DEFAULT(see Default Includes), which are used prior to the declaration under test.
This macro actually tests whether symbol is defined as a macro or can be used as an r-value, not whether it is really declared, because it is much safer to avoid introducing extra declarations when they are not needed. In order to facilitate use of C++ and overloaded function declarations, it is possible to specify function argument types in parentheses for types which can be zero-initialized:AC_CHECK_DECL([basename(char *)])
This macro caches its result in the
ac_cv_have_decl_symbol variable, with characters not suitable for a variable name mapped to underscores.
For each of the symbols (comma-separated list with optional function argument types for C++ overloads), define
HAVE_DECL_symbol (in all capitals) to ‘1’ if symbol is declared, otherwise to ‘0’. If action-if-not-found is given, it is additional shell code to execute when one of the function declarations is needed, otherwise action-if-found is executed.
includes is a series of include directives, defaulting to
AC_INCLUDES_DEFAULT(see Default Includes), which are used prior to the declarations under test.
This macro uses an M4 list as first argument:AC_CHECK_DECLS([strdup]) AC_CHECK_DECLS([strlen]) AC_CHECK_DECLS([malloc, realloc, calloc, free]) AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]]) AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
Unlike the other ‘AC_CHECK_*S’ macros, when a symbol is not declared,
HAVE_DECL_symbol is defined to ‘0’ instead of leaving
HAVE_DECL_symbol undeclared. When you are sure that the check was performed, use
HAVE_DECL_symbol in
#if: void *malloc (size_t *s); #endif
You fall into the second category only in extreme situations: either your files may be used without being configured, or they are used during the configuration. In most cases the traditional approach is enough.
This macro caches its results in
ac_cv_have_decl_symbol variables, with characters not suitable for a variable name mapped to underscores.
For each of the symbols (comma-separated list), define
HAVE_DECL_symbol (in all capitals) to ‘1’ if symbol is declared in the default include files, otherwise to ‘0’. This is a once-only variant of
AC_CHECK_DECLS. It generates the checking code at most once, so that configure is smaller and faster; but the checks cannot be conditionalized and are always done once, early during the configure run.
The following macros check for the presence of certain members in C
structures. If there is no macro specifically defined to check for a
member you need, then you can use the general structure-member macros
(see Generic Structures) or, for more complex tests, you may use
AC_COMPILE_IFELSE (see Running the Compiler)..
Figure out how to get the current timezone. If
struct tmhas a
tm_zonemember, define
HAVE_STRUCT_TM_TM_ZONE(and the obsoleted
HAVE_TM_ZONE). Otherwise, if the external array
tznameis found, define
HAVE_TZNAME; if it is declared, define
HAVE_DECL_TZNAME.
These macros are used to find structure members not covered by the “particular” test macros.
Check whether member is a member of the aggregate aggregate. If no includes are specified, the default includes are used (see Default Includes).AC_CHECK_MEMBER([struct passwd.pw_gecos], [], [AC_MSG_ERROR([we need `passwd.pw_gecos'])], [[#include <pwd.h>]])
You can use this macro for submembers:AC_CHECK_MEMBER(struct top.middle.bot)
This macro caches its result in the
ac_cv_member_aggregate
_member variable, with characters not suitable for a variable name mapped to underscores.
Check for the existence of each ‘aggregate.member’ of members using the previous macro. When member belongs to aggregate, define
HAVE_aggregate
_member (in all capitals, with spaces and dots replaced by underscores). If action-if-found is given, it is executed for each of the found members. If action-if-not-found is given, it is executed for each of the members that could not be found.
includes is a series of include directives, defaulting to
AC_INCLUDES_DEFAULT(see Default Includes), which are used prior to the members under test., stdint.h, inttypes.h and others, if they exist.
The Gnulib
stdint module is an alternate way to define many of
these symbols; it is useful if you prefer your code to assume a
C99-or-better environment. See Gnulib.
Define
GETGROUPS_Tto be whichever of
gid_tor
intis the base type of the array argument to
getgroups.
This macro caches the base type in the
ac_cv_type_getgroupsvariable.
If stdint.h or inttypes.h does not define the type
int8_t, define
int8_tto a signed integer type that is exactly 8 bits wide and that uses two's complement representation, if such a type exists. If you are worried about porting to hosts that lack such a type, you can use the results of this macro in C89-or-later code as follows:#if HAVE_STDINT_H # include <stdint.h> #endif #if defined INT8_MAX || defined int8_t code using int8_t #else complicated alternative using >8-bit 'signed char' #endif
This macro caches the type in the
ac_cv_c_int8_tvariable.
If stdint.h or inttypes.h defines the type
intmax_t, define
HAVE_INTMAX_T. Otherwise, define
intmax_tto the widest signed integer type.
If stdint.h or inttypes.h defines the type
intptr_t, define
HAVE_INTPTR_T. Otherwise, define
intptr_tto a signed integer type wide enough to hold a pointer, if such a type exists.
If the C compiler supports a working
long doubletype, define
HAVE_LONG_DOUBLE. The
long doubletype might have the same range and precision as
double.
This macro caches its result in the
ac_cv_type_long_doublevariable.
This macro is obsolescent, as current C compilers support
long double. New programs need not use this macro.
If the C compiler supports a working
long doubletype with more range or precision than the
doubletype, define
HAVE_LONG_DOUBLE_WIDER.
This macro caches its result in the
ac_cv_type_long_double_widervariable.
If the C compiler supports a working
long long inttype, define
HAVE_LONG_LONG_INT. However, this test does not test
long long intvalues in preprocessor
#ifexpressions, because too many compilers mishandle such expressions. See Preprocessor Arithmetic.
This macro caches its result in the
ac_cv_type_long_long_intvariable.
Define
HAVE_MBSTATE_Tif
<wchar.h>declares the
mbstate_ttype. Also, define
mbstate_tto be a type if
<wchar.h>does not declare it.
This macro caches its result in the
ac_cv_type_mbstate_tvariable.
Define
mode_tto a suitable type, if standard headers do not define it.
This macro caches its result in the
ac_cv_type_mode_tvariable.
Define
off_tto a suitable type, if standard headers do not define it.
This macro caches its result in the
ac_cv_type_off_tvariable.
Define
pid_tto a suitable type, if standard headers do not define it.
This macro caches its result in the
ac_cv_type_pid_tvariable.
Define
size_tto a suitable type, if standard headers do not define it.
This macro caches its result in the
ac_cv_type_size_tvariable.
Define
ssize_tto a suitable type, if standard headers do not define it.
This macro caches its result in the
ac_cv_type_ssize_tvariable.
Define
uid_tand
gid_tto suitable types, if standard headers do not define them.
This macro caches its result in the
ac_cv_type_uid_tvariable.
If stdint.h or inttypes.h does not define the type
uint8_t, define
uint8_tto an unsigned integer type that is exactly 8 bits wide, if such a type exists. This is like
AC_TYPE_INT8_T, except for unsigned integers.
If stdint.h or inttypes.h defines the type
uintmax_t, define
HAVE_UINTMAX_T. Otherwise, define
uintmax_tto the widest unsigned integer type.
If stdint.h or inttypes.h defines the type
uintptr_t, define
HAVE_UINTPTR_T. Otherwise, define
uintptr_tto an unsigned integer type wide enough to hold a pointer, if such a type exists.
If the C compiler supports a working
unsigned long long inttype, define
HAVE_UNSIGNED_LONG_LONG_INT. However, this test does not test
unsigned long long intvalues in preprocessor
#ifexpressions, because too many compilers mishandle such expressions. See Preprocessor Arithmetic.
This macro caches its result in the
ac_cv_type_unsigned_long_long_intvariable.
These macros are used to check for types not covered by the “particular” test macros.
Check whether type is defined. It may be a compiler builtin type or defined by the includes. includes is a series of include directives, defaulting to
AC_INCLUDES_DEFAULT(see Default Includes), which are used prior to the type under test.
In C, type must be a type-name, so that the expression ‘sizeof (type)’ is valid (but ‘sizeof ((type))’ is not). The same test is applied when compiling for C++, which means that in C++ type should be a type-id and should not be an anonymous ‘struct’ or ‘union’.
This macro caches its result in the
ac_cv_type_type variable, with ‘*’ mapped to ‘p’ and other characters not suitable for a variable name mapped to underscores.
For each type of the types that is defined, define
HAVE_type (in all capitals). Each type must follow the rules of
AC_CHECK_TYPE. If no includes are specified, the default includes are used (see int, uintmax_t]) AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
Autoconf, up to 2.13, used to provide to another version of
AC_CHECK_TYPE, broken by design. In order to keep backward
compatibility, a simple heuristic, quite safe but not totally, is
implemented. In case of doubt, read the documentation of the former
AC_CHECK_TYPE, see Obsolete Macros.
All the tests for compilers (
AC_PROG_CC,
AC_PROG_CXX,
AC_PROG_F77) define the output variable
EXEEXT based on
the output of the compiler, typically to the empty string if
Posix and ‘.exe’ if a DOS variant.
They also define the output variable
OBJEXT based on the
output of the compiler, after .c files have been excluded, typically
to ‘o’ if Posix, ‘obj’ if a DOS variant.
If the compiler being used does not produce executables, the tests fail. If the executables can't be run, and cross-compilation is not enabled, they fail too. See Manual Configuration, for more on support for cross compiling.
Some.
Define
SIZEOF_type-or-expr (see Standard Symbols) to be the size in bytes of type-or-expr, which may be either a type or an expression returning a value that has a size. If the expression ‘sizeof (type-or-expr)’ is invalid, the result is 0. includes is a series of include directives, defaulting to
AC_INCLUDES_DEFAULT(see Default Includes), which are used prior to the expression under test.
This macro now works even when cross-compiling. The unused argument was used when cross-compiling.
For example, the callAC_CHECK_SIZEOF([int *])
defines
SIZEOF_INT_Pto be 8 on DEC Alpha AXP systems.
This macro caches its result in the
ac_cv_sizeof_type-or-expr variable, with ‘*’ mapped to ‘p’ and other characters not suitable for a variable name mapped to underscores.
Define
ALIGNOF_type (see Standard Symbols) to be the alignment in bytes of type. ‘type y;’ must be valid as a structure member declaration. If ‘type’ is unknown, the result is 0. If no includes are specified, the default includes are used (see Default Includes).
This macro caches its result in the
ac_cv_alignof_type-or-expr variable, with ‘*’ mapped to ‘p’ and other characters not suitable for a variable name mapped to underscores.
Store into the shell variable var the value of the integer expression. The value should fit in an initializer in a C variable of type
signed long. To support cross compilation (in which case, the macro only works on hosts that use twos-complement arithmetic), it should be possible to evaluate the expression at compile-time. If no includes are specified, the default includes are used (see Default Includes).
Execute action-if-fails if the value cannot be determined correctly.
Normally Autoconf ignores warnings generated by the compiler, linker, and preprocessor. If this macro is used, warnings count as fatal errors for the current language. This macro is useful when the results of configuration are used where warnings are unacceptable; for instance, if parts of a program are built with the GCC -Werror option. If the whole program is built using -Werror it is often simpler to put -Werror in the compiler flags (
CFLAGS, etc.).
OpenMP specifies extensions of C, C++, and Fortran that simplify optimization of shared memory parallelism, which is a common problem on multicore CPUs.
If the current language is C, the macro
AC_OPENMPsets the variable
OPENMP_CFLAGSto the C compiler flags needed for supporting OpenMP.
OPENMP_CFLAGSis set to empty if the compiler already supports OpenMP, if it has no way to activate OpenMP support, or if the user rejects OpenMP support by invoking ‘configure’ with the ‘--disable-openmp’ option.
OPENMP_CFLAGSneeds to be used when compiling programs, when preprocessing program source, and when linking programs. Therefore you need to add
$(OPENMP_CFLAGS)to the
CFLAGSof C programs that use OpenMP. If you preprocess OpenMP-specific C code, you also need to add
$(OPENMP_CFLAGS)to
CPPFLAGS. The presence of OpenMP support is revealed at compile time by the preprocessor macro
_OPENMP.
Linking a program with
OPENMP_CFLAGStypically adds one more shared library to the program's dependencies, so its use is recommended only on programs that actually require OpenMP.
If the current language is C++,
AC_OPENMPsets the variable
OPENMP_CXXFLAGS, suitably for the C++ compiler. The same remarks hold as for C.
If the current language is Fortran 77 or Fortran,
AC_OPENMPsets the variable
OPENMP_FFLAGSor
OPENMP_FCFLAGS, respectively. Similar remarks as for C hold, except that
CPPFLAGSis not used for Fortran, and no preprocessor macro signals OpenMP support.
For portability, it is best to avoid spaces between ‘#’ and ‘pragma omp’. That is, write ‘#pragma omp’, not ‘# pragma omp’. The Sun WorkShop 6.2 C compiler chokes on the latter.
This macro caches its result in the
ac_cv_prog_c_openmp,
ac_cv_prog_cxx_openmp,
ac_cv_prog_f77_openmp, or
ac_cv_prog_fc_openmpvariable, depending on the current language.
The following macros provide ways to find and exercise a C Compiler. There are a few constructs that ought to be avoided, but do not deserve being checked for, since they can easily be worked around.
#ifdef __STDC__ /\ * A comment with backslash-newlines in it. %{ %} *\ \ / char str[] = "\\ " A string with backslash-newlines in it %{ %} \\ ""; char apostrophe = '\\ \ '\ '; #endif
the compiler incorrectly fails with the diagnostics “Non-terminating
comment at end of file” and “Missing ‘#endif’ at end of file.”
Removing the lines with solitary backslashes solves the problem.
$ cc a.c b.c a.c: b.c:
This can cause problems if you observe the output of the compiler to
detect failures. Invoking ‘cc -c a.c && cc -c b.c && cc -o c a.o
b.o’ solves the issue.
#errorfailing
#error "Unsupported word size"it is more portable to use an invalid directive like
#Unsupported word sizein Autoconf tests. In ordinary source code,
#erroris OK, since installers with inadequate compilers like IRIX can simply examine these compilers' diagnostic output.
#linesupport
#linedirectives whose line numbers are greater than 32767. Nothing in Posix makes this invalid. That is why Autoconf stopped issuing
#linedirectives.
Determine a C compiler to use. If
CCis not already set in the environment, check for
gccand
cc, then for other C compilers. Set output variable
CCto the name of the compiler found.Clike this:AC_PROG_CC([gcc cl cc])
If the C compiler does not handle function prototypes correctly by default, try to add an option to output variable
CCto make it so. This macro tries various options that select standard-conformance modes on various systems.
After calling this macro you can check whether the C compiler has been set to accept ANSI C89 (ISO C90); if not, the shell variable
ac_cv_prog_cc_c89is set to ‘no’. See also
AC_C_PROTOTYPESbelow.
If using the GNU C compiler, set shell variable
GCCto ‘yes’. If output variable
CFLAGSwas not already set, set it to -g -O2 for the GNU C compiler (-O2 on systems where GCC does not accept -g), or -g for other compilers. If your package does not like this default, then it is acceptable to insert the line ‘: ${CFLAGS=""}’ after
AC_INITand before
AC_PROG_CCto select an empty default instead.
Many Autoconf macros use a compiler, and thus call ‘AC_REQUIRE([AC_PROG_CC])’ to ensure that the compiler has been determined before the body of the outermost
AC_DEFUNmacro. Although
AC_PROG_CCis safe to directly expand multiple times, it performs certain checks (such as the proper value of EXEEXT) only on the first invocation. Therefore, care must be used when invoking this macro from within another macro rather than at the top level (see Expanded Before Required).
If the C compiler does not accept the -c and -o options simultaneously, define
NO_MINUS_C_MINUS_O. This macro actually tests both the compiler found by
AC_PROG_CC, and, if different, the first
ccin the path. The test fails if one fails. This macro was created for GNU Make to choose the default C compilation rule.
For the compiler compiler, this macro caches its result in the
ac_cv_prog_cc_compiler
_c_ovariable.
Set output variable
CPPto a command that runs the C preprocessor. If ‘$CC -E’ doesn't work, /lib/cpp is used. It is only portable to run
CPPon files with a .c extension.
Some preprocessors don't indicate missing include files by the error status. For such preprocessors an internal variable is set that causes other macros to check the standard error from the preprocessor and consider the test failed if any warnings have been reported. For most preprocessors, though, warnings do not cause include-file tests to fail unless
AC_PROG_CPP_WERRORis also specified.
This acts like
AC_PROG_CPP, except it treats warnings from the preprocessor as errors even if the preprocessor exit status indicates success. This is useful for avoiding headers that generate mandatory warnings, such as deprecation notices.
The following macros check for C compiler or machine architecture
features. To check for characteristics not listed here, use
AC_COMPILE_IFELSE (see Running the Compiler) or
AC_RUN_IFELSE (see Runtime).
If the C compiler cannot compile ISO Standard C (currently C99), try to add an option to output variable
CCto make it work. If the compiler does not support C99, fall back to supporting ANSI C89 (ISO C90).
After calling this macro you can check whether the C compiler has been set to accept Standard C; if not, the shell variable
ac_cv_prog_cc_stdcis set to ‘no’.
If the C compiler is not in ANSI C89 (ISO C90) mode by default, try to add an option to output variable
CCto make it so. This macro tries various options that select ANSI C89 on some system or another, preferring extended functionality modes over strict conformance modes. It considers the compiler to be in ANSI C89 mode if it handles function prototypes correctly.
After calling this macro you can check whether the C compiler has been set to accept ANSI C89; if not, the shell variable
ac_cv_prog_cc_c89is set to ‘no’.
This macro is called automatically by
AC_PROG_CC.
If the C compiler is not in C99 mode by default, try to add an option to output variable
CCto make it so. This macro tries various options that select C99 on some system or another, preferring extended functionality modes over strict conformance modes. It considers the compiler to be in C99 mode if it handles
_Bool,
inline, signed and unsigned
long long int, mixed code and declarations, named initialization of structs,
restrict,
va_copy, varargs macros, variable declarations in
forloops, and variable length arrays.
After calling this macro you can check whether the C compiler has been set to accept C99; if not, the shell variable
ac_cv_prog_cc_c99is set to ‘no’.
Define ‘HAVE_C_BACKSLASH_A’ to 1 if the C compiler understands ‘\a’.
This macro is obsolescent, as current C compilers understand ‘\a’. New programs need not use this macro.
If words are stored with the most significant byte first (like Motorola and SPARC CPUs), execute action-if-true. If words are stored with the least significant byte first (like Intel and VAX CPUs), execute action-if-false.
This macro runs a test-case if endianness cannot be determined from the system header files. When cross-compiling, the test-case is not run but grep'ed for some magic values. action-if-unknown is executed if the latter case fails to determine the byte sex of the host system.
In some cases a single run of a compiler can generate code for multiple architectures. This can happen, for example, when generating Mac OS X universal binary files, which work on both PowerPC and Intel architectures. In this case, the different variants might be for different architectures whose endiannesses differ. If configure detects this, it executes action-if-universal instead of action-if-unknown.
The default for action-if-true is to define ‘WORDS_BIGENDIAN’. The default for action-if-false is to do nothing. The default for action-if-unknown is to abort configure and tell the installer how to bypass this test. And finally, the default for action-if-universal is to ensure that ‘WORDS_BIGENDIAN’ is defined if and only if a universal build is detected and the current code is big-endian; this default works only if autoheader is used (see autoheader Invocation).
If you use this macro without specifying action-if-universal, you should also use
AC_CONFIG_HEADERS; otherwise ‘WORDS_BIGENDIAN’ may be set incorrectly for Mac OS X universal binary files.
If the C compiler does not fully support the
constkeyword, defines it as empty.
Occasionally installers use a C++ compiler to compile C code, typically because they lack a C compiler. This causes problems with
const, because C and C++ treat
constdifferently. For example:const int foo;
is valid in C but not in C++. These differences unfortunately cannot be papered over by defining
constto be empty.
If autoconf detects this situation, it leaves
constalone, as this generally yields better results in practice. However, using a C++ compiler to compile C code is not recommended or supported, and installers who run into trouble in this area should get a C compiler like GCC to compile their C code.
This macro caches its result in the
ac_cv_c_constvariable.
This macro is obsolescent, as current C compilers support
const. New programs need not use this macro.
If the C compiler recognizes a variant spelling for the
restrictkeyword (
__restrict,
__restrict__, or
_Restrict), then define
restrictto that; this is more likely to do the right thing with compilers that support language variants where plain
restrictis not a keyword. Otherwise, if the C compiler recognizes the
restrictkeyword, don't do anything. Otherwise, define
restrictto be empty. Thus, programs may simply use
restrictas if every C compiler supported it; for those that do not, the makefile or configuration header defines it away.
Although support in C++ for the
restrictkeyword is not required, several C++ compilers do accept the keyword. This macro works for them, too.
This macro caches ‘no’ in the
ac_cv_c_restrictvariable if
restrictis not supported, and a supported spelling otherwise.
If the C compiler does not understand the keyword
volatile, define
volatileto be empty. Programs can simply use
volatileas if every C compiler supported it; for those that do not, the makefile or configuration header defines it as empty.
If the correctness of your program depends on the semantics of
volatile, simply defining it to be empty does, in a sense, break your code. However, given that the compiler does not support
volatile, you are at its mercy anyway. At least your program compiles, when it wouldn't before. See Volatile Objects, for more about
volatile.
In general, the
volatilekeyword is a standard C feature, so you might expect that
volatileis available only when
__STDC__is defined. However, Ultrix 4.3's native compiler does support volatile, but does not define
__STDC__.
This macro is obsolescent, as current C compilers support
volatile. New programs need not use this macro.
If the C compiler supports the keyword
inline, do nothing. Otherwise define
inlineto
__inline__or
__inlineif it accepts one of those, otherwise define
inlineto be empty.
If the C type
charis unsigned, define
__CHAR_UNSIGNED__, unless the C compiler predefines it.
These days, using this macro is not necessary. The same information can be determined by this portable alternative, thus avoiding the use of preprocessor macros in the namespace reserved for the implementation.#include <limits.h> #if CHAR_MIN == 0 # define CHAR_UNSIGNED 1 #endif
If the C preprocessor supports the stringizing operator, define
HAVE_STRINGIZE. The stringizing operator is ‘#’ and is found in macros such as this:#define x(y) #y
This macro is obsolescent, as current C compilers support the stringizing operator. New programs need not use this macro.
If the C compiler supports flexible array members, define
FLEXIBLE_ARRAY_MEMBERto nothing; otherwise define it to 1. That way, a declaration like this:struct s { size_t n_vals; double val[FLEXIBLE_ARRAY_MEMBER]; };
will let applications use the “struct hack” even with compilers that do not support flexible array members. To allocate and use such an object, you can use code like this:size_t i; size_t n = compute_value_count (); struct s *p = malloc (offsetof (struct s, val) + n * sizeof (double)); p->n_vals = n; for (i = 0; i < n; i++) p->val[i] = compute_value (i);
If the C compiler supports variable-length arrays, define
HAVE_C_VARARRAYS. A variable-length array is an array of automatic storage duration whose length is determined at run time, when the array is declared.
If the C compiler supports GCC's
typeofsyntax either directly or through a different spelling of the keyword (e.g.,
__typeof__), define
HAVE_TYPEOF. If the support is available only through a different spelling, define
typeofto that spelling.
If function prototypes are understood by the compiler (as determined by
AC_PROG_CC), define
PROTOTYPESand
__PROTOTYPES. Defining
__PROTOTYPESis for the benefit of header files that cannot use macros that infringe on user name space.
This macro is obsolescent, as current C compilers support prototypes. New programs need not use this macro.
Add -traditional to output variable
CCif using the GNU C compiler and
ioctldoes not work properly without -traditional. That usually happens when the fixed header files have not been installed on an old system.
This macro is obsolescent, since current versions of the GNU C compiler fix the header files automatically when installed.
Determine a C++ compiler to use. Check whether([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
If using the GNU C++ compiler, set shell variable
GXXto ‘yes’. If output variable
CXXFLAGSwas not already set, set it to -g -O2 for the GNU C++ compiler (-O2 on systems where G++ does not accept -g), or -g for other compilers. If your package does not like this default, then it is acceptable to insert the line ‘: ${CXXFLAGS=""}’ after
AC_INITand before
AC_PROG_CXXto select an empty default instead.
Set output variable
CXXCPPto a command that runs the C++ preprocessor. If ‘$CXX -E’ doesn't work, /lib/cpp is used. It is portable to run
CXXCPPonly on files with a .c, .C, .cc, or .cpp++.
Test whether the C++ compiler accepts the options -c and -o simultaneously, and define
CXX_NO_MINUS_C_MINUS_O, if it does not.
Determine an Objective C compiler to use. If
OBJCis not already set in the environment, check for Objective C compilers. Set output variable
OBJCtClike this:AC_PROG_OBJC([gcc objcc objc])
If using the GNU Objective C compiler, set shell variable
GOBJCto ‘yes’. If output variable
OBJCFLAGSwas not already set, set it to -g -O2 for the GNU Objective C compiler (-O2 on systems where gcc does not accept -g), or -g for other compilers.
Set output variable
OBJCPPto a command that runs the Objective C preprocessor. If ‘$OBJC -E’ doesn't work, /lib/cpp is used.
Determine an Objective C++ compiler to use. If
OBJCXXis not already set in the environment, check for Objective C++ compilers. Set output variable
OBJCXXtCXXlike this:AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
If using the GNU Objective C++ compiler, set shell variable
GOBJCXXto ‘yes’. If output variable
OBJCXXFLAGSwas not already set, set it to -g -O2 for the GNU Objective C++ compiler (-O2 on systems where gcc does not accept -g), or -g for other compilers.
Set output variable
OBJCXXCPPto a command that runs the Objective C++ preprocessor. If ‘$OBJCXX -E’ doesn't work, /lib/cpp is used.
Autoconf defines the following macros for determining paths to the essential Erlang/OTP programs:
Determine an Erlang compiler to use. If
ERLCis not already set in the environment, check for erlc. Set output variable
ERLCto the complete path of the compiler command found. In addition, if
ERLCFLAGSis not set in the environment, set it to an empty value.
The two optional arguments have the same meaning as the two last arguments of macro
AC_PATH_PROGfor looking for the erlc program. For example, to look for erlc only in the /usr/lib/erlang/bin directory:AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
A simplified variant of the
AC_ERLANG_PATH_ERLCmacro, that prints an error message and exits the configure script if the erlc program is not found.
Determine an Erlang interpreter to use. If
ERLis not already set in the environment, check for erl. Set output variable
ERLto the complete path of the interpreter command found.
The two optional arguments have the same meaning as the two last arguments of macro
AC_PATH_PROGfor looking for the erl program. For example, to look for erl only in the /usr/lib/erlang/bin directory:AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
A simplified variant of the
AC_ERLANG_PATH_ERLmacro, that prints an error message and exits the configure script if the erl program is not found.
The Autoconf Fortran support is divided into two categories: legacy
Fortran 77 macros (
F77), and modern Fortran macros (
FC).
The former are intended for traditional Fortran 77 code, and have output
variables like
F77,
FFLAGS, and
FLIBS. The latter
are for newer programs that can (or must) compile under the newer
Fortran standards, and have output variables like
FC,
FCFLAGS, and
FCLIBS.
Except for the macros
AC_FC_SRCEXT,
AC_FC_FREEFORM,
AC_FC_FIXEDFORM, and
AC_FC_LINE_LENGTH (see below), the
FC and
F77 macros behave almost identically, and so they
are documented together in this section.
Determine a Fortran 77 compiler to use. If blanklike this:AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
If using
g77(the GNU Fortran 77 compiler), then set the shell variable
G77to ‘yes’. If the output variable
FFLAGSwas not already set in the environment, then set it to -g -02 for
g77(or -O2 where
g77does not accept -g). Otherwise, set
FFLAGSto -g for all other Fortran 77 compilers.
The result of the GNU test is cached in the
ac_cv_f77_compiler_gnuvariable, acceptance of -g in the
ac_cv_prog_f77_gvariable.
Determine a Fortran compiler to use. If
FCis not already set in the environment, then
dialectis a hint to indicate what Fortran dialect to search for; the default is to search for the newest available dialect. Set the output variable
FCto the name of the compiler found.
By default, newer dialects are preferred over older dialects, but if
dialectis specified then older dialects are preferred starting with the specified dialect.
dialectcan currently be one of Fortran 77, Fortran 90, or Fortran 95. However, this is only a hint of which compiler name to prefer (e.g.,
f90or
f95), and no attempt is made to guarantee that a particular language standard is actually supported. Thus, it is preferable that you avoid the
dialectoption, and use AC_PROG_FC only for code compatible with the latest Fortran standard.
This macro may, alternatively, be invoked with an optional first argument which, if specified, must be a blank-separated list of Fortran compilers to search for, just as in
AC_PROG_F77.
If using
gfortranor
g77(the GNU Fortran compilers), then set the shell variable
GFCto ‘yes’. If the output variable
FCFLAGSwas not already set in the environment, then set it to -g -02 for GNU
g77(or -O2 where
g77does not accept -g). Otherwise, set
FCFLAGSto -g for all other Fortran compilers.
The result of the GNU test is cached in the
ac_cv_fc_compiler_gnuvariable, acceptance of -g in the
ac_cv_prog_fc_gvariable.
Test whether the Fortran compiler accepts the options -c and -o simultaneously, and define
F77_NO_MINUS_C_MINUS_Oor
FC_NO_MINUS_C_MINUS_O, respectively, if it does not.
The result of the test is cached in the
ac_cv_prog_f77_c_oor
ac_cv_prog_fc_c_ovariable, respectively.
The following macros check for Fortran compiler characteristics.
To check for characteristics not listed here, use
AC_COMPILE_IFELSE (see Running the Compiler) or
AC_RUN_IFELSE (see Runtime), making sure to first set the
current language to Fortran 77 or Fortran via
AC_LANG([Fortran 77])
or
AC_LANG(Fortran) (see Language Choice).
Determine the linker flags (e.g., -L and -l) for the Fortran intrinsic and runtime libraries that are required to successfully link a Fortran program or shared library. The output variable
FLIBSor
FCLIBSis set to these flags (which should be included after
LIBSwhen linking).
This macro is intended to be used in those situations when it is necessary to mix, e.g., C++ and Fortran source code in a single program or shared library (see Mixing Fortran 77 With C and C++).
For example, if object files from a C++ and Fortran compiler must be linked together, then the C++ compiler/linker must be used for linking (since special C++-ish things need to happen at link time like calling global constructors, instantiating templates, enabling exception support, etc.).
However, the Fortran intrinsic and runtime libraries must be linked in as well, but the C++ compiler/linker doesn't know by default how to add these Fortran 77 libraries. Hence, this macro was created to determine these Fortran libraries.
The macros
AC_F77_DUMMY_MAINand
AC_FC_DUMMY_MAINor
AC_F77_MAINand
AC_FC_MAINare probably also necessary to link C/C++ with Fortran; see below. Further, it is highly recommended that you use
AC_CONFIG_HEADERS(see Configuration Headers) because the complex defines that the function wrapper macros create may not work with C/C++ compiler drivers.
These macros internally compute the flag needed to verbose linking output and cache it in
ac_cv_prog_f77_vor
ac_cv_prog_fc_vvariables, respectively. The computed linker flags are cached in
ac_cv_f77_libsor
ac_cv_fc_libs, respectively.
With many compilers, the Fortran libraries detected by
AC_F77_LIBRARY_LDFLAGSor
AC_FC_LIBRARY_LDFLAGSprovide their own
mainentry function that initializes things like Fortran I/O, and which then calls a user-provided entry function named (say)
MAIN__to run the user's program. The
AC_F77_DUMMY_MAINand
AC_FC_DUMMY_MAINor
AC_F77_MAINand
AC_FC_MAINmacros figure out how to deal with this interaction.
When using Fortran for purely numerical functions (no I/O, etc.) often one prefers to provide one's own
mainand skip the Fortran library initializations. In this case, however, one may still need to provide a dummy
MAIN__routine in order to prevent linking errors on some systems.
AC_F77_DUMMY_MAINor
AC_FC_DUMMY_MAINdetects whether any such routine is required for linking, and what its name is; the shell variable
F77_DUMMY_MAINor
FC_DUMMY_MAINholds this name,
unknownwhen no solution was found, and
nonewhen no such dummy main is needed.
By default, action-if-found defines
F77_DUMMY_MAINor
FC_DUMMY_MAINto the name of this routine (e.g.,
MAIN__) if it is required.
(Replace
F77with
FCfor Fortran instead of Fortran 77.)
Note that this macro is called automatically from
AC_F77_WRAPPERSor
AC_FC_WRAPPERS; there is generally no need to call it explicitly unless one wants to change the default actions.
The result of this macro is cached in the
ac_cv_f77_dummy_mainor
ac_cv_fc_dummy_mainvariable, respectively.
As discussed above, many Fortran libraries allow you to provide an entry point called (say)
MAIN__instead of the usual
main, which is then called by a
mainfunction in the Fortran libraries that initializes things like Fortran I/O. The
AC_F77_MAINand
AC_FC_MAINmacros detect whether it is possible to utilize such an alternate main function, and defines
F77_MAINand
FC_MAINto the name of the function. (If no alternate main function name is found,
F77_MAINand
FC_MAINare simply defined to
main.)
Thus, when calling Fortran routines from C that perform things like I/O, one should use this macro and declare the "main" function like so:#ifdef __cplusplus extern "C" #endif int F77_MAIN (int argc, char *argv[]);
(Again, replace
F77with
FCfor Fortran instead of Fortran 77.)
The result of this macro is cached in the
ac_cv_f77_mainor
ac_cv_fc_mainvariable, respectively.
Defines C macros
F77_FUNC (name, NAME),
FC_FUNC (name, NAME),
F77_FUNC_(name, NAME), and
FC_FUNC_(name, NAME)to properly mangle the names of C/C++ identifiers, and identifiers with underscores, respectively, so that they match the name-mangling scheme used by the Fortran compiler.
Fortran is case-insensitive, and in order to achieve this the Fortran compiler converts all identifiers into a canonical case and format. To call a Fortran subroutine from C or to write a C function that is callable from Fortran, the C program must explicitly use identifiers in the format expected by the Fortran compiler. In order to do this, one simply wraps all C identifiers in one of the macros provided by
AC_F77_WRAPPERSor
AC_FCso that it can select the right one. Note also that all parameters to Fortran 77 routines are passed as pointers (see Mixing Fortran 77 With C and C++).
(Replace
F77with
FCfor Fortran instead of Fortran 77.)
Although Autoconf tries to be intelligent about detecting the name-mangling scheme of the Fortran compiler, there may be Fortran compilers that it doesn't support yet. In this case, the above code generates a compile-time error, but some other behavior (e.g., disabling Fortran-related features) can be induced by checking whether
F77_FUNCor
FC_FUNCis defined.
Now, to call that routine from a C program, we would do something like:{ double x = 2.7183, y; FOOBAR_F77 (&x, &y); }
If the Fortran identifier contains an underscore (e.g.,
foo_bar), you should use
F77_FUNC_or
FC_FUNC_instead of
F77_FUNCor
FC_FUNC(with the same arguments). This is because some Fortran compilers mangle names differently if they contain an underscore.
The name mangling scheme is encoded in the
ac_cv_f77_manglingor
ac_cv_fc_manglingcache variable, respectively, and also used for the
AC_F77_FUNCand
AC_FC_FUNCmacros described below.
Given an identifier name, set the shell variable shellvar to hold the mangled version name according to the rules of the Fortran linker (see also
AC_F77_WRAPPERSor
AC_FC_WRAPPERS). shellvar is optional; if it is not supplied, the shell variable is simply name. The purpose of this macro is to give the caller a way to access the name-mangling information other than through the C preprocessor as above, for example, to call Fortran routines from some language other than C/C++.
By default, the
FCmacros perform their tests using a .f extension for source-code files. Some compilers, however, only enable newer language features for appropriately named files, e.g., Fortran 90 features only for .f90 files, or preprocessing only with .F files or maybe other upper-case extensions. On the other hand, some other compilers expect all source files to end in .f and require special flags to support other file name extensions. The
AC_FC_SRCEXTand
AC_FC_PP_SRCEXTmacros deal with these issues.
The
AC_FC_SRCEXTmacro tries to get the
FCcompiler to accept files ending with the extension .ext (i.e., ext does not contain the dot). If any special compiler flags are needed for this, it stores them in the output variable
FCFLAGS_ext. This extension and these flags are then used for all subsequent
FCtests (until
AC_FC_SRCEXTor
AC_FC_PP_SRCEXTis called another time).
For example, you would use
AC_FC_SRCEXT(f90)to employ the .f90 extension in future tests, and it would set the
FCFLAGS_f90output variable with any extra flags that are needed to compile such files.
Similarly, the
AC_FC_PP_SRCEXTmacro tries to get the
FCcompiler to preprocess and compile files with the extension .ext. When both fpp and cpp style preprocessing are provided, the former is preferred, as the latter may treat continuation lines,
//tokens, and white space differently from what some Fortran dialects expect. Conversely, if you do not want files to be preprocessed, use only lower-case characters in the file name extension. Like with
AC_FC_SRCEXT(f90), any needed flags are stored in the
FCFLAGS_ext variable.
The
FCFLAGS_ext flags can not be simply absorbed into
FCFLAGS, for two reasons based on the limitations of some compilers. First, only one
FCFLAGS_ext can be used at a time, so files with different extensions must be compiled separately. Second,
FCFLAGS_ext must appear immediately before the source-code file name when compiling. So, continuing the example above, you might compile a foo.f90 file in your makefile with the command:foo.o: foo.f90 $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
If
AC_FC_SRCEXTor
AC_FC_PP_SRCEXTsucceeds in compiling files with the ext extension, it calls action-if-success (defaults to nothing). If it fails, and cannot find a way to make the
FCcompiler accept such files, it calls action-if-failure (defaults to exiting with an error message).
The
AC_FC_SRCEXTand
AC_FC_PP_SRCEXTmacros cache their results in
ac_cv_fc_srcext_ext and
ac_cv_fc_pp_srcext_ext variables, respectively.
Find a flag to specify defines for preprocessed Fortran. Not all Fortran compilers use -D. Substitute
FC_DEFINEwith the result and call action-if-success (defaults to nothing) if successful, and action-if-failure (defaults to failing with an error message) if not.
This macro calls
AC_FC_PP_SRCEXT([F])in order to learn how to preprocess a conftest.F file, but restores a previously used Fortran source file extension afterwards again.
The result of this test is cached in the
ac_cv_fc_pp_definevariable.
Try to ensure that the Fortran compiler (
$FC) allows free-format source code (as opposed to the older fixed-format style from Fortran 77). If necessary, it may add some additional flags to
FCFLAGS.
This macro is most important if you are using the default .f extension, since many compilers interpret this extension as indicating fixed-format source unless an additional flag is supplied. If you specify a different extension with
AC_FC_SRCEXT, such as .f90, then
AC_FC_FREEFORMordinarily succeeds without modifying
FCFLAGS. For extensions which the compiler does not know about, the flag set by the
AC_FC_SRCEXTmacro might let the compiler assume Fortran 77 by default, however.
If
AC_FC_FREEFORMsucceeds in compiling free-form source, it calls action-if-success (defaults to nothing). If it fails, it calls action-if-failure (defaults to exiting with an error message).
The result of this test, or ‘none’ or ‘unknown’, is cached in the
ac_cv_fc_freeformvariable.
Try to ensure that the Fortran compiler (
$FC) allows the old fixed-format source code (as opposed to free-format style). If necessary, it may add some additional flags to
FCFLAGS.
This macro is needed for some compilers alias names like xlf95 which assume free-form source code by default, and in case you want to use fixed-form source with an extension like .f90 which many compilers interpret as free-form by default. If you specify a different extension with
AC_FC_SRCEXT, such as .f, then
AC_FC_FIXEDFORMordinarily succeeds without modifying
FCFLAGS.
If
AC_FC_FIXEDFORMs_fixedformvariable.
Try to ensure that the Fortran compiler (
$FC) accepts long source code lines. The length argument may be given as 80, 132, or unlimited, and defaults to 132. Note that line lengths above 254 columns are not portable, and some compilers do not accept more than 132 columns at least for fixed format source. If necessary, it may add some additional flags to
FCFLAGS.
If
AC_FC_LINE_LENGTHs_line_lengthvariable.
The
AC_FC_CHECK_BOUNDSmacro tries to enable array bounds checking in the Fortran compiler. If successful, the action-if-success is called and any needed flags are added to
FCFLAGS. Otherwise, action-if-failure is called, which defaults to failing with an error message. The macro currently requires Fortran 90 or a newer dialect.
The result of the macro is cached in the
ac_cv_fc_check_boundsvariable.
Try to disallow implicit declarations in the Fortran compiler. If successful, action-if-success is called and any needed flags are added to
FFLAGSor
FCFLAGS, respectively. Otherwise, action-if-failure is called, which defaults to failing with an error message.
The result of these macros are cached in the
ac_cv_f77_implicit_noneand
ac_cv_fc_implicit_nonevariables, respectively.
Find the Fortran 90 module file name extension. Most Fortran 90 compilers store module information in files separate from the object files. The module files are usually named after the name of the module rather than the source file name, with characters possibly turned to upper case, plus an extension, often .mod.
Not all compilers use module files at all, or by default. The Cray Fortran compiler requires -e m in order to store and search module information in .mod files rather than in object files. Likewise, the Fujitsu Fortran compilers uses the -Am option to indicate how module information is stored.
The
AC_FC_MODULE_EXTENSIONmacro computes the module extension without the leading dot, and stores that in the
FC_MODEXTvariable. If the compiler does not produce module files, or the extension cannot be determined,
FC_MODEXTis empty. Typically, the result of this macro may be used in cleanup make rules as follows:clean-modules: -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
The extension, or ‘unknown’, is cached in the
ac_cv_fc_module_extvariable.
Find the compiler flag to include Fortran 90 module information from another directory, and store that in the
FC_MODINCvariable. Call action-if-success (defaults to nothing) if successful, and set
FC_MODINCto empty and call action-if-failure (defaults to exiting with an error message) if not.
Most Fortran 90 compilers provide a way to specify module directories. Some have separate flags for the directory to write module files to, and directories to search them in, whereas others only allow writing to the current directory or to the first directory specified in the include path. Further, with some compilers, the module search path and the preprocessor search path can only be modified with the same flag. Thus, for portability, write module files to the current directory only and list that as first directory in the search path.
There may be no whitespace between
FC_MODINCand the following directory name, but
FC_MODINCmay contain trailing white space. For example, if you use Automake and would like to search ../lib for module files, you can use the following:AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
Inside configure tests, you can use:if test -n "$FC_MODINC"; then FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib" fi
The flag is cached in the
ac_cv_fc_module_flagvariable. The substituted value of
FC_MODINCmay refer to the
ac_emptydummy placeholder empty variable, to avoid losing the significant trailing whitespace in a Makefile.
Find the compiler flag to write Fortran 90 module information to another directory, and store that in the
FC_MODOUTvariable. Call action-if-success (defaults to nothing) if successful, and set
FC_MODOUTto empty and call action-if-failure (defaults to exiting with an error message) if not.
Not all Fortran 90 compilers write module files, and of those that do, not all allow writing to a directory other than the current one, nor do all have separate flags for writing and reading; see the description of
AC_FC_MODULE_FLAGabove. If you need to be able to write to another directory, for maximum portability use
FC_MODOUTbefore any
FC_MODINCand include both the current directory and the one you write to in the search path:AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). ...
The flag is cached in the
ac_cv_fc_module_output_flagvariable. The substituted value of
FC_MODOUTmay refer to the
ac_emptydummy placeholder empty variable, to avoid losing the significant trailing whitespace in a Makefile.
Autoconf provides basic support for the Go programming language when
using the
gccgo compiler (there is currently no support for the
6g and
8g compilers).
Find the Go compiler to use. Check whether the environment variable
GOCis set; if so, then set output variable
GOCto its value.
Otherwise, if the macro is invoked without an argument, then search for a Go compiler named
gccgo. If it is not found, then as a last resort set
GOCto
gccgo.
This macro may be invoked with an optional first argument which, if specified, must be a blank-separated list of Go compilers to search for.
If output variable
GOFLAGSwas not already set, set it to -g -O2. If your package does not like this default,
GOFLAGSmay be set before
AC_PROG_GO.
The following macros check for operating system services or capabilities.
Try to locate the X Window System include files and libraries. If the user gave the command line options --x-includes=dir and --x-libraries=dir, use those directories.
If either or both were not given, get the missing values by running
xmkmf(or an executable pointed to by the
XMKMFenvironment variable) on a trivial Imakefile and examining the makefile that it produces. Setting
XMKMFto ‘false’ disables this method.
If this method fails to find the X Window System, configure looks for the files in several directories where they often reside. If either method is successful, set the shell variables
x_includesand
x_librariesto their locations, unless they are in directories the compiler searches by default.
If both methods fail, or the user gave the command line option --without-x, set the shell variable
no_xto ‘yes’; otherwise set it to the empty string.
An enhanced version of -lX11, and adds any found to the output variable
X_PRE_LIBS.
Check whether the system supports starting scripts with a line of the form ‘#!/bin/sh’ to select the interpreter to use for the script. After running this macro, shell code in configure.ac can check the shell variable
interpval; it is set to ‘yes’ if the system supports ‘#!’, ‘no’ if not.
Arrange for 64-bit file offsets, known as large-file support. On some hosts, one must use special compiler options to build programs that can access large files. Append any such options to the output variable
CC. Define
_FILE_OFFSET_BITSand
_LARGE_FILESif necessary.
Large-file support can be disabled by configuring with the --disable-largefile option.
If you use this macro, check that your program works even when
off_tis wider than
long int, since this is common when large-file support is enabled. For example, it is not correct to print an arbitrary
off_tvalue
Xwith
printf ("%ld", (long int) X).
The LFS introduced the
fseekoand
ftellofunctions to replace their C counterparts
fseekand
ftellthat do not use
off_t. Take care to use
AC_FUNC_FSEEKOto make their prototypes available when using them and large-file support is enabled.
If the system supports file names longer than 14 characters, define
HAVE_LONG_FILE_NAMES.
Check to see if the Posix termios headers and functions are available on the system. If so, set the shell variable
ac_cv_sys_posix_termiosto ‘yes’. If not, set the variable to ‘no’.
The following macro makes it possible to use features of Posix that are extensions to C, as well as platform extensions not defined by Posix.
This macro was introduced in Autoconf 2.60. If possible, enable extensions to C or Posix on hosts that normally disable the extensions, typically due to standards-conformance namespace issues. This should be called before any macros that run the C compiler. The following preprocessor macros are defined where appropriate:
_GNU_SOURCE
- Enable extensions on GNU/Linux.
__EXTENSIONS__
- Enable general extensions on Solaris.
_POSIX_PTHREAD_SEMANTICS
- Enable threading extensions on Solaris.
_TANDEM_SOURCE
- Enable extensions for the HP NonStop platform.
_ALL_SOURCE
- Enable extensions for AIX 3, and for Interix.
_POSIX_SOURCE
- Enable Posix functions for Minix.
_POSIX_1_SOURCE
- Enable additional Posix functions for Minix.
_MINIX
- Identify Minix platform. This particular preprocessor macro is obsolescent, and may be removed in a future release of Autoconf..
Autoconf-generated configure scripts check for the C compiler and its features by default. Packages that use other programming languages (maybe more than one, e.g., C and C++) need to test features of the compilers for the respective languages. The following macros determine which programming language is used in the subsequent tests in configure.ac.
Do compilation tests using the compiler, preprocessor, and file extensions for the specified language.
Supported languages are:
- ‘C’
- Do compilation tests using
CCand
CPPand use extension .c for test programs. Use compilation flags:
CPPFLAGSwith
CPP, and both
CPPFLAGSand
CFLAGSwith
CC.
- ‘C++’
- Do compilation tests using
CXXand
CXXCPPand use extension .C for test programs. Use compilation flags:
CPPFLAGSwith
CXXCPP, and both
CPPFLAGSand
CXXFLAGSwith
CXX.
- ‘Fortran 77’
- Do compilation tests using
F77and use extension .f for test programs. Use compilation flags:
FFLAGS.
- ‘Fortran’
- Do compilation tests using
FCand use extension .f (or whatever has been set by
AC_FC_SRCEXT) for test programs. Use compilation flags:
FCFLAGS.
- ‘Erlang’
- Compile and execute tests using
ERLCand
ERLand use extension .erl for test Erlang modules. Use compilation flags:
ERLCFLAGS.
- ‘Objective C’
- Do compilation tests using
OBJCand
OBJCPPand use extension .m for test programs. Use compilation flags:
CPPFLAGSwith
OBJCPP, and both
CPPFLAGSand
OBJCFLAGSwith
OBJC.
- ‘Objective C++’
- Do compilation tests using
OBJCXXand
OBJCXXCPPand use extension .mm for test programs. Use compilation flags:
CPPFLAGSwith
OBJCXXCPP, and both
CPPFLAGSand
OBJCXXFLAGSwith
OBJCXX.
- ‘Go’
- Do compilation tests using
GOCand use extension .go for test programs. Use compilation flags
GOFLAGS.
Remember the current language (as set by
AC_LANG) on a stack, and then select the language. Use this macro and
AC_LANG_POPin macros that need to temporarily switch to a particular language.
Select the language that is saved on the top of the stack, as set by
AC_LANG_PUSH, and remove it from the stack.
If given, language specifies the language we just quit. It is a good idea to specify it when it's known (which should be the case...), since Autoconf detects inconsistencies.AC_LANG_PUSH([Fortran 77]) # Perform some tests on Fortran 77. # ... AC_LANG_POP([Fortran 77])
Check statically that the current language is language. You should use this in your language specific macros to avoid that they be called with an inappropriate language.
This macro runs only at autoconf time, and incurs no cost at configure time. Sadly enough and because Autoconf is a two layer language 2, the macros
AC_LANG_PUSHand
AC_LANG_POPcannot be “optimizing”, therefore as much as possible you ought to avoid using them to wrap your code, rather, require from the user to run the macro with a correct current language, and check it with
AC_LANG_ASSERT. And anyway, that may help the user understand she is running a Fortran macro while expecting a result about her Fortran 77 compiler...
Ensure that whichever preprocessor would currently be used for tests has been found. Calls
AC_REQUIRE(see Prerequisite Macros) with an argument of either
AC_PROG_CPPor
AC_PROG_CXXCPP, depending on which language is current.
Autoconf tests follow a common scheme: feed some program with some input, and most of the time, feed a compiler with some source file. This section is dedicated to these source samples..
These days it's safe to assume support for function prototypes (introduced in C89).
Functions that test programs declare should also be conditionalized for C++, which requires ‘extern "C"’ prototypes. Make sure to not include any header files containing clashing prototypes.
#ifdef __cplusplus extern "C" #endif void *valloc (size_t);
If a test program calls a function with invalid parameters (just to see
whether it exists), organize the program to ensure that it never invokes
that function. You can do this by calling it in another function that is
never invoked. You can't do it by putting it after a call to
exit, because GCC version 2 knows that
exit
never returns
and optimizes out any code that follows it in the same block.
If you include any header files, be sure to call the functions
relevant to them with the correct number of arguments, even if they are
just 0, to avoid compilation errors due to prototypes. GCC
version 2
has internal prototypes for several functions that it automatically
inlines; for example,
memcpy. To avoid errors when checking for
them, either pass them the correct number of arguments or redeclare them
with a different return type (such as
char).
Autoconf provides a set of macros that can be used to generate test source files. They are written to be language generic, i.e., they actually depend on the current language (see Language Choice) to “format” the output properly.
Save the source text in the current test source file: conftest.extension where the extension depends on the current language. As of Autoconf 2.63b, the source file also contains the results of all of the
AC_DEFINEperformed so far.
Note that the source is evaluated exactly once, like regular Autoconf macro arguments, and therefore (i) you may pass a macro invocation, (ii) if not, be sure to double quote if needed.
This macro issues a warning during autoconf processing if source does not include an expansion of the macro
AC_LANG_DEFINES_PROVIDED(note that both
AC_LANG_SOURCEand
AC_LANG_PROGRAMcall this macro, and thus avoid the warning).
This macro is seldom called directly, but is used under the hood by more common macros such as
AC_COMPILE_IFELSEand
AC_RUN_IFELSE.
This macro is called as a witness that the file conftest.extension appropriate for the current language is complete, including all previously determined results from
AC_DEFINE. This macro is seldom called directly, but exists if you have a compelling reason to write a conftest file without using
AC_LANG_SOURCE, yet still want to avoid a syntax warning from
AC_LANG_CONFTEST.
Expands into the source, with the definition of all the
AC_DEFINEperformed so far. This macro includes an expansion of
AC_LANG_DEFINES_PROVIDED.
In many cases, you may find it more convenient to use the wrapper
AC_LANG, Erlang, or Go, the
AC_DEFINE
definitions are not automatically translated into constants in the
source code by this macro.
Expands into a source file which consists of the prologue, and then body as body of the main function (e.g.,
mainin C). Since it uses
AC_LANG_SOURCE, the features of the latter are available.
For instance:
AC_INIT([Hello], [1.0], [[email protected]], [], []) AC_DEFINE([HELLO_WORLD], ["Hello, World\n"], [Greetings string.]) AC_LANG_CONFTEST( [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]], [[fputs (hw, std"; int main () { fputs (hw, stdout); ; return 0; }
In Erlang tests, the created source file is that of an Erlang module called
conftest (conftest.erl). This module defines and exports
at least
one
start/0 function, which is called to perform the test. The
prologue is optional code that is inserted between the module header and
the
start/0 function definition. body is the body of the
start/0 function without the final period (see Runtime, about
constraints on this function's behavior).
For instance:
AC_INIT([Hello], [1.0], [[email protected]]) AC_LANG(Erlang) AC_LANG_CONFTEST( [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]], [[io:format("~s~n", [?HELLO_WORLD])]])]) cat conftest.erl
results in:
-module(conftest). -export([start/0]). -define(HELLO_WORLD, "Hello, world!"). start() -> io:format("~s~n", [?HELLO_WORLD]) .
Expands into a source file which consists of the prologue, and then a call to the function as body of the main function (e.g.,
mainin C). Since it uses
AC_LANG_PROGRAM, the feature of the latter are available.
This function will probably be replaced in the future by a version which would enable specifying the arguments. The use of this macro is not encouraged, as it violates strongly the typing system.
This macro cannot be used for Erlang tests.
Expands into a source file which uses the function in the body of the main function (e.g.,
mainin C). Since it uses
AC_LANG_PROGRAM, the features of the latter are available.
As
AC_LANG_CALL, this macro is documented only for completeness. It is considered to be severely broken, and in the future will be removed in favor of actual function calls (with properly typed arguments).
This macro cannot be used for Erlang tests.
Sometimes one might need to run the preprocessor on some source file. Usually it is a bad idea, as you typically need to compile your project, not merely run the preprocessor on it; therefore you certainly want to run the compiler, not the preprocessor. Resist the temptation of following the easiest path.
Nevertheless, if you need to run the preprocessor, then use
AC_PREPROC_IFELSE.
The macros described in this section cannot be used for tests in Erlang, Fortran, or Go, since those languages require no preprocessor.
Run the preprocessor of the current language (see Language Choice) on the input, run the shell commands action-if-true on success, action-if-false otherwise. The input can be made by
AC_LANG_PROGRAMand friends.
This macro uses
CPPFLAGS, but not
CFLAGS, because -g, -O, etc. are not valid options to many C preprocessors.
It is customary to report unexpected failures with
AC_MSG_FAILURE. If needed, action-if-true can further access the preprocessed output in the file conftest.i.
For instance:
AC_INIT([Hello], [1.0], [[email protected]]) AC_DEFINE([HELLO_WORLD], ["Hello, World\n"], [Greetings string.]) AC_PREPROC_IFELSE( [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]], [[fputs (hw, stdout);]])], [AC_MSG_RESULT([OK])], [AC_MSG_FAILURE([unexpected preprocessor failure])])
results OK
The macroThe macro
AC_TRY_CPP(see Obsolete Macros) used to play the role of
AC_PREPROC_IFELSE, but double quotes its argument, making it impossible to use it to elaborate sources. You are encouraged to get rid of your old use of the macro
AC_TRY_CPPin favor of
AC_PREPROC_IFELSE, but, in the first place, are you sure you need to run the preprocessor and not the compiler?
If the output of running the preprocessor on the system header file header-file matches the extended regular expression pattern, execute shell commands action-if-found, otherwise execute action-if-not-found.
program is the text of a C or C++ program, on which shell variable, back quote, and backslash substitutions are performed. If the output of running the preprocessor on program matches the extended regular expression pattern, execute shell commands action-if-found, otherwise execute action-if-not-found.
To check for a syntax feature of the current language's (see Language Choice) compiler, such as whether it recognizes a certain keyword, or
simply to try some library feature, use
AC_COMPILE_IFELSE to try
to compile a small program that uses that feature.
Run the compiler and compilation flags of the current language (see Language Choice) on the input, run the shell commands action-if-true on success, action-if-false otherwise. The input can be made by
AC_LANG_PROGRAMand friends.
It is customary to report unexpected failures with
AC_MSG_FAILURE. This macro does not try to link; use
AC_LINK_IFELSEif you need to do that (see Running the Linker). If needed, action-if-true can further access the just-compiled object file conftest.$OBJEXT.
This macro uses
AC_REQUIREfor the compiler associated with the current language, which means that if the compiler has not yet been determined, the compiler determination will be made prior to the body of the outermost
AC_DEFUNmacro that triggered this macro to expand (see Expanded Before Required).
For tests in Erlang, the input must be the source code of a module named
conftest.
AC_COMPILE_IFELSE generates a conftest.beam
file that can be interpreted by the Erlang virtual machine (
ERL). It is
recommended to use
AC_LANG_PROGRAM to specify the test program,
to ensure that the Erlang module has the right name. runtime. If needed, action-if-true can further access the just-linked program file conftest$EXEEXT.
LDFLAGSand
LIBSare used for linking, in addition to the current compilation flags.
It is customary to report unexpected failures with
AC_MSG_FAILURE. This macro does not try to execute the program; use
AC_RUN_IFELSEif you need to do that (see Runtime).
The
AC_LINK_IFELSE macro cannot be used for Erlang tests, since Erlang
programs are interpreted and do not require linking..
Run the compiler (and compilation flags) and the linker of the current language (see Language Choice) on the input, then execute the resulting program. If the program). Additionally, action-if-true can run ./conftest$EXEEXT for further testing.
In the action-if-false section, the failing exit status is available in the shell variable ‘$?’. This exit status might be that of a failed compilation, or it might be that of a failed program execution.
If cross-compilation mode is enabled (this is the case if either the compiler being used does not produce executables that run on the system where configure is being run, or if the options
--buildand
--hostwere both specified and their values are different), then the test program is not run. If the optional shell commands action-if-cross-compiling are given, those commands are run instead; typically these commands provide pessimistic defaults that allow cross-compilation to work even if the guess was wrong. If the fourth argument is empty or omitted, but cross-compilation is detected, then configure prints an error message and exits. If you want your package to be useful in a cross-compilation scenario, you should provide a non-empty action-if-cross-compiling clause, as well as wrap the
AC_RUN_IFELSEcompilation inside an
AC_CACHE_CHECK(see Caching Results) which allows the user to override the pessimistic default if needed.
It is customary to report unexpected failures with
AC_MSG_FAILURE.
autoconf prints a warning message when creating
configure each time it encounters a call to
AC_RUN_IFELSE with no action-if-cross-compiling argument
given. If you are not concerned about users configuring your package
for cross-compilation, you may ignore the warning. A few of the macros
distributed with Autoconf produce this warning message; but if this is a
problem for you, please report it as a bug, along with an appropriate
pessimistic guess to use instead.
‘yes’,).
Some operations are accomplished in several possible ways, depending on the OS. Note that
since the value of
fstype is under our control, we don't have to
use the longer ‘test "x$fstype" = xno’.
AC_MSG_CHECKING([how to get file system type]) fstype=no # The order of these tests is important. AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h> #include <sys/fstyp.h>]])], [AC_DEFINE([FSTYPE_STATVFS], [1], [Define if statvfs exists.]) fstype=SVR4]) if test $fstype = no; then AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h> #include <sys/fstyp.h>]])], [AC_DEFINE([FSTYPE_USG_STATFS], [1], [Define if USG statfs.]) fstype=SVR3]) fi if test $fstype = no; then AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h> #include <sys/vmount.h>]])]), [AC_DEFINE([FSTYPE_AIX_STATFS], [1], [Define if AIX statfs.]) fstype=AIX]) fi # (more cases omitted here) AC_MSG_RESULT([$fstype])
Many output variables are intended to be evaluated both by make and by the shell. Some characters are expanded differently in these two contexts, so to avoid confusion these variables' values should not contain any of the following characters:
" # $ & ' ( ) * ; < > ? [ \ ^ ` |
Also, these variables' values should neither contain newlines, nor start with ‘~’, nor contain white space or ‘:’ immediately followed by ‘~’. The values can contain nonempty sequences of white space characters like tabs and spaces, but each such sequence might arbitrarily be replaced by a single space during substitution.
These restrictions apply both to the values that configure
computes, and to the values set directly by the user. For example, the
following invocations of configure are problematic, since they
attempt to use special characters within
CPPFLAGS and white space
within
$(srcdir):
CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure' '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
To avoid checking for the same features repeatedly in various configure scripts (or in repeated runs of one script), configure can optionally save the results of many checks in a cache file (see Cache Files). If a configure script runs with caching enabled and finds a cache file, it reads the results of previous runs from the cache and avoids rerunning those checks. As a result, configure can then run much faster than if it had to perform all of the checks every time.. If the shell commands are run to determine the value, the value is saved in the cache file just before configure creates its output files. See Cache Variable Names, for how to choose the name of the cache-id variable.
The commands-to-set-it must have no side effects except for setting the variable cache-id, see below.
A wrapper for
AC_CACHE_VALthat takes care of printing the messages. This macro provides a convenient shorthand for the most common way to use these macros. It calls
AC_MSG_CHECKINGfor message, then
AC_CACHE_VALwith the cache-id and commands arguments, and
AC_MSG_RESULTwith cache-id.
The commands-to-set-it must have no side effects except for setting the variable cache-id, see below.
It is common to find buggy macros using
AC_CACHE_VAL or
AC_CACHE_CHECK, because people are tempted to call
AC_DEFINE in the commands-to-set-it. Instead, the code that
follows the call to
AC_CACHE_VAL should call
AC_DEFINE, by examining the value of the cache variable. For
instance, the following macro is broken:]) ])
This fails if the cache is enabled: the second time this macro is run,
TRUE_WORKS will not be defined. The proper implementation
is: ])
Also, commands-to-set-it should not print any messages, for
example with
AC_MSG_CHECKING; do that before calling
AC_CACHE_VAL, so the messages are printed regardless of whether
the results of the check are retrieved from the cache or determined by
running the shell commands.
The names of cache variables should have the following format:
package-prefix_cv_value-type_specific-value_[additional-options]
for example, ‘ac_cv_header_stat_broken’ or ‘ac_cv_prog_gcc_traditional’. The parts of the variable name are:
_cv_
The values assigned to cache variables may not contain newlines. Usually, their values are Boolean (‘yes’ or ‘no’) or the names of files or functions; so this is not an important restriction. Cache Variable Index for an index of cache variables with documented semantics., or override documented cache variables on the configure command line..
If configure is interrupted at the right time when it updates a cache file outside of the build directory where the configure script is run, it may leave behind a temporary file named after the cache file with digits following it. You may safely delete such a file.
If your configure script, or a macro called from configure.ac, happens
to abort the configure process, it may be useful to checkpoint the cache
a few times at key points using
AC_CACHE_SAVE. Doing so
reduces the amount of time it takes to rerun the configure script with
(hopefully) the error that caused the previous abort corrected.
Loads values from existing cache file, or creates a new cache file if a cache file is not found. Called automatically from
AC_INIT.
Flushes all cached values to the cache file. Called automatically from
AC_OUTPUT, but it can be quite useful to call
AC_CACHE_SAVEat key points in configure.ac.
For instance:
... AC_INIT, etc. ... # Checks for programs. AC_PROG_CC AC_PROG_AWK ... more program checks ... AC_CACHE_SAVE # Checks for libraries. AC_CHECK_LIB([nsl], [gethostbyname]) AC_CHECK_LIB([socket], [connect]) ... more lib checks ... AC_CACHE_SAVE # Might abort... AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])]) AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])]) ... AC_OUTPUT, etc. ...
configure scripts need to give users running them several kinds of information. The following macros print messages in ways appropriate for each kind. The arguments to all of them get enclosed in shell double quotes, so the shell performs variable and back-quote substitution on them.
These macros are all wrappers around the echo shell command. They direct output to the appropriate file descriptor (see File Descriptor Macros). configure scripts should rarely need to run echo directly to print messages for the user. Using these macros makes it easy to change how and when each kind of message is printed; such changes need only be made to the macro definitions and all the callers change automatically.
To diagnose static issues, i.e., when autoconf is run, see Diagnostic Macros.
Notify the user that configure is checking for a particular feature. This macro prints a message that starts with ‘checking ’ and ends with ‘...’ and no newline. It must be followed by a call to
AC_MSG_RESULTto print the result of the check and the newline. The feature-description should be something like ‘whether the Fortran compiler accepts C++ comments’ or ‘for c89’.
This macro prints nothing if configure is run with the --quiet or --silent option.
Notify the user of the results of a check. result-description is almost always the value of the cache variable for the check, typically ‘yes’, ‘no’, or a file name. This macro should follow a call to
AC_MSG_CHECKING, and the result-description should be the completion of the message printed by the call to
AC_MSG_CHECKING.
This macro prints nothing if configure is run with the --quiet or --silent option.
Deliver the message to the user. It is useful mainly to print a general description of the overall purpose of a group of feature checks, e.g.,AC_MSG_NOTICE([checking if stack overflow is detectable])
This macro prints nothing if configure is run with the --quiet or --silent option.
Notify the user of an error that prevents configure from completing. This macro prints an error message to the standard error output and exits configure with exit-status (‘$?’ by default, except that ‘0’ is converted to ‘1’). error-description should be something like ‘invalid value $HOME for \$HOME’.
The error-description should start with a lower-case letter, and “cannot” is preferred to “can't”.
This
AC_MSG_ERRORwrapper notifies the user of an error that prevents configure from completing and that additional details are provided in config.log. This is typically used when abnormal results are found during a compilation.
Notify the configure user of a possible problem. This macro prints the message to the standard error output; configure continues running afterward, so macros that call
AC_MSG_WARNshould provide a default (back-up) behavior for the situations they warn about. problem-description should be something like ‘ln -s seems to make hard links’.: ‘#’ introduces a comment inside which no macro expansion is performed, ‘,’ separates arguments, ‘[’ and ‘]’ are the quotes themselves3, ‘(’ and ‘)’ (which M4 tries to match by pairs), and finally ‘$’ inside a macro definition.:
# define([def], ine) ⇒# define([def], ine)
Each time there can be a macro expansion, there is a quotation expansion, i.e., one level of quotes is stripped:
int tab[10]; ⇒int tab10; [int tab[10];] ⇒int tab[10];
Without this in mind, the reader might try hopelessly to use her macro
array:
define([array], [int tab[10];]) array ⇒int tab10; [array] ⇒array
How can you correctly output the intended results4?]
When M4 encounters ‘$’ within a macro definition, followed immediately by a character it recognizes (‘0’...‘9’, ‘#’, ‘@’, or ‘*’), it will perform M4 parameter expansion. This happens regardless of how many layers of quotes the parameter expansion is nested within, or even if it occurs in text that will be rescanned as a comment.
define([none], [$1]) ⇒ define([one], [[$1]]) ⇒ define([two], [[[$1]]]) ⇒ define([comment], [# $1]) ⇒ define([active], [ACTIVE]) ⇒ none([active]) ⇒ACTIVE one([active]) ⇒active two([active]) ⇒[active] comment([active]) ⇒# active
On the other hand, since autoconf generates shell code, you often want to output shell variable expansion, rather than performing M4 parameter expansion. To do this, you must use M4 quoting to separate the ‘$’ from the next character in the definition of your macro. If the macro definition occurs in single-quoted text, then insert another level of quoting; if the usage is already inside a double-quoted string, then split it into concatenated strings.
define([single], [a single-quoted $[]1 definition]) ⇒ define([double], [[a double-quoted $][1 definition]]) ⇒ single ⇒a single-quoted $1 definition double ⇒a double-quoted $1 definition
Posix states that M4 implementations are free to provide implementation extensions when ‘${’ is encountered in a macro definition. Autoconf reserves the longer sequence ‘${{’ for use with planned extensions that will be available in the future GNU M4 2.0, but guarantees that all other instances of ‘${’ will be output literally. Therefore, this idiom can also be used to output shell code parameter references:
define([first], [${1}])first ⇒${1}
Posix also states that ‘$11’ should expand to the first parameter concatenated with a literal ‘1’, although some versions of GNU M4 expand the eleventh parameter instead. For portability, you should only use single-digit M4 parameter expansion.
With this in mind, we can explore the cases where macros invoke macros... ‘`’ and ‘'’ as
quotes, but in the context of shell programming (and actually of most
programming languages), that's about the worst choice one can make:
because of strings and back-quoted expressions in shell code (such as
‘'this'’ and ‘`that`’), and because of literal characters in usual
programming languages (as in ‘'0'’), there are many unbalanced
‘`’ and ‘'’. ‘[’ and ‘]’. Not especially
because they are unlikely characters, but because they are
characters unlikely to be unbalanced.
There are other magic primitives, such as
changecom to specify
what syntactic forms are comments (it is common to see
‘changecom(<!--, -->)’ when M4 is used to produce HTML pages),
changeword and
changesyntax to change other syntactic
details (such as the character to denote the nth argument, ‘$’ by
default, the parentheses.
When writing an Autoconf macro you may occasionally need to generate special characters that are difficult to express with the standard Autoconf quoting rules. For example, you may need to output the regular expression ‘[^[]’, which matches any character other than ‘[’. This expression contains unbalanced brackets so it cannot be put easily into an M4 macro.
Additionally, there are a few m4sugar macros (such as
m4_split
and
m4_expand) which internally use special markers in addition
to the regular quoting characters. If the arguments to these macros
contain the literal strings ‘-=<{(’ or ‘)}>=-’, the macros
might behave incorrectly.
You can work around these problems by using one of the following quadrigraphs:
Quadrigraphs are replaced at a late stage of the translation process, after m4 is run, so they do not get in the way of M4 quoting. For example, the string ‘^@<:@’, independently of its quotation, appears as ‘^[’ in the output.
The empty quadrigraph can be used:
Trailing spaces are smashed by autom4te. This is a feature.
For instance ‘@<@&t@:@’ produces ‘@<:@’. For a more contrived example:
m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl m4_split([a )}>=- b -=<{( c]) ⇒[a], [], [B], [], [c] m4_split([a )}@&t@>=- b -=<@&t@{( c]) ⇒[a], [)}>=-], [b], [-=<{(], [c]
For instance you might want to mention
AC_FOO in a comment, while
still being sure that autom4te still catches unexpanded
‘AC_*’. Then write ‘AC@&t@_FOO’.
The name ‘@&t@’ was suggested by Paul Eggert:
I should give some credit to the ‘@&t@’ pun. The ‘&’ is my own invention, but the ‘t’ came from the source code of the ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame), and which used ‘mt’ to denote the empty string. In C, it would have looked like something like:char const mt[] = "";
but of course the source code was written in Algol 68.
I don't know where he got ‘mt’ from: it could have been his own invention, and I suppose it could have been a common pun around the Cambridge University computer lab at the time.)
which is incredibly useless since
AC_TRY_LINK is already
double quoting, so you just need:
AC_TRY_LINK( [#include <time.h> #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif], [atoi (*tzname);], [ac_cv_var_tzname=yes], [ac_cv_var_tzname=no])
The M4-fluent reader might note that these two examples are rigorously equivalent, since M4 swallows both the ‘changequote(<<, >>)’ and ‘<<’ ‘>>’ when it collects the arguments: these quotes are not part of the arguments!
Simplified, the example above is just doing this:
changequote(<<, >>)dnl <<[]>> changequote([, ])dnl
instead of simply:
[[]]
With macros that do not double quote their arguments (which is the rule), double-quote the (risky) literals:
AC_LINK_IFELSE([AC_LANG_PROGRAM( [[#include <time.h> #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif]], [atoi (*tzname);])], [ac_cv_var_tzname=yes], [ac_cv_var_tzname=no])
Please note that the macro
AC_TRY_LINK is obsolete, so you really
should be using
AC_LINK_IFELSE instead. may contain
unexpanded macros. The autoconf program checks for this problem
by looking for the string ‘AC_’ in configure. However, this
heuristic does not work in general: for example, it does not catch
overquoting in
AC_DEFINE descriptions.
The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition to Autoconf per se, heavily rely on M4. All these different uses revealed common needs factored into a layer over M4: autom4te5.
autom4te is a preprocessor that is like m4. It supports M4 extensions designed for use in tools like Autoconf.
The command line arguments are modeled after M4's:
autom4te options files
where the files are directly passed to m4. By default, GNU M4 is found during configuration, but the environment variable M4 can be set to tell autom4te where to look. In addition to the regular expansion, it handles the replacement of the quadrigraphs (see Quadrigraphs), and of ‘__oline__’, the current line in the output. It supports an extended syntax for the files:
Of course, it supports the Autoconf common subset of options:Of course, it supports the Autoconf common subset of options:
As an extension of m4, it includes the following options:As an extension of m4, it includes the following options:
AC_DIAGNOSE, for a comprehensive list of categories. Special values include:
Warnings about ‘syntax’ are enabled by default, and the environment variable WARNINGS, a comma separated list of categories, is honored. ‘autom4te -W category’ actually behaves as if you had run:
autom4te --warnings=syntax,$WARNINGS,category
For example, if you want to disable defaults and WARNINGS of autom4te, but enable the warnings about obsolete constructs, you would use -W none,obsolete.
autom4te displays a back trace for errors, but not for
warnings; if you want them, just pass -W error.
.m4fis replaced by file
.m4. This helps tracing the macros which are executed only when the files are frozen, typically
m4_define. For instance, running:
autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
is roughly equivalent to running:
m4 1.m4 2.m4 3.m4 4.m4 input.m4
while
autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
is equivalent to:
m4 --reload-state=4.m4f input.m4
autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
corresponds to
m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f).
Because traces are so important to the GNU Build System, autom4te provides high level tracing features as compared to M4, and helps exploiting the cache:Because traces are so important to the GNU Build System, autom4te provides high level tracing features as compared to M4, and helps exploiting the cache:
The format is a regular string, with newlines if desired, and several special escape codes. It defaults to ‘$f:$l:$n:$%’. It can use the following special escapes:
The escape ‘$%’ produces single-line trace outputs (unless you put newlines in the ‘separator’), while ‘$@’ and ‘$*’ do not.
See autoconf Invocation, for examples of trace uses.
Finally, autom4te introduces the concept of Autom4te libraries. They consists in a powerful yet extremely simple feature: sets of combined command line arguments:Finally, autom4te introduces the concept of Autom4te libraries. They consists in a powerful yet extremely simple feature: sets of combined command line arguments:
M4sugar
M4sh
Autotest
Autoconf-without-aclocal-m4
Autoconf
Autoconf-without-aclocal-m4and additionally reads aclocal.m4.
As an example, if Autoconf is installed in its default location, /usr/local, the command ‘autom4te -l m4sugar foo.m4’ is strictly equivalent to the command:
autom4te --prepend-include /usr/local/share/autoconf \ m4sugar/m4sugar.m4f --warnings syntax foo.m4
Recursive expansion applies here: the command ‘autom4te -l m4sh foo.m4’ is the same as ‘autom"
M4 by itself provides only a small, but sufficient, set of all-purpose macros. M4sugar introduces additional generic macros. Its name was coined by Lars J. Aas: “Readability And Greater Understanding Stands 4 M4sugar”.
M4sugar reserves the macro namespace ‘^_m4_’ for internal use, and the macro namespace ‘^m4_’ for M4sugar macros. You should not define your own macros into these namespaces.
With a few exceptions, all the M4 native macros are moved in the
‘m4_’ pseudo-namespace, e.g., M4sugar renames
define as
m4_define etc.
The list of macros unchanged from M4, except for their name, is:
Some M4 macros are redefined, and are slightly incompatible with their native equivalent.
All M4 macros starting with ‘__’ retain their original name: for example, no
m4__file__is defined.
This is not technically a macro, but a feature of Autom4te. The sequence
__oline__can be used similarly to the other m4sugar location macros, but rather than expanding to the location of the input file, it is translated to the line number where it appears in the output file after all other M4 expansions.
This macro corresponds to
patsubst. The name
m4_patsubstis kept for future versions of M4sugar, once GNU M4 2.0 is released and supports extended regular expression syntax.
This macro corresponds to
regexp. The name
m4_regexpis kept for future versions of M4sugar, once GNU M4 2.0 is released and supports extended regular expression syntax.
These macros aren't directly builtins, but are closely related to
m4_pushdefand
m4_defn.
m4_copyand
m4_renameensure that dest is undefined, while
m4_copy_forceand
m4_rename_forceoverwrite any existing definition. All four macros then proceed to copy the entire pushdef stack of definitions of source over to dest.
m4_copyand
m4_copy_forcepreserve the source (including in the special case where source is undefined), while
m4_renameand
m4_rename_forceundefine the original macro name (making it an error to rename an undefined source).
Note that attempting to invoke a renamed macro might not work, since the macro may have a dependence on helper macros accessed via composition of ‘$0’ but that were not also renamed; likewise, other macros may have a hard-coded dependence on source and could break if source has been deleted. On the other hand, it is always safe to rename a macro to temporarily move it out of the way, then rename it back later to restore original semantics.
This macro fails if macro is not defined, even when using older versions of M4 that did not warn. See
m4_undefine. Unfortunately, in order to support these older versions of M4, there are some situations involving unbalanced quotes where concatenating multiple macros together will work in newer M4 but not in m4sugar; use quadrigraphs to work around this.
M4sugar relies heavily on diversions, so rather than behaving as a primitive,
m4_divertbehaves like:m4_divert_pop()m4_divert_push([diversion])
See Diversion support, for more details about the use of the diversion stack. In particular, this implies that diversion should be a named diversion rather than a raw number. But be aware that it is seldom necessary to explicitly change the diversion stack, and that when done incorrectly, it can lead to syntactically invalid scripts.
m4_dumpdefis like the M4 builtin, except that this version requires at least one argument, output always goes to standard error rather than the current debug file, no sorting is done on multiple arguments, and an error is issued if any name is undefined.
m4_dumpdefsis a convenience macro that calls
m4_dumpdeffor all of the
m4_pushdefstack of definitions, starting with the current, and silently does nothing if name is undefined.
Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a builtin is output as the empty string. This behavior is rectified by using M4 1.6 or newer. However, this behavior difference means that
m4_dumpdefshould only be used while developing m4sugar macros, and never in the final published form of a macro.
Like
m4_esyscmd, this macro expands to the result of running command in a shell. The difference is that any trailing newlines are removed, so that the output behaves more like shell command substitution.
This macro corresponds to
ifelse. string-1 and string-2 are compared literally, so usually one of the two arguments is passed unquoted. See Conditional constructs, for more conditional idioms.
Like the M4 builtins, but warn against multiple inclusions of file.
Posix requires
maketempto replace the trailing ‘X’ characters in template with the process id, without regards to the existence of a file by that name, but this a security hole. When this was pointed out to the Posix folks, they agreed to invent a new macro
mkstempthat always creates a uniquely named file, but not all versions of GNU M4 support the new macro. In M4sugar,
m4_maketempand
m4_mkstempare synonyms for each other, and both have the secure semantics regardless of which macro the underlying M4 provides.
This macro fails if macro is not defined, even when using older versions of M4 that did not warn. See
m4_undefine.
This macro fails if macro is not defined, even when using older versions of M4 that did not warn. Usem4_ifdef([macro], [m4_undefine([macro])])
if you are not sure whether macro is defined.
Unlike the M4 builtin, at least one diversion must be specified. Also, since the M4sugar diversion stack prefers named diversions, the use of
m4_undivertto include files is risky. See Diversion support, for more details about the use of the diversion stack. But be aware that it is seldom necessary to explicitly change the diversion stack, and that when done incorrectly, it can lead to syntactically invalid scripts.
These macros correspond to
m4wrap. Posix requires arguments of multiple wrap calls to be reprocessed at EOF in the same order as the original calls (first-in, first-out). GNU M4 versions through 1.4.10, however, reprocess them in reverse order (last-in, first-out). Both orders are useful, therefore, you can rely on
m4_wrapto provide FIFO semantics and
m4_wrap_lifofor LIFO semantics, regardless of the underlying GNU M4 version.
Unlike the GNU M4 builtin, these macros only recognize one argument, and avoid token pasting between consecutive invocations. On the other hand, nested calls to
m4_wrapfrom within wrapped text work just as in the builtin.])])
Initialize the M4sugar environment, setting up the default named diversion to be
KILL.
The following macros provide additional conditional constructs as
convenience wrappers around
m4_if.
The string string is repeatedly compared against a series of regex arguments; if a match is found, the expansion is the corresponding value, otherwise, the macro moves on to the next regex. If no regex match, then the result is the optional default, or nothing.
The string string is altered by regex-1 and subst-1, as if by:m4_bpatsubst([[string]], [regex], [subst])
The result of the substitution is then passed through the next set of regex and subst, and so forth. An empty subst implies deletion of any matched portions in the current string. Note that this macro over-quotes string; this behavior is intentional, so that the result of each step of the recursion remains as a quoted string. However, it means that anchors (‘^’ and ‘$’ in the regex will line up with the extra quotations, and not the characters of the original string. The overquoting is removed after the final substitution.
Test string against multiple value possibilities, resulting in the first if-value for a match, or in the optional default. This is shorthand for:m4_if([string], [value-1], [if-value-1], [string], [value-2], [if-value-2], ..., [default])
This macro was introduced in Autoconf 2.62. Similar to
m4_if, except that each test is expanded only when it is encountered. This is useful for short-circuiting expensive tests; while
m4_ifrequires all its strings to be expanded up front before doing comparisons,
m4_condonly expands a test when all earlier tests have failed.
For an example, these two sequences give the same result, but in the case where ‘$1’ does not contain a backslash, the
m4_condversion only expands
m4_indexonce, instead of five times, for faster computation if this is a common case for ‘$1’. Notice that every third argument is unquoted for
m4_if, and quoted for
m4_cond:m4_if(m4_index([$1], [\]), [-1], [$2], m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2], m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2], m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3], m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3], [$2]) m4_cond([m4_index([$1], [\])], [-1], [$2], [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2], [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2], [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3], [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3], [$2])
If expr-1 contains text, use it. Otherwise, select expr-2.
m4_defaultexpands the result, while
m4_default_quoteddoes not. Useful for providing a fixed default if the expression that results in expr-1 would otherwise be empty. The difference between
m4_defaultand
m4_default_nblankis whether an argument consisting of just blanks (space, tab, newline) is significant. When using the expanding versions, note that an argument may contain text but still expand to an empty string.m4_define([active], [ACTIVE])dnl m4_define([empty], [])dnl m4_define([demo1], [m4_default([$1], [$2])])dnl m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl demo1([active], [default]) ⇒ACTIVE demo1([], [active]) ⇒ACTIVE demo1([empty], [text]) ⇒ -demo1([ ], [active])- ⇒- - demo2([active], [default]) ⇒active demo2([], [active]) ⇒active demo2([empty], [text]) ⇒empty -demo2([ ], [active])- ⇒- - demo3([active], [default]) ⇒ACTIVE demo3([], [active]) ⇒ACTIVE demo3([empty], [text]) ⇒ -demo3([ ], [active])- ⇒-ACTIVE- demo4([active], [default]) ⇒active demo4([], [active]) ⇒active demo4([empty], [text]) ⇒empty -demo4([ ], [active])- ⇒-active-
If macro does not already have a definition, then define it to default-definition.
If cond is empty or consists only of blanks (space, tab, newline), then expand if-blank; otherwise, expand if-text. Two variants exist, in order to make it easier to select the correct logical sense when using only two parameters. Note that this is more efficient than the equivalent behavior of:m4_ifval(m4_normalize([cond]), if-text, if-blank)
m4_ifdef([macro], [if-defined], [if-not-defined])
If macro is undefined, or is defined as the empty string, expand to if-false. Otherwise, expands to if-true. Similar to:m4_ifval(m4_defn([macro]), [if-true], [if-false])
except that it is not an error if macro is undefined.
Expands to if-true if cond is not empty, otherwise to if-false. This is shorthand for:m4_if([cond], [], [if-false], [if-true])
Similar to
m4_ifval, except guarantee that a newline is present after any non-empty expansion. Often followed by
dnl.
The following macros are useful in implementing recursive algorithms in
M4, including loop operations. An M4 list is formed by quoting a list
of quoted elements; generally the lists are comma-separated, although
m4_foreach_w is whitespace-separated. For example, the list
‘[[a], [b,c]]’ contains two elements: ‘[a]’ and ‘[b,c]’.
It is common to see lists with unquoted elements when those elements are
not likely to be macro names, as in ‘[fputc_unlocked,
fgetc_unlocked]’.
Although not generally recommended, it is possible for quoted lists to have side effects; all side effects are expanded only once, and prior to visiting any list element. On the other hand, the fact that unquoted macros are expanded exactly once means that macros without side effects can be used to generate lists. For example,
m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i]) error-->hi ⇒123 m4_define([list], [[1], [2], [3]]) ⇒ m4_foreach([i], [list], [i]) ⇒123
Extracts argument n (larger than 0) from the remaining arguments. If there are too few arguments, the empty string is used. For any n besides 1, this is more efficient than the similar ‘m4_car(m4_shiftn([n], [], [arg...]))’.
Expands to the quoted first arg. Can be used with
m4_cdrto recursively iterate through a list. Generally, when using quoted lists of quoted elements,
m4_carshould be called without any extra quotes.
Expands to a quoted list of all but the first arg, or the empty string if there was only one argument. Generally, when using quoted lists of quoted elements,
m4_cdrshould be called without any extra quotes.
For example, this is a simple implementation of
m4_map; note how each iteration checks for the end of recursion, then merely applies the first argument to the first element of the list, then repeats with the rest of the list. (The actual implementation in M4sugar is a bit more involved, to gain some speed and share code with
m4_map_sep, and also to avoid expanding side effects in ‘$2’ twice).m4_define([m4_map], [m4_ifval([$2], [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]]) ⇒ 1 2 a
Loop over the numeric values between first and last including bounds by increments of step. For each iteration, expand expression with the numeric value assigned to var. If step is omitted, it defaults to ‘1’ or ‘-1’ depending on the order of the limits. If given, step has to match this order. The number of iterations is determined independently from definition of var; iteration cannot be short-circuited or lengthened by modifying var from within expression.
Loop over the comma-separated M4 list list, assigning each value to var, and expand expression. The following example outputs two lines:m4_foreach([myvar], [[foo], [bar, baz]], [echo myvar ])dnl ⇒echo foo ⇒echo bar, baz
Note that for some forms of expression, it may be faster to use
m4_map_args.
Loop over the white-space-separated list list, assigning each value to var, and expand expression. If var is only referenced once in expression, it is more efficient to use
m4_map_args_w.
The deprecated macro
AC_FOREACHis an alias of
m4_foreach_w.
Loop over the comma separated quoted list of argument descriptions in list, and invoke macro with the arguments. An argument description is in turn a comma-separated quoted list of quoted elements, suitable for
m4_apply. The macros
m4_mapand
m4_map_sepignore empty argument descriptions, while
m4_mapalland
m4_mapall_sepinvoke macro with no arguments. The macros
m4_map_sepand
m4_mapall_sepadditionally expand separator between invocations of macro.
Note that separator is expanded, unlike in
m4_join. When separating output with commas, this means that the map result can be used as a series of arguments, by using a single-quoted comma as separator, or as a single string, by using a double-quoted comma.m4_map([m4_count], []) ⇒ m4_map([ m4_count], [[], [[1]], [[1], [2]]]) ⇒ 1 2 m4_mapall([ m4_count], [[], [[1]], [[1], [2]]]) ⇒ 0 1 2 m4_map_sep([m4_eval], [,], [[[1+2]], [[10], [16]]]) ⇒3,a m4_map_sep([m4_echo], [,], [[[a]], [[b]]]) ⇒a,b m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]])) ⇒2 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]) ⇒a,b m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])) ⇒1
Repeatedly invoke macro with each successive arg as its only argument. In the following example, three solutions are presented with the same expansion; the solution using
m4_map_argsis the most efficient.m4_define([active], [ACTIVE])dnl m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))]) ⇒ plain active m4_map([ m4_echo], [[[plain]], [[active]]]) ⇒ plain active m4_map_args([ m4_echo], [plain], [active]) ⇒ plain active
In cases where it is useful to operate on additional parameters besides the list elements, the macro
m4_currycan be used in macro to supply the argument currying necessary to generate the desired argument list. In the following example,
list_add_nis more efficient than
list_add_x. On the other hand, using
m4_map_args_sepcan be even more efficient.m4_define([list], [[1], [2], [3]])dnl m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl dnl list_add_n(N, ARG...) dnl Output a list consisting of each ARG added to N m4_define([list_add_n], [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@)))])dnl list_add_n([1], list) ⇒2,3,4 list_add_n([2], list) ⇒3,4,5 m4_define([list_add_x], [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@)), [,add([$1],m4_defn([var]))]))])dnl list_add_x([1], list) ⇒2,3,4
For every pair of arguments arg, invoke macro with two arguments. If there is an odd number of arguments, invoke macro-end, which defaults to macro, with the remaining argument.m4_map_args_pair([, m4_reverse], [], [1], [2], [3]) ⇒, 2, 1, 3 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3]) ⇒, 2, 1, [3] m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4]) ⇒, 2, 1, 4, 3
Expand the sequence pre
[arg
]post for each argument, additionally expanding sep between arguments. One common use of this macro is constructing a macro call, where the opening and closing parentheses are split between pre and post; in particular,
m4_map_args([macro
], [arg
])is equivalent to
m4_map_args_sep([macro
(], [)], [], [arg
]). This macro provides the most efficient means for iterating over an arbitrary list of arguments, particularly when repeatedly constructing a macro call with more arguments than arg.
Expand the sequence pre
[word]post for each word in the whitespace-separated string, additionally expanding sep between words. This macro provides the most efficient means for iterating over a whitespace-separated string. In particular,
m4_map_args_w([string
], [action
(], [)])is more efficient than
m4_foreach_w([var], [string
], [action
(m4_defn([var]))]).
m4_shiftnperforms count iterations of
m4_shift, along with validation that enough arguments were passed in to match the shift count, and that the count is positive.
m4_shift2and
m4_shift3are specializations of
m4_shiftn, introduced in Autoconf 2.62, and are more efficient for two and three shifts, respectively.
For each of the
m4_pushdefdefinitions of macro, expand action with the single argument of a definition of macro.
m4_stack_foreachstarts with the oldest definition, while
m4_stack_foreach_lifostarts with the current definition. action should not push or pop definitions of macro, nor is there any guarantee that the current definition of macro matches the argument that was passed to action. The macro
m4_currycan be used if action needs more than one argument, although in that case it is more efficient to use m4_stack_foreach_sep.
Due to technical limitations, there are a few low-level m4sugar functions, such as
m4_pushdef, that cannot be used as the macro argument.m4_pushdef([a], [1])m4_pushdef([a], [2])dnl m4_stack_foreach([a], [ m4_incr]) ⇒ 2 3 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])]) ⇒ cd bcd
Expand the sequence pre
[definition]post for each
m4_pushdefdefinition of macro, additionally expanding sep between definitions.
m4_stack_foreach_sepvisits the oldest definition first, while
m4_stack_foreach_sep_lifovisits the current definition first. This macro provides the most efficient means for iterating over a pushdef stack. In particular,
m4_stack_foreach([macro
], [action
])is short for
m4_stack_foreach_sep([macro
], [action
(], [)]).
The following macros give some control over the order of the evaluation by adding or removing levels of quotes.
Apply the elements of the quoted, comma-separated list as the arguments to macro. If list is empty, invoke macro without arguments. Note the difference between
m4_indir, which expects its first argument to be a macro name but can use names that are otherwise invalid, and
m4_apply, where macro can contain other text, but must end in a valid macro name.m4_apply([m4_count], []) ⇒0 m4_apply([m4_count], [[]]) ⇒1 m4_apply([m4_count], [[1], [2]]) ⇒2 m4_apply([m4_join], [[|], [1], [2]]) ⇒1|2
This macro returns the decimal count of the number of arguments it was passed.
This macro performs argument currying. The expansion of this macro is another macro name that expects exactly one argument; that argument is then appended to the arg list, and then macro is expanded with the resulting argument list.m4_curry([m4_curry], [m4_reverse], [1])([2])([3]) ⇒3, 2, 1
Unfortunately, due to a limitation in M4 1.4.x, it is not possible to pass the definition of a builtin macro as the argument to the output of
m4_curry; the empty string is used instead of the builtin token. This behavior is rectified by using M4 1.6 or newer.
This macro loops over its arguments and expands each arg in sequence. Its main use is for readability; it allows the use of indentation and fewer
dnlto result in the same expansion. This macro guarantees that no expansion will be concatenated with subsequent text; to achieve full concatenation, use
m4_unquote(m4_join([],arg...
)).m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl m4_do([a],[b])c ⇒abc m4_unquote(m4_join([],[a],[b]))c ⇒3 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl m4_do([a],[b])c ⇒ABC m4_unquote(m4_join([],[a],[b]))c ⇒3
Return the arguments as a quoted list of quoted arguments. Conveniently, if there is just one arg, this effectively adds a level of quoting.
Return the arguments as a series of double-quoted arguments. Whereas
m4_dquotereturns a single argument,
m4_dquote_eltreturns as many arguments as it was passed.
Return the arguments, with the same level of quoting. Other than discarding whitespace after unquoted commas, this macro is a no-op.
Return the expansion of arg as a quoted string. Whereas
m4_quoteis designed to collect expanded text into a single argument,
m4_expandis designed to perform one level of expansion on quoted text. One distinction is in the treatment of whitespace following a comma in the original arg. Any time multiple arguments are collected into one with
m4_quote, the M4 argument collection rules discard the whitespace. However, with
m4_expand, whitespace is preserved, even after the expansion of macros contained in arg. Additionally,
m4_expandis able to expand text that would involve an unterminated comment, whereas expanding that same text as the argument to
m4_quoteruns into difficulty in finding the end of the argument. Since manipulating diversions during argument collection is inherently unsafe,
m4_expandissues an error if arg attempts to change the current diversion (see Diversion support).m4_define([active], [ACT, IVE])dnl m4_define([active2], [[ACT, IVE]])dnl m4_quote(active, active) ⇒ACT,IVE,ACT,IVE m4_expand([active, active]) ⇒ACT, IVE, ACT, IVE m4_quote(active2, active2) ⇒ACT, IVE,ACT, IVE m4_expand([active2, active2]) ⇒ACT, IVE, ACT, IVE m4_expand([# m4_echo]) ⇒# m4_echo m4_quote(# m4_echo) ) ⇒# m4_echo) ⇒
Note that
m4_expandcannot handle an arg that expands to literal unbalanced quotes, but that quadrigraphs can be used when unbalanced output is necessary. Likewise, unbalanced parentheses should be supplied with double quoting or a quadrigraph.m4_define([pattern], [[!@<:@]])dnl m4_define([bar], [BAR])dnl m4_expand([case $foo in m4_defn([pattern])@:}@ bar ;; *[)] blah ;; esac]) ⇒case $foo in ⇒ [![]) BAR ;; ⇒ *) blah ;; ⇒esac
This macro was introduced in Autoconf 2.62. Expands to nothing, ignoring all of its arguments. By itself, this isn't very useful. However, it can be used to conditionally ignore an arbitrary number of arguments, by deciding which macro name to apply to a list of arguments.dnl foo outputs a message only if [debug] is defined. m4_define([foo], [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
Note that for earlier versions of Autoconf, the macro
__gnu__can serve the same purpose, although it is less readable.
This macro exists to aid debugging of M4sugar algorithms. Its net effect is similar to
m4_dquote—it produces a quoted list of quoted arguments, for each arg. The difference is that this version uses a comma-newline separator instead of just comma, to improve readability of the list; with the result that it is less efficient than
m4_dquote.m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl m4_dquote(zero, [one], [[two]]) ⇒[0],[one],[[two]] m4_make_list(zero, [one], [[two]]) ⇒[0], ⇒[one], ⇒[[two]] m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number]) ⇒ 0 1 two m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number]) ⇒ 0 1 two
Return the arguments as a single entity, i.e., wrap them into a pair of quotes. This effectively collapses multiple arguments into one, although it loses whitespace after unquoted commas in the process.
Outputs each argument with the same level of quoting, but in reverse order, and with space following each comma for readability.m4_define([active], [ACT,IVE]) ⇒ m4_reverse(active, [active]) ⇒active, IVE, ACT
This macro was introduced in Autoconf 2.62. Expand each argument, separated by commas. For a single arg, this effectively removes a layer of quoting, and
m4_unquote([arg
])is more efficient than the equivalent
m4_do([arg
]). For multiple arguments, this results in an unquoted list of expansions. This is commonly used with
m4_split, in order to convert a single quoted list into a series of quoted elements.
The following example aims at emphasizing the difference between several
scenarios: not using these macros, using
m4_defn, using
m4_quote, using
m4_dquote, and using
m4_expand.
$ cat example.m4 dnl Overquote, so that quotes are visible. m4_define([show], [$[]1 = [$1], $[]@ = [$@]]) m4_define([a], [A]) m4_define([mkargs], [1, 2[,] 3]) m4_define([arg1], [[$1]]) m4_divert([0])dnl show(a, b) show([a, b]) show(m4_quote(a, b)) show(m4_dquote(a, b)) show(m4_expand([a, b])) arg1(mkargs) arg1([mkargs]) arg1(m4_defn([mkargs])) arg1(m4_quote(mkargs)) arg1(m4_dquote(mkargs)) arg1(m4_expand([mkargs])) $ autom4te -l m4sugar example.m4 $1 = A, $@ = [A],[b] $1 = a, b, $@ = [a, b] $1 = A,b, $@ = [A,b] $1 = [A],[b], $@ = [[A],[b]] $1 = A, b, $@ = [A, b] 1 mkargs 1, 2[,] 3 1,2, 3 [1],[2, 3] 1, 2, 3.
Return string with letters converted to upper or lower case, respectively.
The following macros facilitate integer arithmetic operations.
Where a parameter is documented as taking an arithmetic expression, you
can use anything that can be parsed by
m4_eval.
Compare the arithmetic expressions expr-1 and expr-2, and expand to ‘-1’ if expr-1 is smaller, ‘0’ if they are equal, and ‘1’ if expr-1 is larger.
Compare the two M4 lists consisting of comma-separated arithmetic expressions, left to right. Expand to ‘-1’ for the first element pairing where the value from list-1 is smaller, ‘1’ where the value from list-2 is smaller, or ‘0’ if both lists have the same values. If one list is shorter than the other, the remaining elements of the longer list are compared against zero.m4_list_cmp([1, 0], [1]) ⇒0 m4_list_cmp([1, [1 * 0]], [1, 0]) ⇒0 m4_list_cmp([1, 2], [1, 0]) ⇒1 m4_list_cmp([1, [1+1], 3],[1, 2]) ⇒1 m4_list_cmp([1, 2, -3], [1, 2]) ⇒-1 m4_list_cmp([1, 0], [1, 2]) ⇒-1 m4_list_cmp([1], [1, 2]) ⇒-1
This macro was introduced in Autoconf 2.62. Expand to the decimal value of the maximum arithmetic expression among all the arguments.
This macro was introduced in Autoconf 2.62. Expand to the decimal value of the minimum arithmetic expression among all the arguments.
Expand to ‘-1’ if the arithmetic expression expr is negative, ‘1’ if it is positive, and ‘0’ if it is zero.
This macro was introduced in Autoconf 2.53, but had a number of usability limitations that were not lifted until Autoconf 2.62. Compare the version strings version-1 and version-2, and expand to ‘-1’ if version-1 is smaller, ‘0’ if they are the same, or ‘1’ version-2 is smaller. Version strings must be a list of elements separated by ‘.’, ‘,’ or ‘-’, where each element is a number along with optional case-insensitive letters designating beta releases. The comparison stops at the leftmost element that contains a difference, although a 0 element compares equal to a missing element.
It is permissible to include commit identifiers in version, such as an abbreviated SHA1 of the commit, provided there is still a monotonically increasing prefix to allow for accurate version-based comparisons. For example, this paragraph was written when the development snapshot of autoconf claimed to be at version ‘2.61a-248-dc51’, or 248 commits after the 2.61a release, with an abbreviated commit identification of ‘dc51’.m4_version_compare([1.1], [2.0]) ⇒-1 m4_version_compare([2.0b], [2.0a]) ⇒1 m4_version_compare([1.1.1], [1.1.1a]) ⇒-1 m4_version_compare([1.2], [1.1.1a]) ⇒1 m4_version_compare([1.0], [1]) ⇒0 m4_version_compare([1.1pre], [1.1PRE]) ⇒0 m4_version_compare([1.1a], [1,10]) ⇒-1 m4_version_compare([2.61a], [2.61a-248-dc51]) ⇒-1 m4_version_compare([2.61b], [2.61a-248-dc51]) ⇒1
Compares version against the version of Autoconf currently running. If the running version is at version or newer, expand if-new-enough, but if version is larger than the version currently executing, expand if-old, which defaults to printing an error message and exiting m4sugar with status 63. When given only one argument, this behaves like
AC_PREREQ(see Versioning). Remember that the autoconf philosophy favors feature checks over version checks.
Sometimes, it is necessary to track a set of data, where the order does
not matter and where there are no duplicates in the set. The following
macros facilitate set manipulations. Each set is an opaque object,
which can only be accessed via these basic operations. The underlying
implementation guarantees linear scaling for set creation, which is more
efficient than using the quadratic
m4_append_uniq. Both set
names and values can be arbitrary strings, except for unbalanced quotes.
This implementation ties up memory for removed elements until the next
operation that must traverse all the elements of a set; and although
that may slow down some operations until the memory for removed elements
is pruned, it still guarantees linear performance.
Adds the string value as a member of set set. Expand if-uniq if the element was added, or if-dup if it was previously in the set. Operates in amortized constant time, so that set creation scales linearly.
Adds each value to the set set. This is slightly more efficient than repeatedly invoking
m4_set_add.
Expands if-present if the string value is a member of set, otherwise if-absent.m4_set_contains([a], [1], [yes], [no]) ⇒no m4_set_add([a], [1], [added], [dup]) ⇒added m4_set_add([a], [1], [added], [dup]) ⇒dup m4_set_contains([a], [1], [yes], [no]) ⇒yes m4_set_remove([a], [1], [removed], [missing]) ⇒removed m4_set_contains([a], [1], [yes], [no]) ⇒no m4_set_remove([a], [1], [removed], [missing]) ⇒missing
Expands to a single string consisting of all the members of the set set, each separated by sep, which is not expanded.
m4_set_contentsleaves the elements in set but reclaims any memory occupied by removed elements, while
m4_set_dumpis a faster one-shot action that also deletes the set. No provision is made for disambiguating members that contain a non-empty sep as a substring; use
m4_set_emptyto distinguish between an empty set and the set containing only the empty string. The order of the output is unspecified; in the current implementation, part of the speed of
m4_set_dumpresults from using a different output order than
m4_set_contents. These macros scale linearly in the size of the set before memory pruning, and
m4_set_contents([set
], [sep
])is faster than
m4_joinall([sep
]m4_set_listc([set
])).m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_contents([a], [-]) ⇒1-2-3 m4_joinall([-]m4_set_listc([a])) ⇒1-2-3 m4_set_dump([a], [-]) ⇒3-2-1 m4_set_contents([a]) ⇒ m4_set_add([a], []) ⇒ m4_set_contents([a], [-]) ⇒
Delete all elements and memory associated with set. This is linear in the set size, and faster than removing one element at a time.
Compute the relation between seta and setb, and output the result as a list of quoted arguments without duplicates and with a leading comma. Set difference selects the elements in seta but not setb, intersection selects only elements in both sets, and union selects elements in either set. These actions are linear in the sum of the set sizes. The leading comma is necessary to distinguish between no elements and the empty string as the only element.m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_add_all([b], [3], [], [4]) ⇒ m4_set_difference([a], [b]) ⇒,1,2 m4_set_difference([b], [a]) ⇒,,4 m4_set_intersection([a], [b]) ⇒,3 m4_set_union([a], [b]) ⇒,1,2,3,,4
Expand if-empty if the set set has no elements, otherwise expand if-elements. This macro operates in constant time. Using this macro can help disambiguate output from
m4_set_contentsor
m4_set_list.
For each element in the set set, expand action with the macro variable defined as the set element. Behavior is unspecified if action recursively lists the contents of set (although listing other sets is acceptable), or if it modifies the set in any way other than removing the element currently contained in variable. This macro is faster than the corresponding
m4_foreach([variable
], m4_indir([m4_dquote]m4_set_listc([set
])), [action
]), although
m4_set_mapmight be faster still.m4_set_add_all([a]m4_for([i], [1], [5], [], [,i])) ⇒ m4_set_contents([a]) ⇒12345 m4_set_foreach([a], [i], [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])]) ⇒24 m4_set_contents([a]) ⇒135
Produce a list of arguments, where each argument is a quoted element from the set set. The variant
m4_set_listcis unambiguous, by adding a leading comma if there are any set elements, whereas the variant
m4_set_listcannot distinguish between an empty set and a set containing only the empty string. These can be directly used in macros that take multiple arguments, such as
m4_joinor
m4_set_add_all, or wrapped by
m4_dquotefor macros that take a quoted list, such as
m4_mapor
m4_foreach. Any memory occupied by removed elements is reclaimed during these macros.m4_set_add_all([a], [1], [2], [3]) ⇒ m4_set_list([a]) ⇒1,2,3 m4_set_list([b]) ⇒ m4_set_listc([b]) ⇒ m4_count(m4_set_list([b])) ⇒1 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))]) ⇒0 m4_set_add([b], []) ⇒ m4_set_list([b]) ⇒ m4_set_listc([b]) ⇒, m4_count(m4_set_list([b])) ⇒1 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))]) ⇒1
For each element in the set set, expand action with a single argument of the set element. Behavior is unspecified if action recursively lists the contents of set (although listing other sets is acceptable), or if it modifies the set in any way other than removing the element passed as an argument. This macro is faster than either corresponding counterpart of
m4_map_args([action
]m4_set_listc([set
]))or
m4_set_foreach([set
], [var], [action
(m4_defn([var]))]). It is possible to use
m4_curryif more than one argument is needed for action, although it is more efficient to use
m4_set_map_sepin that case.
For each element in the set set, expand pre
[element]post, additionally expanding sep between elements. Behavior is unspecified if the expansion recursively lists the contents of set (although listing other sets is acceptable), or if it modifies the set in any way other than removing the element visited by the expansion. This macro provides the most efficient means for non-destructively visiting the elements of a set; in particular,
m4_set_map([set
], [action
])is equivalent to
m4_set_map_sep([set
], [action
(], [)]).
If value is an element in the set set, then remove it and expand if-present. Otherwise expand if-absent. This macro operates in constant time so that multiple removals will scale linearly rather than quadratically; but when used outside of
m4_set_foreachor
m4_set_map, it leaves memory occupied until the set is later compacted by
m4_set_contentsor
m4_set_list. Several other set operations are then less efficient between the time of element removal and subsequent memory compaction, but still maintain their guaranteed scaling performance.
Expand to the size of the set set. This implementation operates in constant time, and is thus more efficient than
m4_eval(m4_count(m4_set_listc([set])) - 1).
M4sugar provides a means to define suspicious patterns, patterns describing tokens which should not be found in the output. For instance, if an Autoconf configure script includes tokens such as ‘AC_DEFINE’, or ‘dnl’, then most probably something went wrong (typically a macro was not evaluated because of overquotation).
M4sugar forbids all the tokens matching ‘^_?m4_’ and ‘^dnl$’. Additional layers, such as M4sh and Autoconf, add additional forbidden patterns to the list.
Declare that no token matching pattern must be found in the output. Comments are not checked; this can be a problem if, for instance, you have some macro left unexpanded after an ‘#include’. No consensus is currently found in the Autoconf community, as some people consider it should be valid to name macros in comments (which doesn't make sense to the authors of this documentation: input, such as macros, should be documented by ‘dnl’ comments; reserving ‘#’-comments to document the output).
Of course, you might encounter exceptions to these generic rules, for instance you might have to refer to ‘$m4_flags’.
Any token matching pattern is allowed, including if it matches an
m4_pattern_forbidpattern.
At times, it is desirable to see what was happening inside m4, to see
why output was not matching expectations. However, post-processing done
by autom4te means that directly using the m4 builtin
m4_traceon is likely to interfere with operation. Also, frequent
diversion changes and the concept of forbidden tokens make it difficult
to use
m4_defn to generate inline comments in the final output.
There are a couple of tools to help with this. One is the use of the --trace option provided by autom4te (as well as each of the programs that wrap autom4te, such as autoconf), in order to inspect when a macro is called and with which arguments. For example, when this paragraph was written, the autoconf version could be found by:
$ autoconf --trace=AC_INIT configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:[email protected] $ autoconf --trace='AC_INIT:version is $2' version is 2.63b.95-3963
Another trick is to print out the expansion of various m4 expressions to
standard error or to an independent file, with no further m4 expansion,
and without interfering with diversion changes or the post-processing
done to standard output.
m4_errprintn shows a given expression
on standard error. For example, if you want to see the expansion of an
autoconf primitive or of one of your autoconf macros, you can do it like
this:
$ cat <<\EOF > configure.ac AC_INIT m4_errprintn([The definition of AC_DEFINE_UNQUOTED:]) m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED])) AC_OUTPUT EOF $ autoconf error-->The definition of AC_DEFINE_UNQUOTED: error-->_AC_DEFINE_Q([], $@).
M4sh reserves the M4 macro namespace ‘^_AS_’ for internal use, and the namespace ‘^AS_’ for M4sh macros. It also reserves the shell and environment variable namespace ‘^as_’, and the here-document delimiter namespace ‘^_AS[A-Z]’ in the output file. You should not define your own macros or output shell code that conflicts with these namespaces.
M4sh provides portable alternatives for some common shell constructs that unfortunately are not portable in practice.
Expand into shell code that will output text surrounded by a box with char in the top and bottom border. text should not contain a newline, but may contain shell expansions valid for unquoted here-documents. char defaults to ‘-’, but can be any character except ‘/’, ‘'’, ‘"’, ‘\’, ‘&’, or ‘`’. This is useful for outputting a comment box into log files to separate distinct phases of script operation.
Expand into a shell ‘case’ statement, where word is matched against one or more patterns. if-matched is run if the corresponding pattern matched word, else default is run. Avoids several portability issues (see Limitations of Shell Builtins).
Output the directory portion of file-name. For example, if
$fileis ‘/one/two/three’, the command
dir=`AS_DIRNAME(["$file"])`sets
dirto ‘/one/two’.
This interface may be improved in the future to avoid forks and losing trailing newlines.
Emits word to the standard output, followed by a newline. word must be a single shell word (typically a quoted string). The bytes of word are output as-is, even if it starts with "-" or contains "\". Redirections can be placed outside the macro invocation. This is much more portable than using echo (see Limitations of Shell Builtins).
Emits word to the standard output, without a following newline. word must be a single shell word (typically a quoted string) and, for portability, should not include more than one newline. The bytes of word are output as-is, even if it starts with "-" or contains "\". Redirections can be placed outside the macro invocation.
Expands to string, with any characters in chars escaped with a backslash (‘\’). chars should be at most four bytes long, and only contain characters from the set ‘`\"$’; however, characters may be safely listed more than once in chars for the sake of syntax highlighting editors. The current implementation expands string after adding escapes; if string contains macro calls that in turn expand to text needing shell quoting, you can use
AS_ESCAPE(m4_dquote(m4_expand([string]))).
The default for chars (‘\"$`’) is the set of characters needing escapes when string will be used literally within double quotes. One common variant is the set of characters to protect when string will be used literally within back-ticks or an unquoted here-document (‘\$`’). Another common variant is ‘""’, which can be used to form a double-quoted string containing the same expansions that would have occurred if string were expanded in an unquoted here-document; however, when using this variant, care must be taken that string does not use double quotes within complex variable expansions (such as ‘${foo-`echo "hi"`}’) that would be broken with improper escapes.
This macro is often used with
AS_ECHO. For an example, observe the output generated by the shell code generated from this snippet:foo=bar AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"]) ⇒"$foo" = "bar" m4_define([macro], [a, [\b]]) AS_ECHO(["AS_ESCAPE([[macro]])"]) ⇒macro AS_ECHO(["AS_ESCAPE([macro])"]) ⇒a, b AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"]) ⇒a, \b
To escape a string that will be placed within single quotes, use:m4_bpatsubst([[string]], ['], ['\\''])
Emit code to probe whether file is a regular file with executable permissions (and not a directory with search permissions). The caller is responsible for quoting file.
Emit code to exit the shell with status, defaulting to ‘$?’. This macro works around shells that see the exit status of the command prior to
exitinside a ‘trap 0’ handler (see Limitations of Shell Builtins).
Run shell code test1. If test1 exits with a zero status then run shell code run-if-true1, else examine further tests. If no test exits with a zero status, run shell code run-if-false, with simplifications if either run-if-true1 or run-if-false is empty. For example,AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])], [test "x$foo" != xno], [HANDLE_FOO([maybe])], [echo foo not specified])
ensures any required macros of
HANDLE_FOOare expanded before the first test.
Make the directory file-name, including intervening directories as necessary. This is equivalent to ‘mkdir -p -- file-name’, except that it is portable to older versions of mkdir that lack support for the -p option or for the -- delimiter (see Limitations of Usual Tools). Also,
AS_MKDIR_Psucceeds if file-name is a symbolic link to an existing directory, even though Posix is unclear whether ‘mkdir -p’ should succeed in that case. If creation of file-name fails, exit the script.
Also see the
AC_PROG_MKDIR_Pmacro (see Particular Programs).
Emit shell code to set the value of ‘$?’ to status, as efficiently as possible. However, this is not guaranteed to abort a shell running with
set -e(see Limitations of Shell Builtins). This should also be used at the end of a complex shell function instead of ‘return’ (see Shell Functions) to avoid a DJGPP shell bug.
Transform expression into a valid right-hand side for a C
#define. For example:# This outputs "#define HAVE_CHAR_P 1". # Notice the m4 quoting around #, to prevent an m4 comment type="char *" echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
Transform expression into shell code that generates a valid shell variable name. The result is literal when possible at m4 time, but must be used with
evalif expression causes shell indirections. For example:# This outputs "Have it!". header="sys/some file.h" eval AS_TR_SH([HAVE_$header])=yes if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
Set the polymorphic shell variable var to dir/file, but optimizing the common cases (dir or file is ‘.’, file is absolute, etc.).
Unsets the shell variable var, working around bugs in older shells (see Limitations of Shell Builtins). var can be a literal or indirect variable name.
Compare two strings version-1 and version-2, possibly containing shell variables, as version strings, and expand action-if-less, action-if-equal, or action-if-greater depending upon the result. The algorithm to compare is similar to the one used by strverscmp in glibc (see String/Array Comparison).([var], [$1]) echo "$var"], ([t], [var
])and
AS_VAR_SET([var
], ["$t word, execute if-equal; otherwise execute if-not-equal. word must be a single shell word (typically a quoted string)..
Emit a shell statement that results in a successful exit status only if the polymorphic shell variable
varis set.
Set up the shell to be more compatible with the Bourne shell as standardized by Posix, if possible. This may involve setting environment variables, or setting options, or similar implementation-specific actions. This macro is deprecated, since
AS_INITalready invokes it.
Initialize the M4sh environment. This macro calls
m4_init, then outputs the
#! /bin/shline, a notice about where the output was generated from, and code to sanitize the environment for the rest of the script. Among other initializations, this sets SHELL to the shell chosen to run the script (see CONFIG_SHELL), and LC_ALL to ensure the C locale. Finally, it changes the current diversion to
BODY.
AS_INITis called automatically by
AC_INITand
AT_INIT, so shell code in configure, config.status, and testsuite all benefit from a sanitized shell environment.
Emit shell code to start the creation of a subsidiary shell script in file, including changing file to be executable. This macro populates the child script with information learned from the parent (thus, the emitted code is equivalent in effect, but more efficient, than the code output by
AS_INIT,
AS_BOURNE_COMPATIBLE, and
AS_SHELL_SANITIZE). If present, comment is output near the beginning of the child, prior to the shell initialization code, and is subject to parameter expansion, command substitution, and backslash quote removal. The parent script should check the exit status after this macro, in case file could not be properly created (for example, if the disk was full). If successfully created, the parent script can then proceed to append additional M4sh constructs into the child script.
Note that the child script starts life without a log file open, so if the parent script uses logging (see AS_MESSAGE_LOG_FD), you must temporarily disable any attempts to use the log file until after emitting code to open a log within the child. On the other hand, if the parent script has
AS_MESSAGE_FDredirected somewhere besides ‘1’, then the child script already has code that copies stdout to that descriptor. Currently, the suggested idiom for writing a M4sh shell script from within another script is:AS_INIT_GENERATED([file], [[# My child script. ]]) || { AS_ECHO(["Failed to create child script"]); AS_EXIT; } m4_pushdef([AS_MESSAGE_LOG_FD])dnl cat >> "file" <<\__EOF__ # Code to initialize AS_MESSAGE_LOG_FD m4_popdef([AS_MESSAGE_LOG_FD])dnl # Additional code __EOF__
This, however, may change in the future as the M4sh interface is stabilized further.
Also, be aware that use of LINENO within the child script may report line numbers relative to their location in the parent script, even when using
AS_LINENO_PREPARE, if the parent script was unable to locate a shell with working LINENO support.
Find a shell that supports the special variable LINENO, which contains the number of the currently executing line. This macro is automatically invoked by
AC_INITin configure scripts.
Set up variable as_me to be the basename of the currently executing script. This macro is automatically invoked by
AC_INITin configure scripts.
Create, as safely as possible, a temporary sub-directory within dir with a name starting with prefix. prefix should be 2-4 characters, to make it slightly easier to identify the owner of the directory. If dir is omitted, then the value of TMPDIR will be used (defaulting to ‘/tmp’). On success, the name of the newly created directory is stored in the shell variable
tmp. On error, the script is aborted.
Typically, this macro is coupled with some exit traps to delete the created directory and its contents on exit or interrupt. However, there is a slight window between when the directory is created and when the name is actually known to the shell, so an interrupt at the right moment might leave the temporary directory behind. Hence it is important to use a prefix that makes it easier to determine if a leftover temporary directory from an interrupted script is safe to delete.
The use of the output variable ‘$tmp’ rather than something in the ‘as_’ namespace is historical; it has the unfortunate consequence that reusing this otherwise common name for any other purpose inside your script has the potential to break any cleanup traps designed to remove the temporary directory.
Initialize the shell suitably for configure scripts. This has the effect of
AS_BOURNE_COMPATIBLE, and sets some other environment variables for predictable results from configuration tests. For example, it sets LC_ALL to change to the default C locale. See Special Shell Variables. This macro is deprecated, since
AS_INITalready invokes it.
The following macros define file descriptors used to output messages (or input values) from configure scripts. For example:
echo "$wombats found" >&AS_MESSAGE_LOG_FD echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD read kangaroos <&AS_ORIGINAL_STDIN_FD`
However doing so is seldom needed, because Autoconf provides higher level macros as described below.
The file descriptor for ‘checking for...’ messages and results. By default,
AS_INITsets this to ‘1’ for standalone M4sh clients. However,
AC_INITshuffles things around to another file descriptor, in order to allow the -q option of configure to choose whether messages should go to the script's standard output or be discarded.
If you want to display some messages, consider using one of the printing macros (see Printing Messages) instead. Copies of messages output via these macros are also recorded in config.log.
This must either be empty, or expand to a file descriptor for log messages. By default,
AS_INITsets this macro to the empty string for standalone M4sh clients, thus disabling logging. However,
AC_INITshuffles things around so that both configure and config.status use config.log for log messages. Macros that run tools, like
AC_COMPILE_IFELSE(see Running the Compiler), redirect all output to this descriptor. You may want to do so if you develop such a low-level macro.
This must expand to a file descriptor for the original standard input. By default,
AS_INITsets this macro to ‘0’ for standalone M4sh clients. However,
AC_INITshuffles things around for safety.
When configure runs, it may accidentally execute an interactive command that has the same name as the non-interactive meant to be used or checked. If the standard input was the terminal, such interactive programs would cause configure to stop, pending some user input. Therefore configure redirects its standard input from /dev/null during its initialization. This is not normally a problem, since configure normally does not need user input.
In the extreme case where your configure script really needs to obtain some values from the original standard input, you can read them explicitly from
AS_ORIGINAL_STDIN_FD.macro, which is similar to the M4 builtin
m4_definemacro; this creates a macro named name and with body as its expansion. In addition to defining a macro,
AC_DEFUNadds to it some code that is used to constrain the order in which macros are called, while avoiding redundant output (see Prerequisite Macros).
An Autoconf macro definition looks like this:
AC_DEFUN(macro-name, macro-body)
You can refer to any arguments passed to the macro as ‘$1’, ‘$2’, etc. See How to define new macros, for more complete information on writing M4 macros.
Most macros fall in one of two general categories. The first category
includes macros which take arguments, in order to generate output
parameterized by those arguments. Macros in this category are designed
to be directly expanded, often multiple times, and should not be used as
the argument to
AC_REQUIRE. The other category includes macros
which are shorthand for a fixed block of text, and therefore do not take
arguments. For this category of macros, directly expanding the macro
multiple times results in redundant output, so it is more common to use
the macro as the argument to
AC_REQUIRE, or to declare the macro
with
AC_DEFUN_ONCE (see One-Shot]) # -------------------------------------- m4_define([AC_MSG_ERROR], [{ AS_MESSAGE([error: $1], [2]) exit m4_default([$2], [1]); }])
Comments about the macro should be left in the header comment. Most other comments make their way into configure, so just keep using ‘#’ to introduce comments.
If you have some.
Public third-party macros need to use
AC_DEFUN, and not
m4_define, in order to be found by aclocal
(see Extending aclocal).
Additionally, if it is ever determined that a macro should be made
obsolete, it is easy to convert from
AC_DEFUN to
AU_DEFUN
in order to have autoupdate assist the user in choosing a
better alternative, but there is no corresponding way to make
m4_define issue an upgrade notice (see AU_DEFUN).
There is another subtle, but important, difference between using
m4_define and
AC_DEFUN: only the former is unaffected by
AC_REQUIRE. When writing a file, it is always safe to replace a
block of text with a
m4_define macro that will expand to the same
text. But replacing a block of text with an
AC_DEFUN macro with
the same content does not necessarily give the same results, because it
changes the location where any embedded but unsatisfied
AC_REQUIRE invocations within the block will be expanded. For an
example of this, see Expanded Before Required., it is possible to make autoconf detect the problem, and refuse to create configure in the case of an error. The macros in this section are considered obsolescent, and new code should use M4sugar macros for this purpose, see Diagnostic Macros.
On the other hand, it is possible to want to detect errors when configure is run, which are dependent on the environment of the user rather than the maintainer. For dynamic diagnostics, see Printing Messages.
Report message as a warning (or as an error if requested by the user) if warnings of the category are turned on. This macro is obsolescent; you are encouraged to use:m4_warn([category], [message])
instead. See m4_warn, for more details, including valid category names.
Report message as a syntax warning. This macro is obsolescent; you are encouraged to use:m4_warn([syntax], [message])
instead. See m4_warn, for more details, as well as better finer-grained categories of warnings (not all problems have to do with syntax).
Report a severe error message, and have autoconf die. This macro is obsolescent; you are encouraged to use:m4_fatal([message])
instead. See m4_fatal, for more details.
When the user runs ‘autoconf -W error’, warnings from
m4_warn (including those issued through
AC_DIAGNOSE and
AC_WARNING) are reported as errors, see autoconf Invocation..
If the M4 macro macro-name has not already been called, call it (without any arguments). Make sure to quote macro-name with square brackets. macro-name must have been defined using
AC_DEFUNor else contain a call to
AC_PROVIDEto indicate that it has been called.
AC_REQUIREmust be used inside a macro defined by
AC_DEFUN; it must not be called from the top level. Also, it does not make sense to require a macro that takes parameters.
AC_REQUIRE is often misunderstood. It really implements
dependencies between macros in the sense that if one macro depends upon
another, the latter is expanded before the body of the
former. To be more precise, the required macro is expanded before
the outermost defined macro in the current expansion stack.
In particular, ‘AC_REQUIRE([FOO])’ is not replaced with the body of
FOO. For instance, this definition of macros:
AC_DEFUN([TRAVOLTA], [test "$body_temperature_in_celsius" -gt "38" && dance_floor=occupied]) AC_DEFUN([NEWTON_JOHN], [test "x$hair_style" = xcurly && dance_floor=occupied]) AC_DEFUN([RESERVE_DANCE_FLOOR], [if date | grep '^Sat.*pm' >/dev/null 2>&1; then AC_REQUIRE([TRAVOLTA]) AC_REQUIRE([NEWTON_JOHN]) fi])
with this configure.ac
AC_INIT([Dance Manager], [1.0], [[email protected]]) RESERVE_DANCE_FLOOR if test "x$dance_floor" = xoccupied; then AC_MSG_ERROR([cannot pick up here, let's move]) fi
does not leave you with a better chance to meet a kindred soul at other times than Saturday night since it expands into:
test "$body_temperature_in_Celsius" -gt "38" && dance_floor=occupied test "x$hair_style" = xcurly &&
However, this implementation can lead to another class of problems. Consider the case where an outer macro first expands, then indirectly requires, an inner macro:
AC_DEFUN([TESTA], [[echo in A if test -n "$SEEN_A" ; then echo duplicate ; fi SEEN_A=:]]) AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B if test -z "$SEEN_A" ; then echo bug ; fi]]) AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]]) AC_DEFUN([OUTER], [[echo in OUTER] TESTA TESTC]) OUTER
Prior to Autoconf 2.64, the implementation of
AC_REQUIRE
recognized that
TESTB needed to be hoisted prior to the expansion
of
OUTER, but because
TESTA had already been directly
expanded, it failed to hoist
TESTA. Therefore, the expansion of
TESTB occurs prior to its prerequisites, leading to the following
output:
in B bug in OUTER in A in C
Newer Autoconf is smart enough to recognize this situation, and hoists
TESTA even though it has already been expanded, but issues a
syntax warning in the process. This is because the hoisted expansion of
TESTA defeats the purpose of using
AC_REQUIRE to avoid
redundant code, and causes its own set of problems if the hoisted macro
is not idempotent:
in A in B in OUTER in A duplicate in C
The bug is not in Autoconf, but in the macro definitions. If you ever
pass a particular macro name to
AC_REQUIRE, then you are implying
that the macro only needs to be expanded once. But to enforce this,
either the macro must be declared with
AC_DEFUN_ONCE (although
this only helps in Autoconf 2.64 or newer), or all
uses of that macro should be through
AC_REQUIRE; directly
expanding the macro defeats the point of using
AC_REQUIRE to
eliminate redundant expansion. In the example, this rule of thumb was
violated because
TESTB requires
TESTA while
OUTER
directly expands it. One way of fixing the bug is to factor
TESTA into two macros, the portion designed for direct and
repeated use (here, named
TESTA), and the portion designed for
one-shot output and used only inside
AC_REQUIRE (here, named
TESTA_PREREQ). Then, by fixing all clients to use the correct
calling convention according to their needs:
AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]]) AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ if test -n "$SEEN_A" ; then echo duplicate ; fi SEEN_A=:]]) AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B if test -z "$SEEN_A" ; then echo bug ; fi]]) AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]]) AC_DEFUN([OUTER], [[echo in OUTER] TESTA TESTC]) OUTER
the resulting output will then obey all dependency rules and avoid any syntax warnings, whether the script is built with old or new Autoconf versions:
in A_PREREQ in B in OUTER in A in C
The helper macros
AS_IF and
AS_CASE may be used to
enforce expansion of required macros outside of shell conditional
constructs. You are furthermore encouraged, although not required, to
put all
AC_REQUIRE calls.
Make M4 print prints it as a warning, and includes it in the updated configure.ac file.
The details of this macro are hairy: if autoconf encounters an
AU_DEFUNed macro, all macros inside its second argument are expanded as usual. However, when autoupdate is run, only M4 and M4sugar macros are expanded here, while all other macros are disabled and appear literally in the updated configure.ac.
Used if the old-name is to be replaced by a call to new-macro with the same parameters. This happens for example if the macro was renamed..
There are several families of shells, most prominently the Bourne family and the C shell family which are deeply incompatible. If you want to write portable shell scripts, avoid members of the C shell family. The the Shell difference FAQ includes a small history of Posix shells, and a comparison between several of them.
Below we describe some of the members of the Bourne shell family.
To be compatible with Ash 0.2:
foo= false $foo echo "Do not use it: $?" false eval 'echo "Do not use it: $?"'
cat ${FOO=`bar`}
BASH_VERSIONis set. To require Posix compatibility, run ‘set -o posix’. See Bash Posix Mode, for details.
Solaris systems have three variants: /usr/bin/ksh is ‘ksh88’; it is standard on Solaris 2.0 and later. /usr/xpg4/bin/sh is a Posix-compliant variant of ‘ksh88’; it is standard on Solaris 9 and later. /usr/dt/bin/dtksh is ‘ksh93’. Variants that are not standard may be parts of optional packages. There is no extra charge for these packages, but they are not part of a minimal OS install and therefore some installations may not have it.
Starting with Tru64 Version 4.0, the Korn shell /usr/bin/ksh
is also available as /usr/bin/posix/sh. If the environment
variable BIN_SH is set to
xpg4, subsidiary invocations of
the standard shell conform to Posix.
KSH_VERSION, except if invoked as /bin/sh on OpenBSD, and similarly to Bash you can require Posix compatibility by running ‘set -o posix’. Unfortunately, with pdksh 5.2.14 (the latest stable version as of January 2007) Posix mode is buggy and causes pdksh to depart from Posix in at least one respect, see Shell Substitutions.
ZSH_VERSIONis set. By default zsh is not compatible with the Bourne shell: you must execute ‘emulate sh’, and for zsh versions before 3.1.6-dev-18 you must also set
NULLCMDto ‘:’. See Compatibility, for details.
The default Mac OS X sh was originally Zsh; it was changed to Bash in Mac OS X 10.2.
The Korn shell (up to at least version M-12/28/93d) has a bug when invoked on a file whose name does not contain a slash. It first searches for the file's name in PATH, and if found it executes that rather than the original file. For example, assuming there is a binary executable /usr/bin/script in your PATH, the last command in the following example fails because the Korn shell finds /usr/bin/script and refuses to execute it as a shell script:
$ touch xxyzzyz script $ ksh xxyzzyz $ ksh ./script $ ksh script ksh: script: cannot execute
Bash 2.03 has a bug when invoked with the -c option: if the option-argument ends in backslash-newline, Bash incorrectly reports a syntax error. The problem does not occur if a character follows the backslash:
$ $ bash -c 'echo foo \ > ' bash: -c: line 2: syntax error: unexpected end of file $ bash -c 'echo foo \ > ' foo
See Backslash-Newline-Empty, for how this can cause problems in makefiles.
Don't rely on ‘\’ being preserved just because it has no special meaning together with the next symbol. In the native sh on OpenBSD 2.7 ‘\"’ expands to ‘"’ in here-documents with unquoted delimiter. As a general rule, if ‘\\’ expands to ‘\’ use ‘\\’ to get ‘\’.
With OpenBSD 2.7's sh
$ cat <<EOF > \" \\ > EOF " \
and with Bash:
bash-2.04$ cat <<EOF > \" \\ > EOF \" \
Using command substitutions in a here-document that is fed to a shell function is not portable. For example, with Solaris 10 /bin/sh:
$ kitty () { cat; } $ kitty <<EOF > `echo ok` > EOF /tmp/sh199886: cannot open $ echo $? 1
Some shells mishandle large here-documents: for example,
Solaris 10 dtksh and the UnixWare 7.1.1 Posix shell, which are
derived from Korn shell version M-12/28/93d, mishandle braced variable
expansion that crosses a 1024- or 4096-byte buffer boundary
within a here-document. Only the part of the variable name after the boundary
is used. For example,
${variable} could be replaced by the expansion
of
${ble}. If the end of the variable name is aligned with the block
boundary, the shell reports an error, as if you used
${}.
Instead of
${variable-default}, the shell may expand
${riable-default}, or even
${fault}. This bug can often
be worked around by omitting the braces:
$variable. The bug was
fixed in
‘ksh93g’ (1998-04-30) but as of 2006 many operating systems were
still shipping older versions with the bug.
Empty here-documents are not portable either; with the following code, zsh up to at least version 4.3.10 creates a file with a single newline, whereas other shells create an empty file:
cat >file <<EOF EOF
Many shells (including the Bourne shell) implement here-documents inefficiently. In particular, some shells can be extremely inefficient when a single statement contains many here-documents. can take the shell runtime, and we end up not
executing the macro at all.
Be careful with the use of ‘<<-’ to unindent here-documents. The behavior is only portable for stripping leading <TAB>s, and things can silently break if an overzealous editor converts to using leading spaces (not all shells are nice enough to warn about unterminated here-documents).
$ printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done 1 2 done $ printf 'cat <<-x\n 1\n 2\n x\n' | bash-3.2 && echo done 1 2 x done
Most shells, if not all (including Bash, Zsh, Ash), output traces on stderr, even for subshells. This might result in undesirable
One workaround is to grep out uninteresting lines, hoping not to remove good ones.
If you intend to redirect both standard error and standard output, redirect standard output first. This works better with HP-UX, since its shell mishandles tracing if standard error is redirected first:
$ sh -x -c ': 2>err >out' + : + 2> err $ cat err 1> out
Don't try to redirect the standard error of a command substitution. It must be done inside the command substitution. When running ‘: `cd /zorglub` 2>/dev/null’ expect the error message to escape, while ‘: `cd /zorglub 2>/dev/null`’ works properly.
On the other hand, some shells, such as Solaris or FreeBSD /bin/sh, warn about missing programs before performing redirections. Therefore, to silently check whether a program exists, it is necessary to perform redirections on a subshell or brace group:
$ /bin/sh -c 'nosuch 2>/dev/null' nosuch: not found $ /bin/sh -c '(nosuch) 2>/dev/null' $ /bin/sh -c '{ nosuch; } 2>/dev/null' $ bash -c 'nosuch 2>/dev/null'
FreeBSD 6.2 sh may mix the trace output lines from the statements in a shell pipeline.
It is worth noting that Zsh (but not Ash nor Bash) makes it possible in assignments though: ‘foo=`cd /zorglub` 2>/dev/null’.
Some shells, like ash, don't recognize bi-directional redirection (‘<>’). And even on shells that recognize it, it is not portable to use on fifos: Posix does not require read-write support for named pipes, and Cygwin does not support it:
$ mkfifo fifo $ exec 5<>fifo $ echo hi >&5 bash: echo: write error: Communication error on send
Furthermore, versions of dash before 0.5.6 mistakenly truncate regular files when using ‘<>’:
$ echo a > file $ bash -c ': 1<>file'; cat file a $ dash -c ': 1<>file'; cat file $ rm a
When catering to old systems, don't redirect the same file descriptor several times, ‘matter’ and void being empty. However, this bug is probably not of practical concern to modern platforms.
Solaris 10 sh will try to optimize away a : command (even if it is redirected) in a loop after the first iteration, or in a shell function after the first call:
$ for i in 1 2 3 ; do : >x$i; done $ ls x* x1 $ f () { : >$1; }; f y1; f y2; f y3; $ ls y* y1
As a workaround, echo or eval can be used.
Don't rely on file descriptors 0, 1, and 2 remaining closed in a subsidiary program. If any of these descriptors is closed, the operating system may open an unspecified file for the descriptor in the new process image. Posix 2008 says this may be done only if the subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does it even for ordinary programs, and the next version of Posix will allow HP-UX behavior.
If you want a file descriptor above 2 to be inherited into a child process, then you must use redirections specific to that command or a containing subshell or command group, rather than relying on exec in the shell. In ksh as well as HP-UX sh, file descriptors above 2 which are opened using ‘exec n>file’ are closed by a subsequent ‘exec’ (such as that involved in the fork-and-exec which runs a program or script):
$ echo 'echo hello >&5' >k $ /bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t hello $ bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t hello $ ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t ./k[1]: 5: cannot open [Bad file number] $ ksh -c '(ksh ./k) 5>t; cat t' hello $ ksh -c '{ ksh ./k; } 5>t; cat t' hello $ ksh -c '5>t ksh ./k; cat t hello
Don't rely on duplicating a closed file descriptor to cause an error. With Solaris /bin/sh, failed duplication is silently ignored, which can cause unintended leaks to the original file descriptor. In this example, observe the leak to standard output:
$ bash -c 'echo hi >&3' 3>&-; echo $? bash: 3: Bad file descriptor 1 $ /bin/sh -c 'echo hi >&3' 3>&-; echo $? hi 0
Fortunately, an attempt to close an already closed file descriptor will portably succeed. Likewise, it is safe to use either style of ‘n<&-’ or ‘n>&-’ for closing a file descriptor, even if it doesn't match the read/write mode that the file descriptor was opened with.
DOS variants cannot rename or remove open files, such as in ‘mv foo bar >foo’ or ‘rm foo >foo’, even though this is perfectly portable among Posix hosts.
A few ancient systems reserved some file descriptors. By convention, file descriptor 3 was opened to /dev/tty when you logged into Eighth Edition (1985) through Tenth Edition Unix (1989). File descriptor 4 had a special use on the Stardent/Kubota Titan (circa 1990), though we don't now remember what it was. Both these systems are obsolete, so it's now safe to treat file descriptors 3 and 4 like any other file descriptors.
On the other hand, you can't portably use multi-digit file descriptors. Solaris ksh doesn't understand any file descriptor larger than ‘9’:
$ bash -c 'exec 10>&-'; echo $? 0 $ ksh -c 'exec 9>&-'; echo $? 0 $ ksh -c 'exec 10>&-'; echo $? ksh[1]: exec: 10: not found 127
Portable handling of signals within the shell is another major source of headaches. This is worsened by the fact that various different, mutually incompatible approaches are possible in this area, each with its distinctive merits and demerits. A detailed description of these possible approaches, as well as of their pros and cons, can be found in this article.
Solaris 10 /bin/sh automatically traps most signals by default; the shell still exits with error upon termination by one of those signals, but in such a case the exit status might be somewhat unexpected (even if allowed by POSIX, strictly speaking):
$ bash -c 'kill -1 $$'; echo $? # Will exit 128 + (signal number). Hangup 129 $ /bin/ksh -c 'kill -15 $$'; echo $? # Likewise. Terminated 143 $ for sig in 1 2 3 15; do > echo $sig: > /bin/sh -c "kill -$s \$\$"; echo $? > done signal 1: Hangup 129 signal 2: 208 signal 3: 208 signal 15: 208
This gets even worse if one is using the POSIX `wait' interface to get details about the shell process terminations: it will result in the shell having exited normally, rather than by receiving a signal.
$ cat > foo.c <<'END' #include <stdio.h> /* for printf */ #include <stdlib.h> /* for system */ #include <sys/wait.h> /* for WIF* macros */ int main(void) { int status = system ("kill -15 $$"); printf ("Terminated by signal: %s\n", WIFSIGNALED (status) ? "yes" : "no"); printf ("Exited normally: %s\n", WIFEXITED (status) ? "yes" : "no"); return 0; } END $ cc -o foo foo.c $ ./a.out # On GNU/Linux Terminated by signal: no Exited normally: yes $ ./a.out # On Solaris 10 Terminated by signal: yes Exited normally: no
Various shells seem to handle
SIGQUIT specially: they ignore it even
if it is not blocked, and even if the shell is not running interactively
(in fact, even if the shell has no attached tty); among these shells
are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
/bin/ksh and
/usr/xpg4/bin/sh, and AT&T
ksh93 (2011).
Still,
SIGQUIT seems to be trappable quite portably within all
these shells. OTOH, some other shells doesn't special-case the handling
of
SIGQUIT; among these shells are at least
pdksh 5.2.14,
Solaris 10 and NetBSD 5.1
/bin/sh, and the Almquist Shell 0.5.5.1.
Some shells (especially Korn shells and derivatives) might try to
propagate to themselves a signal that has killed a child process; this is
not a bug, but a conscious design choice (although its overall value might
be debatable). The exact details of how this is attained vary from shell
to shell. For example, upon running
perl -e 'kill 2, $$', after
the perl process has been interrupted AT&T
ksh93 (2011) will
proceed to send itself a
SIGINT, while Solaris 10
/bin/ksh
and
/usr/xpg4/bin/sh will proceed to exit with status 130 (i.e.,
128 + 2). In any case, if there is an active trap associated with
SIGINT, those shells will correctly execute it.
Some Korn shells, when a child process die due receiving a signal with
signal number n, can leave in ‘$?’ an exit status of
256+n instead of the more common 128+n. Observe the
difference between AT&T
ksh93 (2011) and
bash 4.1.5 on
Debian:
$ /bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?' /bin/ksh: line 1: 7837: Hangup 257 $ /bin/bash -c 'sh -c "kill -1 \$\$"; echo $?' /bin/bash: line 1: 7861 Hangup (sh -c "kill -1 \$\$") 129
This ksh behavior is allowed by POSIX, if implemented with due care; see this Austin Group discussion for more background. However, if it is not implemented with proper care, such a behavior might cause problems in some corner cases. To see why, assume we have a “wrapper” script like this:
#!/bin/sh # Ignore some signals in the shell only, not in its child processes. trap : 1 2 13 15 wrapped_command "$@" ret=$? other_command exit $ret
If wrapped_command is interrupted by a
SIGHUP (which
has signal number 1),
ret will be set to 257. Unless the
exit shell builtin is smart enough to understand that such
a value can only have originated from a signal, and adjust the final
wait status of the shell appropriately, the value 257 will just get
truncated to 1 by the closing
exit call, so that a caller of
the script will have no way to determine that termination by a signal
was involved. Observe the different behavior of AT&T
ksh93
(2011) and
bash 4.1.5 on Debian:
$ cat foo.sh #!/bin/sh sh -c 'kill -1 $$' ret=$? echo $ret exit $ret $ /bin/ksh foo.sh; echo $? foo.sh: line 2: 12479: Hangup 257 1 $ /bin/bash foo.sh; echo $? foo.sh: line 2: 12487 Hangup (sh -c 'kill -1 $$') 129 129
Autoconf uses shell-script processing extensively, so the file names that it processes should not contain characters that are special to the shell. Special characters include space, tab, newline, NUL, and the following:
" # $ & ' ( ) * ; < = > ? [ \ ` |
Also, file names should not begin with ‘~’ or ‘-’, and should contain neither ‘-’ immediately after ‘/’ nor ‘~’ immediately after ‘:’. On Posix-like platforms, directory names should not contain ‘:’, as this runs afoul of ‘:’ used as the path separator.
These restrictions apply not only to the files that you distribute, but also to the absolute file names of your source, build, and destination directories.
On some Posix-like platforms, ‘!’ and ‘^’ are special too, so they should be avoided.
Posix lets implementations treat leading // specially, but requires leading /// and beyond to be equivalent to /. Most Unix variants treat // like /. However, some treat // as a “super-root” that can provide access to files that are not otherwise reachable from /. The super-root tradition began with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin has revived it.
While autoconf and friends are usually run on some Posix variety, they can be used on other systems, most notably DOS variants. This impacts several assumptions regarding file names.
For example, the following code:
case $foo_dir in /*) # Absolute ;; *) foo_dir=$dots$foo_dir ;; esac
fails to properly detect absolute file names on those systems, because they can use a drivespec, and usually use a backslash as directory separator. If you want to be portable to DOS variants (at the price of rejecting valid but oddball Posix file names like a:\b), you can check for absolute file names like this:
case $foo_dir in [\\/]* | ?:[\\/]* ) # Absolute ;; *) foo_dir=$dots$foo_dir ;; esac
Make sure you quote the brackets if appropriate and keep the backslash as first character (see Limitations of Shell Builtins).
Also, because the colon is used as part of a drivespec, these systems don't
use it as path separator. When creating or accessing paths, you can use the
PATH_SEPARATOR output variable instead. configure sets this
to the appropriate value for the build system (‘:’ or ‘;’) when it
starts up.
File names need extra care as well. While DOS variants that are Posixy enough to run autoconf (such as DJGPP) are usually able to handle long file names properly, there are still limitations that can seriously break packages. Several of these issues can be easily detected by the doschk package.
A short overview follows; problems are marked with SFN/LFN to indicate where they apply: SFN means the issues are only relevant to plain DOS, not to DOS under Microsoft Windows variants, while LFN identifies problems that exist even under Microsoft Windows variants.
This is perfectly OK on Posix variants:
AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([source.c foo.bar]) AC_OUTPUT
but it causes problems on DOS, as it requires ‘config.h.in’, ‘source.c.in’ and ‘foo.bar.in’. To make your package more portable to DOS-based environments, you should use this instead:
AC_CONFIG_HEADERS([config.h:config.hin]) AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in]) AC_OUTPUT
The 8+3 limit is not usually a problem under Microsoft Windows, as it
uses numeric
tails in the short version of file names to make them unique. However, a
registry setting can turn this behavior off. While this makes it
possible to share file trees containing long file names between SFN
and LFN environments, it also means the above problem applies there
as well.
Nowadays portable patterns can use negated character classes like ‘[!-aeiou]’. The older syntax ‘[^-aeiou]’ is supported by some shells but not others; hence portable scripts should never use ‘^’ as the first character of a bracket pattern.
Outside the C locale, patterns like ‘[a-z]’ are problematic since they may match characters that are not lower-case letters.
Contrary to a persistent urban legend, the Bourne shell does not
systematically split variables and back-quoted
"`..."..."...`",
for example Solaris 10 ksh:
$ foo="`echo " bar" | sed 's, ,,'`" ksh: : cannot execute ksh: bar | sed 's, ,,': cannot execute
Posix does not specify behavior for this sequence. On the other hand,
behavior for
"`...\"...\"...`" is specified by Posix,
but in practice, not all shells understand it the same way: pdksh 5.2.14
prints spurious quotes when in Posix mode:
$ echo "`echo \"hello\"`" hello $ set -o posix $ echo "`echo \"hello\"`" "hello"
There is just no portable way to use double-quoted strings inside double-quoted back-quoted expressions (pfew!).
Bash 4.1 has a bug where quoted empty strings adjacent to unquoted parameter expansions are elided during word splitting. Meanwhile, zsh does not perform word splitting except when in Bourne compatibility mode. In the example below, the correct behavior is to have five arguments to the function, and exactly two spaces on either side of the middle ‘-’, since word splitting collapses multiple spaces in ‘$f’ but leaves empty arguments intact.
$ bash -c 'n() { echo "$#$@"; }; f=" - "; n - ""$f"" -' 3- - - $ ksh -c 'n() { echo "$#$@"; }; f=" - "; n - ""$f"" -' 5- - - $ zsh -c 'n() { echo "$#$@"; }; f=" - "; n - ""$f"" -' 3- - - $ zsh -c 'emulate sh; > n() { echo "$#$@"; }; f=" - "; n - ""$f"" -' 5- - -
You can work around this by doing manual word splitting, such as using ‘"$str" $list’ rather than ‘"$str"$list’.
There are also portability pitfalls with particular expansions:
$@
The traditional way to work around this portability problem is to use ‘${1+"$@"}’. Unfortunately this method does not work with Zsh (3.x and 4.x), which is used on Mac OS X. When emulating the Bourne shell, Zsh performs word splitting on ‘${1+"$@"}’:
zsh $ emulate sh zsh $ for i in "$@"; do echo $i; done Hello World ! zsh $ for i in ${1+"$@"}; do echo $i; done Hello World !
Zsh handles plain ‘"$@"’ properly, but we can't use plain ‘"$@"’ because of the portability problems mentioned above. One workaround relies on Zsh's “global aliases” to convert ‘${1+"$@"}’ into ‘"$@"’ by itself:
test "${ZSH_VERSION+set}" = set && alias -g '${1+"$@"}'='"$@"'
Zsh only recognizes this alias when a shell word matches it exactly; ‘"foo"${1+"$@"}’ remains subject to word splitting. Since this case always yields at least one shell word, use plain ‘"$@"’.
A more conservative workaround is to avoid ‘"$@"’ if it is possible that there may be no positional arguments. For example, instead of:
cat conftest.c "$@"
you can use this instead:
case $# in 0) cat conftest.c;; *) cat conftest.c "$@";; esac
Autoconf macros often use the set command to update
‘$@’, so if you are writing shell code intended for
configure you should not assume that the value of ‘$@’
persists for any length of time.
${10}
shift. The 7th Edition shell reported an error if given
${10}, and Solaris 10 /bin/sh still acts that way:
$ set 1 2 3 4 5 6 7 8 9 10 $ echo ${10} bad substitution
Conversely, not all shells obey the Posix rule that when braces are omitted, multiple digits beyond a ‘$’ imply the single-digit positional parameter expansion concatenated with the remaining literal digits. To work around the issue, you must use braces.
$ bash -c 'set a b c d e f g h i j; echo $10 ${1}0' a0 a0 $ dash -c 'set a b c d e f g h i j; echo $10 ${1}0' j a0
${var
:-value
}
sh, don't accept the colon for any shell substitution, and complain and die. Similarly for ${var:=value}, ${var:?value}, etc. However, all shells that support functions allow the use of colon in shell substitution, and since m4sh requires functions, you can portably use null variable substitution patterns in configure scripts.
${var
+value
}
$ /bin/sh -c 'echo ${a-b c}' /bin/sh: bad substitution $ /bin/sh -c 'echo ${a-'\''b c'\''}' b c $ /bin/sh -c 'echo "${a-b c}"' b c $ /bin/sh -c 'cat <<EOF ${a-b c} EOF b c
According to Posix, if an expansion occurs inside double quotes, then the use of unquoted double quotes within value is unspecified, and any single quotes become literal characters; in that case, escaping must be done with backslash. Likewise, the use of unquoted here-documents is a case where double quotes have unspecified results:
$ /bin/sh -c 'echo "${a-"b c"}"' /bin/sh: bad substitution $ ksh -c 'echo "${a-"b c"}"' b c $ bash -c 'echo "${a-"b c"}"' b c $ /bin/sh -c 'a=; echo ${a+'\''b c'\''}' b c $ /bin/sh -c 'a=; echo "${a+'\''b c'\''}"' 'b c' $ /bin/sh -c 'a=; echo "${a+\"b c\"}"' "b c" $ /bin/sh -c 'a=; echo "${a+b c}"' b c $ /bin/sh -c 'cat <<EOF ${a-"b c"} EOF' "b c" $ /bin/sh -c 'cat <<EOF ${a-'b c'} EOF' 'b c' $ bash -c 'cat <<EOF ${a-"b c"} EOF' b c $ bash -c 'cat <<EOF ${a-'b c'} EOF' 'b c'
Perhaps the easiest way to work around quoting issues in a manner portable to all shells is to place the results in a temporary variable, then use ‘$t’ as the value, rather than trying to inline the expression needing quoting.
$ /bin/sh -c 't="b c\"'\''}\\"; echo "${a-$t}"' b c"'}\ $ ksh -c 't="b c\"'\''}\\"; echo "${a-$t}"' b c"'}\ $ bash -c 't="b c\"'\''}\\"; echo "${a-$t}"' b c"'}\
${var
=value
}
$ time bash -c ': "${a=/usr/bin/*}"; echo "$a"' /usr/bin/* real 0m0.005s user 0m0.002s sys 0m0.003s $ time bash -c ': ${a=/usr/bin/*}; echo "$a"' /usr/bin/* real 0m0.039s user 0m0.026s sys 0m0.009s $ time bash -c 'a=/usr/bin/*; : ${a=noglob}; echo "$a"' /usr/bin/* real 0m0.031s user 0m0.020s sys 0m0.010s $ time bash -c 'a=/usr/bin/*; : "${a=noglob}"; echo "$a"' /usr/bin/* real 0m0.006s user 0m0.002s sys 0m0.003s
As with ‘+’ and ‘-’, you must use quotes when using ‘=’ if the value contains more than one shell word; either single quotes for just the value, or double quotes around the entire expansion:
$ : ${var1='Some words'} $ : "${var2=like this}" $ echo $var1 $var2 Some words like this
otherwise some shells, such as Solaris /bin/sh or on Digital Unix V 5.0, die because of a “bad substitution”. Meanwhile, Posix requires that with ‘=’, quote removal happens prior to the assignment, and the expansion be the final contents of var without quoting (and thus subject to field splitting), in contrast to the behavior with ‘-’ passing the quoting through to the final expansion. However, bash 4.1 does not obey this rule.
$ ksh -c 'echo ${var-a\ \ b}' a b $ ksh -c 'echo ${var=a\ \ b}' a b $ bash -c 'echo ${var=a\ \ b}' a b
Finally, Posix states that when mixing ‘${a=b}’ with regular commands, it is unspecified whether the assignments affect the parent shell environment. It is best to perform assignments independently from commands, to avoid the problems demonstrated in this example:
$ bash -c 'x= y=${x:=b} sh -c "echo +\$x+\$y+";echo -$x-' +b+b+ -b- $ /bin/sh -c 'x= y=${x:=b} sh -c "echo +\$x+\$y+";echo -$x-' ++b+ -- $ ksh -c 'x= y=${x:=b} sh -c "echo +\$x+\$y+";echo -$x-' +b+b+ --
${var
=value
}
$ unset foo $ foo=${foo='}'} $ echo $foo } $ foo=${foo='}' # no error; this hints to what the bug is $ echo $foo } $ foo=${foo='}'} $ echo $foo }} ^ ugh!
It seems that ‘}’ is interpreted as matching ‘${’, even
though it is enclosed in single quotes. The problem doesn't happen
using double quotes, or when using a temporary variable holding the
problematic string.
${var
=expanded-value
}
default="yu,yaa" : ${var="$default"}
sets var to ‘M-yM-uM-,M-yM-aM-a’, i.e., the 8th bit of each char is set. You don't observe the phenomenon using a simple ‘echo $var’ since apparently the shell resets the 8th bit when it expands $var. Here are two means to make this shell confess its sins:
$ cat -v <<EOF $var EOF
and
$ set | grep '^var=' | cat -v
One classic incarnation of this bug is:
default="a b c" : ${list="$default"} for c in $list; do echo $c done
You'll get ‘a b c’ on a single line. Why? Because there are no spaces in ‘$list’: there are ‘M- ’, i.e., spaces with the 8th bit set, hence no IFS splitting is performed!!!
One piece of good news is that Ultrix works fine with ‘: $ ‘}’ bug from Solaris (see above). For safety, use:
test "${var+set}" = set || var={value}
${#var
}
${var
%word
}
${var
%%word
}
${var
#word
}
${var
##word
}
Also, pdksh 5.2.14 mishandles some word forms. For
example if ‘$1’ is ‘a/b’ and ‘$2’ is ‘a’, then
‘${1#$2}’ should yield ‘/b’, but with pdksh it
yields the empty string.
`commands
`
While in general it makes no sense, do not substitute a single builtin with side effects, because Ash 0.2, trying to optimize, does not fork a subshell to perform the command.
For instance, if you wanted to check that cd is silent, do not use ‘test -z "`cd /`"’ because the following can happen:
$ pwd /tmp $ test -z "`cd /`" && pwd /
The result of ‘foo=`exit 1`’ is left as an exercise to the reader.
The MSYS shell leaves a stray byte in the expansion of a double-quoted command substitution of a native program, if the end of the substitution is not aligned with the end of the double quote. This may be worked around by inserting another pair of quotes:
$ echo "`printf 'foo\r\n'` bar" > broken $ echo "`printf 'foo\r\n'`"" bar" | cmp - broken - broken differ: char 4, line 1
Upon interrupt or SIGTERM, some shells may abort a command substitution, replace it with a null string, and wrongly evaluate the enclosing command before entering the trap or ending the script. This can lead to spurious errors:
$ sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi' $ ^C sh: test: hi: unexpected operator/operand
You can avoid this by assigning the command substitution to a temporary variable:
$ sh -c 'res=`sleep 5; echo hi` if test "x$res" = xhi; then echo yes; fi' $ ^C
$(commands
)
`commands
`.
This construct can be nested while this is impossible to do portably with back quotes. Unfortunately it is not yet universally supported. Most notably, even recent releases of Solaris don't support it:
$ showrev -c /bin/sh | grep version Command version: SunOS 5.10 Generic 121005-03 Oct 2006 $ echo $(echo blah) syntax error: `(' unexpected
nor does IRIX 6.5's Bourne shell:
$ uname -a IRIX firebird-image 6.5 07151432 IP22 $ echo $(echo blah) $(echo blah)
If you do use ‘$(commands)’, make sure that the commands do not start with a parenthesis, as that would cause confusion with a different notation ‘$((expression))’ that in modern shells is an arithmetic expression not a command. To avoid the confusion, insert a space between the two opening parentheses.
Avoid commands that contain unbalanced parentheses in here-documents, comments, or case statement patterns, as many shells mishandle them. For example, Bash 3.1, ‘ksh88’, pdksh 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
echo $(case x in x) echo hello;; esac)
$((expression
))
Among shells that do support ‘$(( ))’, not all of them obey the Posix rule that octal and hexadecimal constants must be recognized:
$ bash -c 'echo $(( 010 + 0x10 ))' 24 $ zsh -c 'echo $(( 010 + 0x10 ))' 26 $ zsh -c 'emulate sh; echo $(( 010 + 0x10 ))' 24 $ pdksh -c 'echo $(( 010 + 0x10 ))' pdksh: 010 + 0x10 : bad number `0x10' $ pdksh -c 'echo $(( 010 ))' 10
When it is available, using arithmetic expansion provides a noticeable
speedup in script execution; but testing for support requires
eval to avoid syntax errors. The following construct is used
by
AS_VAR_ARITH to provide arithmetic computation when all
arguments are provided in decimal and without a leading zero, and all
operators are properly quoted and appear as distinct arguments:
if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then eval 'func_arith () { func_arith_result=$(( $* )) }' else func_arith () { func_arith_result=`expr "$@"` } fi func_arith 1 + 1 foo=$func_arith_result
^
When setting several variables in a row, be aware that the order of the evaluation is undefined. For instance ‘foo=1 foo=2; echo $foo’ gives ‘1’ with Solaris /bin/sh, but ‘2’ with Bash. You must use ‘;’ to enforce the order: ‘foo=1; foo=2; echo $foo’.
Don't rely on the following to find subdir/program:
PATH=subdir$PATH_SEPARATOR$PATH program
as this does not work with Zsh 3.0.6. Use something like this instead:
(PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)="has a '}'"
In most cases ‘var=${var="$default"}’ is fine, but in case of doubt, just use the last form. See Shell Substitutions, items ‘${var:-value}’ and ‘${var=value}’ for the rationale.
Beware of two opening parentheses in a row, as many shell implementations treat them specially, and Posix says that a portable script cannot use ‘((’ outside the ‘$((’ form used for shell arithmetic. In traditional shells, ‘((cat))’ behaves like ‘(cat)’; but many shells, including Bash and the Korn shell, treat ‘((cat))’ as an arithmetic expression equivalent to ‘let "cat"’, and may or may not report an error when they detect that ‘cat’ is not a number. As another example, ‘pdksh’ 5.2.14 does not treat the following code as a traditional shell would:
if ((true) || false); then echo ok fi
To work around this problem, insert a space between the two opening parentheses. There is a similar problem and workaround with ‘$((’; see Shell Substitutions.
Unpatched Tru64 5.1 sh omits the last slash of command-line arguments that contain two trailing slashes:
$ echo / // /// //// .// //. / / // /// ./ //. $ x=// $ eval "echo \$x" / $ set -x $ echo abc | tr -t ab // + echo abc + tr -t ab / /bc
Unpatched Tru64 4.0 sh adds a slash after ‘"$var"’ if the variable is empty and the second double-quote is followed by a word that begins and ends with slash:
$ sh -xc 'p=; echo "$p"/ouch/' p= + echo //ouch/ //ouch/
However, our understanding is that patches are available, so perhaps it's not worth worrying about working around these horrendous bugs.
Some shell variables should not be used, since they can have a deep influence on the behavior of the shell. In order to recover a sane behavior from the shell, some variables should be unset; M4sh takes care of this and provides fallback values, whenever needed, to cater for a very old /bin/sh that does not support unset. (see Portable Shell Programming).
As a general rule, shell variable names containing a lower-case letter
are safe; you can define and use these variables without worrying about
their effect on the underlying system, and without worrying about
whether the shell changes them unexpectedly. (The exception is the
shell variable
status, as described below.)
Here is a list of names that are known to cause trouble. This list is
not exhaustive, but you should be safe if you avoid the name
status and names containing only upper-case letters and
underscores.
?
$ bash -c 'false; $empty; echo $?' 0 $ zsh -c 'false; $empty; echo $?' 1
_
BIN_SH
xpg4, subsidiary invocations of the standard shell conform to Posix.
CDPATH
cdwith a relative file name that did not start with ‘./’ or ‘../’. Posix 1003.1-2001 says that if a nonempty directory name from CDPATH is used successfully,
cdprints the resulting absolute file name. Unfortunately this output can break idioms like ‘abs=`cd src && pwd`’ because
absreceives the name twice. Also, many shells do not conform to this part of Posix; for example, zsh prints the result only if a directory name other than . was chosen from CDPATH.
In practice the shells that have this problem also support unset, so you can work around the problem as follows:
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
You can also avoid output by ensuring that your directory name is absolute or anchored at ‘./’, as in ‘abs=`cd ./src && pwd`’.
Configure scripts use M4sh, which automatically unsets CDPATH if
possible, so you need not worry about this problem in those scripts.
CLICOLOR_FORCE
DUALCASE
ENV
MAILPATH
PS1
PS2
PS4
(unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH ' PS4='+ '
(actually, there is some complication due to bugs in unset;
see Limitations of Shell Builtins).
FPATH
GREP_OPTIONS
IFS
Don't set the first character of IFS to backslash. Indeed, Bourne shells use the first character (backslash) when joining the components in ‘"$@"’ and some shells then reinterpret (!) the backslash escapes, so you can end up with backspace and other strange characters.
The proper value for IFS (in regular code, not when performing splits) is ‘<SPC><TAB><RET>’. The first character is especially important, as it is used to join the arguments in ‘$*’; however, note that traditional shells, but also bash-2.04, fail to adhere to this and join with a space anyway.
M4sh guarantees that IFS will have the default value at the beginning of a script, and many macros within autoconf rely on this setting. It is okay to use blocks of shell code that temporarily change the value of IFS in order to split on another character, but remember to restore it before expanding further macros.
Unsetting
IFS instead of resetting it to the default sequence
is not suggested, since code that tries to save and restore the
variable's value will incorrectly reset it to an empty value, thus
disabling field splitting:
unset IFS # default separators used for field splitting save_IFS=$IFS IFS=: # ... IFS=$save_IFS # no field splitting performed
LANG
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MESSAGES
LC_MONETARY
LC_NUMERIC
LC_TIME
LANGUAGE
LC_ADDRESS
LC_IDENTIFICATION
LC_MEASUREMENT
LC_NAME
LC_PAPER
LC_TELEPHONE
LINENO
LINENO. Its value is the line number of the beginning of the current command. M4sh, and hence Autoconf, attempts to execute configure with a shell that supports
LINENO. If no such shell is available, it attempts to implement
LINENOwith a Sed prepass that replaces each instance of the string
$LINENO(not followed by an alphanumeric character) with the line's number. In M4sh scripts you should execute
AS_LINENO_PREPAREso that these workarounds are included in your script; configure scripts do this automatically in
AC_INIT.
You should not rely on
LINENO within eval or shell
functions, as the behavior differs in practice. The presence of a
quoted newline within simple commands can alter which line number is
used as the starting point for
$LINENO substitutions within that
command. Also, the possibility of the Sed prepass means that you should
not rely on
$LINENO when quoted, when in here-documents, or when
line continuations are used. Subshells should be OK, though. In the
following example, lines 1, 9, and 14 are portable, but the other
instances of
$LINENO do not have deterministic values:
$ cat lineno echo 1. $LINENO echo "2. $LINENO 3. $LINENO" cat <<EOF 5. $LINENO 6. $LINENO 7. \$LINENO EOF ( echo 9. $LINENO ) eval 'echo 10. $LINENO' eval 'echo 11. $LINENO echo 12. $LINENO' echo 13. '$LINENO' echo 14. $LINENO ' 15.' $LINENO f () { echo $1 $LINENO; echo $1 $LINENO } f 18. echo 19. \ $LINENO $ bash-3.2 ./lineno 1. 1 2. 3 3. 3 5. 4 6. 4 7. $LINENO 9. 9 10. 10 11. 12 12. 13 13. $LINENO 14. 14 15. 14 18. 16 18. 17 19. 19 $ zsh-4.3.4 ./lineno 1. 1 2. 2 3. 2 5. 4 6. 4 7. $LINENO 9. 9 10. 1 11. 1 12. 2 13. $LINENO 14. 14 15. 14 18. 0 18. 1 19. 19 $ pdksh-5.2.14 ./lineno 1. 1 2. 2 3. 2 5. 4 6. 4 7. $LINENO 9. 9 10. 0 11. 0 12. 0 13. $LINENO 14. 14 15. 14 18. 16 18. 17 19. 19 $ sed '=' <lineno | > sed ' > N > s,$,-, > t loop > :loop > s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3, > t loop > s,-$,, > s,^[0-9]*\n,, > ' | > sh 1. 1 2. 2 3. 3 5. 5 6. 6 7. \7 9. 9 10. 10 11. 11 12. 12 13. 13 14. 14 15. 15 18. 16 18. 17 19. 20
In particular, note that config.status (and any other subsidiary
script created by
AS_INIT_GENERATED) might report line numbers
relative to the parent script as a result of the potential Sed pass.
NULLCMD
options
emulate sh, so it should not be used.
PATH_SEPARATOR
PATH_SEPARATOR.
POSIXLY_CORRECT
$ bash --posix -c 'set -o | grep posix > unset POSIXLY_CORRECT > set -o | grep posix' posix on posix off
PWD
RANDOM
RANDOM, a variable that returns a different integer each time it is used. Most of the time, its value does not change when it is not used, but on IRIX 6.5 the value changes all the time. This can be observed by using set. It is common practice to use
$RANDOMas part of a file name, but code shouldn't rely on
$RANDOMexpanding to a nonempty string.
status
zsh(at least 3.1.6), hence read-only. Do not use it.
Nowadays, it is difficult to find a shell that does not support shell functions at all. However, some differences should be expected.
When declaring a shell function, you must include whitespace between the ‘)’ after the function name and the start of the compound expression, to avoid upsetting ksh. While it is possible to use any compound command, most scripts use ‘{...}’.
$ /bin/sh -c 'a(){ echo hi;}; a' hi $ ksh -c 'a(){ echo hi;}; a' ksh: syntax error at line 1: `}' unexpected $ ksh -c 'a() { echo hi;}; a' hi Limitations of Shell Builtins.. For more detailed descriptions, see awk language history. or
ENVIRON variables.. AIX 5.3
cp -Rmay corrupt its own memory with some directory hierarchies and error out or dump core:
mkdir -p 12345678/12345678/12345678/12345678 touch 12345678/12345678/x cp -R 12345678 t cp: 0653-440 12345678/12345678/: name too long.os
|
https://www.gnu.org/software/libtool/manual/autoconf.html
|
CC-MAIN-2015-32
|
refinedweb
| 42,442 | 55.34 |
Im currently working with an Mpeg7 xml file and want to preform some 'selections' via. xpath.
However im a bit confused about the namespace applied to the elements in the xml file.
Here is the beginning of the xml file:
<?xml-stylesheet type="text/xsl" href="18.xsl"?>
<Mpeg7 xmlns="urn:mpeg:mpeg7:schema:2001" xmlns:
<!-- ================================= CONTENT DESCRIPTION ================================================= -->
<Description xsi:
<!-- ************** MOVIE NUMBER 1 ************************ -->
<CreationInformation>
<Creation>
.....
...
..
Im not an expert at all but if i remember correct and xmlns without any prefix sets the default namespace which scope applies to all sub / descendent elements. So if elements are declared without any prefix they should belong to the default namespace which of couse dont have any prefix.
However in the mpeg7 xml file example it seem to be a little different. The Mpeg7 element declares a default namespace plus some others.
All the elements (such as Mpeg, Description, CreationInformation, Creation ...) within the Mpeg7 element (which sets all the namespaces) are not declared with any prefix and should belong to the default prefix.
So first when I wanted to make an xpath i did /Mpeg7/Description/CreationInformation but what happend ?? nothing. By trial and error I discovered that for some reason all these elements belong to the mpeg7 namespace. So for the Xpath to work i must do /mpeg7:Mpeg7/mpeg7escription/mpeg7:CreationInformation
Can anyone tell me how the mpeg7 namespace is connected to the elements that have not been declared with an mpeg7:Element prefix ??
Edit: if u want to see the full xml file u can se it here
Last edited by onkelsatan; 05-23-2006 at 08:20 AM.
Figured it out me self.
the default and mpeg7 namespace have the same URI which apparently make them the same thing.
Yup. Just to clarify though: When you declare a default namespace on an element, only elements that element and descendants of that element default to the namespace provided if no namespace prefix has been used. It doesn't mean that default namespace is applied to any element in the document. It is common to specify a default namespace on the document element, but you can declare them on any element.
I'm thuper, thanks for asking.
It lives! (Well it kinda' does anyway).
My portable colour selection tool
There are currently 1 users browsing this thread. (0 members and 1 guests)
Forum Rules
|
http://www.webdeveloper.com/forum/showthread.php?107539-Mpeg7-xml-and-namespace
|
CC-MAIN-2014-52
|
refinedweb
| 393 | 65.42 |
SEGV in online backup API
(1) By hgarrereyn on 2021-09-02 04:04:55 [link] [source]
The following test case crashes with a SEGV (read) when compiling with ASAN:
Sqlite3 version: 3.36.0 (using the amalgamation sqlite3.c)
#include "sqlite3.h" int main() { sqlite3 *d1; sqlite3 *d2; sqlite3 *d3; sqlite3_open(":memory:", &d1); sqlite3_open(":memory:", &d2); sqlite3_open(":memory:", &d3); sqlite3_backup *b1 = sqlite3_backup_init(d3, "main", d2, "main"); sqlite3_backup *b2 = sqlite3_backup_init(d1, "main", d3, "main"); sqlite3_backup *b3 = sqlite3_backup_init(d1, "main", d2, "main"); sqlite3_backup_step(b1, 8388608); sqlite3_backup_finish(b1); sqlite3_backup_step(b2, 0); sqlite3_backup_finish(b3); sqlite3_backup_step(b2, 8421376); // SEGV on read sqlite3_backup_finish(b2); sqlite3_close(d1); sqlite3_close(d2); sqlite3_close(d3); }
This is not a security vulnerability because it an impractical situation. However, this usage of the API seems to be allowed by the documentation.
Specifically, the API doesn't mention what should happen if there are multiple simultaneous backups happening. Since there is some amount of error handling safeguards in place when performing backups, perhaps this situation should throw an error instead of segfaulting?
(2) By Dan Kennedy (dan) on 2021-09-02 06:32:44 in reply to 1 [source]
Thanks for reporting this. An assert() fails in debug mode too.
I think this test case is expected to malfunction. See the second paragraph under "Concurrent Usage of Database Handles" here:
As you say, we should be able to avoid the segfault though.
Dan.
(3) By J.M. Aranda (JMAranda) on 2021-09-02 11:14:30 in reply to 2 [link] [source]
What is that thread safe? Sometimes you have to impose good practices. Or limit the bad ones.
|
https://sqlite.org/forum/forumpost/0707e1405207992b
|
CC-MAIN-2022-21
|
refinedweb
| 266 | 64.2 |
30681/concern-and-cross-cutting-concern.
Hope this helps!
Enroll in Spring course online to learn more about it.
Thanks!
Below are the various advices available in AOP:
Before: These types ...READ MORE
You can use this method:
String[] strs = ...READ MORE
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteFiles{
...READ MORE
Whenever you require to explore the constructor ...READ MORE
You can go to maven repositories ...READ MORE
Some of the Spring annotations that I ...READ MORE
To solve your ERROR, I would suggest ...READ MORE
You don't need @EnableJpaRepositories because your package ...READ MORE
By default, Annotation wiring is not turned ...READ MORE
Configuration metadata can be provided to Spring container in ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.
|
https://www.edureka.co/community/30681/concern-and-cross-cutting-concern-in-spring-aop?show=53573
|
CC-MAIN-2022-27
|
refinedweb
| 154 | 63.36 |
In this tutorial series, we will be exploring the basic concepts of singly-linked lists through the implementation of key methods from the List interface including add(elem), add(index, elem), set(index, elem), get(index), get(elem), remove(index), remove(elem), and indexOf(elem), as well as hitting on certain points for doubly and circularly-linked lists.
Let's start out by examining a basic Linked Node. It looks simple enough, and in reality, the individual nodes aren't that complex. When dealing with singly-linked list, the Node previous doesn't come into play. It becomes more important however, when working with doubly and circularly-linked lists.
public class Node<E>{ E elem; Node<E> next, previous; }
So let's start defining our LinkedList class. So far, we see only 3 Nodes and a constructor. As we covered earlier, the head node is the first element in the list and the tail node is the last. The temp node, however, will come in handy when we have to iterate through our list. Lastly, we use the counter field to store the number of elements contained in the list so as to make the size() method more efficient, with an O(1) vs. an O(n) if the counter field wasn't used.
public class LinkedList<E>{ private Node<E> head = null; private Node<E> tail = null; private Node<E> temp = null; private int counter = 0; public LinkedList(){} public int size(){return counter;} }
The add(elem) method
When dealing with the individual methods() of LinkedLists, it is helpful to think of them in relation to only two or
three Nodes- the one being affected, the one before it (applicable only to doubly and circularly linked lists) and
the one after it.
As we can see, the add() method, which simply appends an element to the end of the list, is pretty
straight-forwardfor a singly-linked list. We simply add the element and update the tail node so that the new node is at the end of the list.
public void add(E elem){ //if we don't have any elems in our LinkedList if(head == null){ head = tail = new Node<E>(); head.elem = elem; head.next = tail; tail = head; } else{ tail.next = new Node<E>(); //add a new node to the end of the list tail = tail.next; //set the tail pointer to that node tail.elem = elem; //set elem to be stored to the end node } counter++; }
Consider this- In a doubly-linked list, you would have to also deal with making sure the impacted Nodes are adjusted for not only pointing to the next element in the list, but the previous element as well. How would you accomplish this, and how might it impact runtime?
The add(index, elem) methodThis method is designed to add the specified element at a given position in the list. When working with arrays, this is pretty straight-forward. However, with LinkedLists this becomes more complicated. Due to the nature of LinkedLists, there is no efficient indexing system. Instead, you have to iterate the collection to find the position for which to add the element. From there, it becomes the same concept as the add(elem) above though you have to deal with the new element being sandwiched between two other nodes instead of at the end. Let's try it:
public void add(int index, E elem){ /*If the user wants to add it to the end of the list call the other add() method, which is more efficient and then end this method*/ if(index == size()){ add(elem); return; } else if(index == 0){ Node<E> temp = new Node<E>(); temp.elem = elem; temp.next = head; head.previous = temp; head = temp; counter++; return; } /*Here, we start to see the temp node come into play. We use it to track the current node without modifying the head node. */ temp = head; for(int i = 0; i < index-1; i++) temp = temp.next; //move to the next node Node<E> myNode = new Node<E>(); //create a new node myNode.elem = elem; //and set the elem myNode.next = temp.next; //set it to point to the next elem temp.next = myNode; //set the previous elem to point to it counter++; //increment the count; }
Consider this- In a singly-linked list, we must start at the beginning and work forward. However, this becomes a problem if the index is closer to the end of the list, then why do we need to start at the beginning of the list? Wouldn't be more efficient to start at the end? With doubly-linked lists, we keep track of the previous as well as the next Nodes, so we can start at the tail of the list and work backwards.
The get(index) method
This method is similar to the add(index, elem) method in the sense that we have to iterate through the LinkedList to return the proper element. Unlike arrays, LinkedLists do not allow for an easy method of indexing. So let's give it a try:
public E get(int index){ //forces the index to be valid assert (index >= 0 && index < size()); temp = head; //start at the head of the list //iterate to the correct node for(int i = 0; i < index; i++) temp = temp.next; return temp.elem; //and return the corresponding element }
The get(elem) and indexOf(elem) methods
This method works identically to the indexOf(elem) method, which we will cover in this section as well. In fact, we will make a call to indexOf(elem) when the get(elem) method is called. In a nutshell, the indexOf(elem) method uses the same process of iteration throughout the list as do the above methods.
So let's start off with these methods
//returns first index of the given elem //returns -1 if elem not found public int get(E elem){ return indexOf(elem); } public int indexOf(E elem){ temp = head; //start at the beginning of the list int i = 0; //create a counter field that isn't local to a loop //while we haven't found the elem we are looking for, keep looking for(; !(temp.element).equals(elem) && temp != null; i++) temp = temp.next; if(i == size()) return -1; //if the elem wasn't found, return -1 return i; //otherwise, return the index }
The remove(index) and remove(elem) methods
If you look back to the add(index, elem) methods, then you will see that when we added elements to the list, we had to make sure we adjusted the pointer of the previous Node to point to the new element, and we had to make the new element point to the next Node. The remove() methods work in the exact opposite manner. Instead of correcting the pointers to account for an extra Node, we want the pointers to act as though it didn't exist.
So let's get started with the remove methods:
public E remove(int index){ assert(index >= 0 && index < size()); //force valid index temp = head; //start at the beginning of the list if(index == 0){ E elem = head.elem; head = head.next; counter--; return elem; } else if(index == size()){ E elem = tail.elem; tail = tail.previous; counter--; return elem; } //iterate to the position before the index for(int i = 0; i < index-1; i++) temp = temp.next; Node<E> two = temp.next; //set temp.next to point to the Node next to the Node to be removed temp.next = two.next; E elem = two.elem; //store the element to return two = null; //remove the node counter--; //decrement size return elem; //return the element at that position } public E remove(E elem){ temp = head; //start at the beginning of the list Node<E> two = null; if(head.elem.equals(elem)){ head = head.next; head.previous = null; counter--; return elem; } else if(tail.elem.equals(elem)){ tail = tail.previous; tail.next = null; counter--; return elem; } //while the elem hasn't been found but there is another node while(temp != null && !temp.elem.equals(elem)){ two = temp; //have a reference to the element before the one to remove temp = temp.next; //in this method, temp will be the elem to remove } //if the element wasn't found, return null if(temp == null) return null; two.next = temp.next; E spare = temp.elem; //return element temp = null; counter--; //decrement size return spare; }
Consider this- How could we improve the efficiency by using a doubly-linked list? For the remove(index) method, we could start at the end of the list and iterate backwards. This would improve the average-case efficiency of the remove(index) method to O(n/4) instead of O(n/2).
Consider this- How would the remove() methods be affected when implementing a circularly-linked list? What would we have to factor in when removing the head or tail elements? We would actually be able to use basically the same process as removing an non-end element in a singly or doubly-linked list.
|
http://www.dreamincode.net/forums/topic/143089-linked-list-tutorial/
|
CC-MAIN-2013-20
|
refinedweb
| 1,498 | 70.13 |
Subject: Re: [boost] "Simple C++11 metaprogramming"
From: Peter Dimov (lists_at_[hidden])
Date: 2015-06-02 06:42:36
Bruno Dutra wrote:
> Still, laziness and SFINAE friendliness are the properties I deem most
> fundamental on any metaprogramming library.
I meant to respond to these points too.
The eagerness of template aliases is an obvious problem in at least one
place and that place is mp_if, where the naive mp_if<P<T>, F<T>, G<T>>
evaluates both F<T> and G<T>. But I'm not sure if there are others, under
the assumption that we've no higher-order constructs. Eric Niebler's meta
has an entire lazy:: namespace with deferred copies of all its constructs;
continuing the general theme, I wonder whether all this is strictly needed
once we jettison the lambda part.
SFINAE friendliness can be quite a curse. It often transforms reasonably
comprehensible error messages into full-scale Agatha Christie mysteries (the
compiler output even being of comparable length). So I'm not convinced (at
the moment) that a metaprogramming library should be SFINAE-friendly. I
presently tend to lean towards the philosophy of static_assert'ing as much
as possible, and leaving the primary templates undefined instead of empty.
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/2015/06/223006.php
|
CC-MAIN-2019-47
|
refinedweb
| 225 | 55.95 |
( 'control 'layout' 'Widget\site-packages\PyQt4\py.
(For more resources on Python, see here.)
Connecting the widgets
In the earlier section, the Python source code representing UI was automatically generated using the pyuic4 script. This, however, only has the widgets defined and placed in a nice layout. We need to teach these widgets what they should do when a certain event occurs. To do this, QT's slots and signals will be used. A signal is emitted when a particular GUI event occurs. For example, when the user clicks on the OK button, internally, a clicked() signal is emitted. A slot is a function that is called when a particular signal is emitted. Thus, in this example, it will call a specified method, whenever the OK button is clicked.
Time for action – connecting the widgets
You will notice several different widgets in the dialog. For example, the field which accepts the input image path or the output directory path is a QLineEdit. The widget where image format is specified is a QCombobox. On similar lines, the OK and Cancel buttons are QPushButton. As an exercise, you can open up the thumbnailMaker.ui file and click on each element to see the associated QT class from the Property Editor.
With this, let's learn how the widgets are connected.
- Open the file ThumbnailMakerDialog.py. The _connect method of class ThumbnailMakerDialog is copied. The method is called in the constructor of this class.
def _connect(self):
"""
Connect slots with signals.
"""
self.connect(self._dialog.inputFileDialogButton,
SIGNAL("clicked()"), self._openFileDialog)
self.connect(self._dialog.outputLocationDialogButton,
SIGNAL("clicked()"), self._outputLocationPath)
self.connect(self._dialog.okPushButton,
SIGNAL("clicked()"), self._processImage)
self.connect(self._dialog.closePushButton,
SIGNAL("clicked()"), self.close)
self.connect(self._dialog.aspectRatioCheckBox,
SIGNAL('stateChanged(int)'),
self._aspectRatioOptionChanged)
- self._dialog is an instance of class Ui_ThumbnailMakerDialog.self.connect is the inherited method of Qt class QDialog. Here, it takes the following arguments (QObject, signal, callable), where QObject is any widget type (all inherit QObject), signal is the QT SIGNAL that tells us about what event occurred and callable is any method handling this event.
- For example, consider the highlighted lines of the code snippet. They connect the OK button to a method that handles image processing. The first argument , self._dialog.okPushButton refers to the button widget defined in class Ui_ThumbnailMakerDialog. Referring to QPushButton documentation, you will find there is a "clicked()" signal that it can emit. The second argument SIGNAL("clicked()") tells Qt that we want to know when that button is clicked by the user. The third argument is the method self._processImage that gets called when this signal is emitted.
- Similarly, you can review the other connections in this method. Each of these connects a widget to a method of the class ThumbnailMakerDialog.
What just happened?
We reviewed ThumbnailMakerDialog._connect() method to understand how the UI elements are connected to various internal methods. The previous two sections helped us learn some preliminary concepts of GUI programming using QT.
Developing the image processing code
The previous sections were intended to get ourselves familiar with the application as an end user and to understand some basic aspects of the GUI elements in the application. With all necessary pieces together, let's focus our attention on the class that does all the main image processing in the application.
The class ThumbnailMaker handles the pure image processing code. It defines various methods to achieve this. For example, the class methods such as _rotateImage, _makeThumbnail, and _resizeImage manipulate the given image to accomplish rotation, thumbnail generation, and resizing respectively. This class accepts input from ThumbnailMakerDialog. Thus, no QT related UI code is required here. If you want to use some other GUI framework to process input, you can do that easily. Just make sure to implement the public API methods defined in class ThumbnailMakerDialog, as those are used by the ThumbnailMaker class.
Time for action – developing image processing code
Thus, with ThumbnailMakerDialog at your disposal, you can develop your own code in scratch, in class ThumbnailMaker. Just make sure to implement the method processImage as this is the only method called by ThumbnailMakerDialog.
Let's develop some important methods of class ThumbnailMaker.
- Write the constructor for class ThumbnailMaker. It takes dialog as an argument. In the constructor, we only initialize self._dialog, which is an instance of class ThumbnailMakerDialog. Here is the code.
def __init__(self, dialog):
"""
Constructor for class ThumbnailMaker.
"""
# This dialog can be an instance of
# ThumbnailMakerDialog class. Alternatively, if
# you have some other way to process input,
# it will be that class. Just make sure to implement
# the public API methods defined in
# ThumbnailMakerDialog class!
self._dialog = dialog
- Next, write the processImage method in class ThumbnailMaker. The code is as follows:
Note: You can download the file ThumbnailMaker.py from Packt website. The code written is from this file. The only difference is that some code comments are removed here.
1 def processImage(self):
2 filePath = self._dialog.getInputImagePath()
3 imageFile = Image.open(filePath)
4
5 if self._dialog.maintainAspectRatio:
6 resizedImage = self._makeThumbnail(imageFile)
7 else:
8 resizedImage = self._resizeImage(imageFile)
9
10 rotatedImage = self._rotateImage(resizedImage)
11
12 fullPath = self._dialog.getOutImagePath()
13
14 # Finally save the image.
15 rotatedImage.save(fullPath)
- On line 2, it gets the full path of the input image file. Note that it relies on self._dialog to provide this information.
- Then the image file is opened the usual way. On line 4, it checks a flag that decides whether or not to process the image by maintaining the aspect ratio. Accordingly, _makeThumbnail or _resizeImage methods are called.
- On line 10, it rotates the image resized earlier, using the _rotateImage method.
- Finally, on line 15, the processed image is saved at a path obtained from the getOutImagePath method of class ThumbnailMakerDialog.
- We will now write the _makeThumbnail method.
1 def _makeThumbnail(self, imageFile):
2 foo = imageFile.copy()
3 size = self._dialog.getSize()
4 imageFilter = self._getImageFilter()
5 foo.thumbnail(size, imageFilter)
6 return foo
- First a copy of the original image is made. We will manipulate this copy and the method will return it for further processing.
- Then the necessary parameters such as the image dimension and filter for re-sampling are obtained from self._dialog and _getImageFilter respectively.
- Finally the thumbnail is created on line 5 and then method returns this image instance.
- We have already discussed how to resize and rotate image. The related code is straightforward to write and the readers are suggested to write it as an exercise. You will need to review the code from file ThumbnailMakerDialog.py for getting appropriate parameters. Write remaining routines namely, _resizeImage, _rotateImage and _getImageFilter.
- Once all methods are in place, run the code from the command line as
python Thumbnailmaker.py
- It should show our application dialog. Play around with it to make sure everything works!
(For more resources on Python, see here.)
What just happened?
In the previous section, we completed an exciting project. Several things learned in the previous article Python Image Manipulation, such as image I/O, resizing and so on, were applied in the project. We developed a GUI application where some basic image manipulation features, such as creating thumbnails, were implemented. This project also helped us gain some insight into various aspects of GUI programming using QT.
Have a go hero – enhance the ThumbnailMaker application
Want to do something more with the Thumbnail Maker. Here you go! As you will add more features to this application, the first thing you would need to do is to change its name—at least from the caption of the dialog that pops up! Edit the thumbnailMaker.ui file in QT designer, change the name to something like "Image Processor", and recreate the corresponding .py file. Next, add the following features to this application.
If you don't want to deal with any UI code, that is fine too! You can write a class similar to ThumbnailMakerDialog. Do the input argument processing in your own way. All that class ThumbnailMaker requires is implementation of certain public methods in this new class, to get various input parameters.
- Accept output filename from the user. Currently, it gives the same name as the input file.
Edit the .ui file. You would need to break the layouts before adding a QLineEdit and its QLabel and then recreate the layouts.
- If there is a previously created output image file in the output directory, clicking OK would simply overwrite that file. Add a checkbox reading, "Overwrite existing file (if any)". If the checkbox in deselected, it should pop up a warning dialog and exit.
For the latter part, there is a commented out code block in ThumbnailMakerDialog._processImage. Just enable the code.
- Add a feature that can add specified text in the lower-left corner of the output image.
- Create an image with this text, and use the combination of crop and paste to achieve desired results. For user input, you will need to add a new QLineEdit for accepting text input and then connect signals with a callable method in ThumbnailMakerDialog._connect.
Summary
We created an interesting project implementing some image processing functionality.
Further resources on this subject:
- Python Image Manipulation [Article]
- Python 3 Object Oriented Programming [Book]
- Objects in Python [Article]
- Python 3: When to Use Object-oriented Programming [Article]
- Python 3 Object Oriented Programming: Managing objects [Article]
|
https://www.packtpub.com/books/content/python-multimedia-application-thumbnail-maker
|
CC-MAIN-2016-40
|
refinedweb
| 1,560 | 51.75 |
getfsent()
Get the next entry from the filesystem table (/etc/fstab) file
Synopsis:
#include <fstab.h> struct fstab * getfsent(void);
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The getfsent() function gets the next entry from the filesystem table file, /etc/fstab.
The fstab structure
The getfsent(), getfsfile() , and getfsspec() functions return pointers to a fstab structure, which is defined as follows:
struct fstab { char *fs_spec; char *fs_file; char *fs_vfstype; char *fs_mntops; char *fs_type; int init_flags; int init_mask; };
The members include:
-.
Classification:
Caveats:
The functions that work with /etc/fstab use static data storage; if you need the data for future use, copy it before any subsequent calls overwrite it.
|
http://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/g/getfsent.html
|
CC-MAIN-2019-22
|
refinedweb
| 123 | 59.94 |
enyo.Model, when you
fetch, it doesn't seem to call the
parsefunction ever, even with
options: {parse: true}
fetched: function (opts, res, source) { var idx; if (this._waiting) { idx = this._waiting.findIndex(function (ln) { return (ln instanceof Source ? ln.name : ln) == source; }); if (idx > -1) this._waiting.splice(idx, 1); if (!this._waiting.length) this._waiting = null; } // ensure we have an options hash and it knows it was just fetched opts = opts ? opts : {}; opts.fetched = true; // note this will not add the DIRTY state because it was fetched but also note that it // will not clear the DIRTY flag if it was already DIRTY if (res) this.set(res, opts); // clear the FETCHING and NEW state (if it was NEW) we do not set it as dirty as this // action alone doesn't warrant a dirty flag that would need to be set in the set method if (!this._waiting) this.status = this.status & ~(STATES.FETCHING | STATES.NEW); // now look for an additional success callback if (opts && opts.success) opts.success(this, opts, res, source); },
So no where in there it checks if the results need to be parsed.So no where in there it checks if the results need to be parsed.
set: function (path, is, opts) { if (!this.destroyed) { var attrs = this.attributes, options = this.options, changed, incoming, force, silent, key, value, commit, fetched; // the default case for this setter is accepting an object of key->value pairs // to apply to the model in which case the second parameter is the optional // configuration hash if (typeof path == 'object') { incoming = path; opts = opts || is; } // otherwise in order to have a single path here we flub it so it will keep on // going as expected else { incoming = {}; incoming[path] = is; } // to maintain backward compatibility with the old setters that allowed the third // parameter to be a boolean to indicate whether or not to force notification of // change even if there was any if (opts === true) { force = true; opts = {}; } opts = opts ? enyo.mixin({}, [options, opts]) : options; silent = opts.silent; force = force || opts.force; commit = opts.commit; fetched = opts.fetched; for (key in incoming) { value = incoming[key]; if (value !== attrs[key] || force) { // to ensure we have an object to work with // note that we check inside this loop so we don't have to examine keys // later only the local variable changed changed = this.changed || (this.changed = {}); changed[key] = attrs[key] = value; } } if (changed) { // we add dirty as a value of the status but clear the CLEAN bit if it // was set - this would allow it to be in the ERROR state and NEW and DIRTY if (!fetched) this.status = (this.status | STATES.DIRTY) & ~STATES.CLEAN; if (!silent) this.emit('change', changed, this); if (commit && !fetched) this.commit(opts); // reset value so subsequent changes won't be added to this change-set this.changed = null; } } return this; },
It looks like you're new here. If you want to get involved, click one of these buttons!
I rely heavily on this app being able to parse the response from the server.
|
http://forums.enyojs.com/discussion/2273/enyo-2-5-model-parse
|
CC-MAIN-2019-26
|
refinedweb
| 509 | 71.34 |
graphql-let - A Webpack loader for GraphQL Code Generator
Explore our services and get in touch.
graphql-let is a wrapper tool that makes using GraphQL Code Generator smoother and easier. In this article, I'll explain what graphql-let is and how it relates to GraphQL Code Generator.
What is graphql-let?
"It's a webpack loader" would be a simple explanation to start. It lets you directly import GraphQL documents and use GraphQL Code Generator's result as below:
// You can directly import typed objects generated by GraphQL code generator⚡️ import { useNewsQuery } from './news.graphql' const News: React.FC = () => { // Yes, fetched data is typed too💪 const { data: { news } } = useNewsQuery() if (news) return <div>{news.map(...)}</div> }
The fastest way to try graphql-let is to use the Next.js example from their official repository by hitting the following command.
yarn create next-app --example with-typescript-graphql with-typescript-graphql-app
graphql-let is made for enhancing the development pattern using TypeScript and GraphQL, the most effective combination to solve many front-end problems in 2020. It heavily depends on GraphQL Code Generator, so in other words, if you don't use any of TypeScript and GraphQL Code Generator, you don't need
graphql-let either.
graphql-let's configuration file,
.graphql-let.yml, looks intentionally similar to
codegen.yml of GraphQL Codegen. Next, I'll explain what
graphql-let does by calling GraphQL Code Generator's API under the hood.
What does graphq-let add on top of GraphQL code generator API?
GraphQL Code Generator is an awesome tool. It's an infrastructure to expand the possibility of GraphQL nowadays. graphql-let is in
devDependencies as well as GraphQL Code Generator, so it does nothing in runtime-level too. graphql-let eases two pain points while you develop using
codegen command of GraphQL Code Generator.
With GraphQL Code Generator,
- You need to point to the output path as
import "../../../__generated__/out.tsx"everywhere
- You need to run the
graphql-codegencommand manually every time you change the single file
With graphql-let,
- You can directly import GraphQL source as
import "./news.graphql"thanks to the webpack power.
- You can process codegen in HMR too, thanks to webpack again.
- It achieved the above by getting rid of the
generatesoption, where graphql-let takes care of generated paths and lets you forget them.
Please note that there are limitations, mainly because graphql-let controls output paths. I'd recommend you read the documentation once to get the picture of how graphql-let and GraphQL Code Generator different.
Other features
There are other convenient features graphql-let provides to make it more practical.
#import syntax support
#import is useful to share fragments of GraphQL document, especially when your project codebase becomes big. If you have a fragment file named
partial.graphql like this,
fragment Partial on User { id name }
you can share it from other places by importing it.
# import Partial from './partial.graphql' query Viewer { viewer { ...Partial } }
Jest Transformer
graphql-let exports
graphql-let/jestTransformer that you can use in Jest testing. Please read the docs for more information.
Babel Plugin for inline GraphQL documents
It's still partial support, but graphql-let provides a babel plugin to allows developers to write inline GraphQL documents.
import gql from 'graphql-let'; // Typed️⚡️ const { useViewerQuery } = gql(` query Viewer { viewer { name } } `);
It generates
.d.ts files in
node_modules/@types/graphql-let by default to apply overload signatures on the function
gql. Ideally, it should be available in both a babel plugin and the webpack loader but there needs to be more effort.
Why I made graphql-let
I made this for front-end devs to adopt the TypeScript and GraphQL even more in their project😄
When I actively maintained kriasoft/react-starter-kit a few years ago, I realized it's so happy to use Apollo Server and Apollo Client. At the moment, though, Apollo primarily supported HOCs instead of React Hooks, which leads to troublesome to match types of GraphQL operations and fetched data manually. Then,
@graphql-codegen/typescript-react-apollo appeared and solved all the problems, except ones that graphql-let deals with later.
The less setup process GraphQL development requires, the more people can adopt GraphQL I believe, simply because GraphQL itself solves many problems web development has been struggling with without it for a decade. I couldn't be happier if a few of you get to know the power of GraphQL through using graphql-let.
|
https://the-guild.dev/blog/graphql-let
|
CC-MAIN-2021-31
|
refinedweb
| 747 | 56.35 |
This is a convenient way to take code developed in a Mathematica notebook document and introduce it into a project in the Workbench. An alternative would be to use copy and paste.
To import from a notebook, you should open the
import wizard, select
Mathematica > Code from a File,
and click Next. This opens a page that
looks like the following.
Now you should enter the name of the file to import; the
Browse button might be useful for this. If you
enter the name of a notebook document, a .nb file, the
page should look something like the following.
This lets you import only from initialization cells or all input cells. When you have entered the name of the file, you can click Next and this lets you select the output location in the project. After this you can finish the wizard and the import is carried out.
Before import, the code in the notebook file
might look something like the following.
After import, the imported code in the notebook file
might look as shown below.
After importing some code it might be worth using the
code formatter. This can improve the appearance
of the code.
|
http://reference.wolfram.com/workbench/topic/com.wolfram.eclipse.help/html/tasks/importing/notebook.html
|
CC-MAIN-2014-49
|
refinedweb
| 197 | 74.08 |
Perry <= A framework that let’s you compose websites in Python with ease!
Perry works similar to Qt and Flutter, allowing you to create component collections.
Say you want to create a div with some text and an image. To do that you’d first need to create the page:
from Perry import component, pageView, serve, Composite
Let’s break it down:
- Component – A given element that can be added anywhere on the page
- pageView – Creates a page with a route for us, we can load styles, JS and other things into it by using the ‘styles’ argument
- Serve – A Flask based micro-server for Perry
- Composite – The most important part! This tells our components to build themselves recursively as well as creating the skeleton, route and debugging info.
Now let’s create the page
Homepage = component(pageView, _Inherit = True) # a pageView is also a component, but inherits different functionality # Assign page contents Homepage <= { 'title': 'Home', # Title of the page 'path':'', # Route on the webserver, no need to include the starting / 'styles': [bootstrap], # Styles and other components, here we load bootstrap which is included in Extras 'DOM': pageView.DOM, # DOM, not yet implemented but worth using in case you want to upgrade to a newer verion of Perry later 'components': HomepageContents # A ComponentSource with our elements }
This page will just show up as an error as we haven’t yet created our component source!
This can be done through importing
ComponentSource
HomepageContents = ComponentSource( DIV( Label('Hello World!', 'h1'), Card( Image('Image URL'), CardText('Sample Text which has attributes for bootstrap cards', 'p') ), Label('Good bye!', 'h1') ) )
You’ll get something like this. The trailing comment is used for debugging
<body> <!-- Components ---> <div id="" class=""> <h1 id=""> Hello World! </h1> <!-- Component: <Label id:0x7f398481c910>---> <div style="width: 18rem;" id="" class="card, "> <div class="card-body"> <img src="Image URL" id="style="""> <!-- Component: <Image id:0x7f398481c9d0>---> <p id="class="card-text""> Sample Text which has attributes for bootstrap cards </p> <!-- Component: <BootstrapCardText id:0x7f398481ca60>---> </div> </div> <!-- Component: <BootrstrapCard cclass:None id:0x7f398481cb20>---> <h1 id=""> Good bye! </h1> <!-- Component: <Label id:0x7f398481cbe0>---> </div> <!-- Component: <DIV cclass:None id:0x7f398481cca0>---> <p id=""> Running on Perry v0.9 with Debug Mode on! </p> <!-- Component: <Label id:0x7f3984885d90>---> <!-- End of Components ---> </body>
Want to bundle together multiple elements and create a universal one? That’s easy to do!
OurCoolNewElement = DIV( Label('Hello, I have custom stuff!', 'h1', id = 'CoolTitle'), cclass = 'NewElement' ) # Let's give it some style ourCustomStyle = style() ourCustomStyle <= { 'author':'HUSKI3', 'source':'Local-made ;)' 'ctype':'css', 'css' : ''' .NewElement { color: white; background: black; } '''} # And now add it to the components HomepageContents = ComponentSource( DIV( Label('Hello World!', 'h1'), OurCoolNewElement , # <--- here Label('Good bye!', 'h1') ) )
You’ll need to load the style when defining the homepage contents!
Homepage <= { ..., 'styles': [some, styles, ourCustomStyle], ... }
At the moment JS doesn’t have direct support through built in components, but you can use
JQueryEngine and
JQueryEngineStrapper from Extras.
# First we create the component with JQuery, give it a pageView to wrap around (WIP) js = JQueryEngine(pageView, cid = 'coolscript') # Now you load in the script, it can either be a string or a read from file js <= ( open('PerryApp/coolscript.js','r').read() ) # To load it in, you need to add JQueryEngineStrapper to the styles of the page and add the js component to the components HomepageContents.add( js )
In Perry you always serve pages as a Composite collection, this way they are built and then loaded on Flask on the specified routes.
# Serve our pages as a composite collection serve <= Composite(Homepage, About, OtherPage, debug = True)
GitHub
View Github
|
https://news.priviw.com/tech-examples/a-framework-that-lets-you-compose-websites-in-python-with-ease/
|
CC-MAIN-2022-05
|
refinedweb
| 597 | 63.19 |
How to Build a Simple Actor-based Blockchain
How to build a simple actor-based blockchain
Scalachain is a blockchain built using the Scala programming language and the actor model (Akka Framework).
In this story I will show the development process to build this simple prototype of a blockchain. This means that the project is not perfect, and there may be better implementations. For all these reasons any contribution — may it be a suggestion, or a PR on the GitHub repository — is very welcome! :-)
Let’s start with a little introduction to the blockchain. After that we can define the simplified model that we will implement.
Quick Introduction to the blockchain
There a lot of good articles that explain how a blockchain works, so I will do a high level introduction just to provide some context to this project.
The blockchain is a distributed ledger: it registers some transaction of values (like coins) between a sender and a receiver. What makes a blockchain different from a traditional database is the decentralized nature of the blockchain: it is distributed among several communicating nodes that guarantee the validity of the transactions registered.
The blockchain stores transactions in blocks, that are created —we say mined — by nodes investing computational power. Every block is created by solving a cryptographic puzzle that is hard to solve, but easy to verify. In this way, every block represents the work needed to solve such puzzle. This is the reason why the cryptographic puzzle is called the Proof of Work: the solution of the puzzle is the proof that a node spent a certain amount of work to solve it and mine the block.
Why do nodes invest computational power to mine a block? Because the creation of a new block is rewarded by a predefined amount of coins. In this way nodes are encouraged to mine new blocks, contributing in the growth and strength of the blockchain.
The solution of the Proof Of Work depends on the values stored in the last mined block. In this way every block is chained to the previous one. This means that, to change a mined block, a node should mine again all the blocks above the modified one. Since every block represents an amount of work, this operation would be unfeasible once several blocks are mined upon the modified one. This is the foundation of the distributed consensus, The agreement of all the nodes on the validity of the blocks (that is the transactions) stored in the blockchain.
It may happen that different nodes mine a block at the same time, creating different “branches” from the same blockchain — this is called a fork in the blockchain. This situation is solved when a branch becomes longer than the others: the longest chain always wins, so the winning branch becomes the new blockchain.
The blockchain model
Scalachain is based on a blockchain model that is a simplification of the Bitcoin one.
The main components of our blockchain model are the Transaction, the Chain, the Proof of Work (PoW) algorithm, and the Node. The transactions are stored inside the blocks of the chain, that are mined using the PoW. The node is the server that runs the blockchain.
Transaction Transactions register the movement of coins between two entities. Every transaction is composed by a sender, a recipient, and an amount of coin. Transactions will be registered inside the blocks of our blockchain.
Chain The chain is a linked list of blocks containing a list of transactions. Every block of the chain has an index, the proof that validates it (more on this later), the list of transactions, the hash of the previous block, the list of previous blocks, and a timestamp. Every block is chained to the previous one by its hash, that is computed converting the block to a
JSON string and then hashing it through a
SHA-256 hashing function.
PoW The PoW algorithm is required to mine the blocks composing the blockchain. The idea is to solve a cryptographic puzzle that is hard to solve, but easy to verify having the proof. The PoW algorithm that is implemented in Scalachain is similar to the Bitcoin one (based on Hashcash). It consists in finding a hash with N leading zeros, that is computed starting from the hash of the last block and a number, that is the proof of our algorithm.
We can formalize it as:
NzerosHash = SHA-256(previousNodeHash + proof
The higher is N, the harder is to find the proof. In Scalachain N=4 (It will be configurable eventually).
Node The Node is the server running our blockchain. It provides some REST API to interact with it and perform basic operations such as send a new transaction, get the list of pending transactions, mine a block, and get the current status of the blockchain.
Blockchain implementation in Scala
We are going to implement the defined model using the Scala Programming Language. From an high level view, the things we need to implement a blockchain are:
- transactions
- the chain of blocks containing lists of transactions
- the PoW algorithm to mine new blocks
These components are the essential parts of a blockchain.
Transaction The transaction is a very simple object: it has a sender, a recipient and a value. We can implement it as a simple
case class.
case class Transaction(sender: String, recipient: String, value: Long)
Chain The chain is the core of our blockchain: it is a linked list of blocks containing transactions.
sealed trait Chain { val index: Int val hash: String val values: List[Transaction] val proof: Long val timestamp: Long }
We start by creating a
sealed trait that represents the block of our chain. The
Chain can have two types: it can be an
EmptyChain or a
ChainLink. The former is our block zero (the genesis block), and it is implemented as a singleton (it is a
case object), while the latter is a regular mined block.
case class ChainLink(index: Int, proof: Long, values: List[Transaction], previousHash: String = "", tail: Chain = EmptyChain, timestamp: Long = System.currentTimeMillis()) extends Chain { val hash = Crypto.sha256Hash(this.toJson.toString) } case object EmptyChain extends Chain { val index = 0 val hash = "1" val values = Nil val proof = 100L val timestamp = System.currentTimeMillis() }
Let’s look more in detail at our chain. It provides an index, that is the current height of the blockchain. There is the list of
Transaction, the proof that validated the block, and the timestamp of the block creation. The hash value is set to a default one in the
EmptyChain, while in the
ChainLink it is computed converting the object to its
JSON representation and hashing it with an utility function (see the
crypto package in the repository). The
ChainLink provides also the hash of the previous block in the chain (our link between blocks). The tail field is a reference to the previously mined blocks. This may not be the most efficient solution, but it is useful to see how the blockchain grows in our simplified implementation.
We can improve our
Chain with some utilities. We can add it a companion object that defines an
apply method to create a new chain passing it a list of blocks. A companion object is like a “set of static methods” — doing an analogy with Java — that has complete access rights on the fields and methods of the class/trait.
object Chain { def apply[T](b: Chain*): Chain = { if (b.isEmpty) EmptyChain else { val link = b.head.asInstanceOf[ChainLink] ChainLink(link.index, link.proof, link.values, link.previousHash, apply(b.tail: _*)) } } }
If the list of blocks is empty, we simply initialize our blockchain with an
EmptyChain. Otherwise we create a new
ChainLink adding as a tail the result of the apply method on the remaining blocks of the list. In this way the list of blocks is added following the order of the list.
It would be nice to have the possibility to add a new block to our chain using a simple addition operator, like the one we have on
List. We can define our own addition operator
:: inside the
Chain trait.
sealed trait Chain { val index: Int val hash: String val values: List[Transaction] val proof: Long val timestamp: Long def ::(link: Chain): Chain = link match { case l:ChainLink => ChainLink(l.index, l.proof, l.values, this.hash, this) case _ => throw new InvalidParameterException("Cannot add invalid link to chain") } }
We pattern match on the block that is passed as an argument: if it is a valid
ChainLink object we add it as the head of our chain, putting the chain as the tail of the new block, otherwise we throw an exception.
PoW The PoW algorithm is fundamental for the mining of new blocks. We implement it as a simple algorithm:
- Take the hash of the last block and a number representing the proof.
- Concatenate the hash and the proof in a string.
- hash the resulting string using the
SHA-256algorithm.
- check the 4 leading characters of the hash: if they are four zeros return the proof.
- otherwise repeat the algorithm increasing the proof by one.
This a simplification of the HashCash algorithm used in the Bitcoin blockchain.
Since it is a recursive function, we can implement it as a tail recursive one to improve the usage of resources.
object ProofOfWork { def proofOfWork(lastHash: String): Long = { @tailrec def powHelper(lastHash: String, proof: Long): Long = { if (validProof(lastHash, proof)) proof else powHelper(lastHash, proof + 1) } val proof = 0 powHelper(lastHash, proof) } def validProof(lastHash: String, proof: Long): Boolean = { val guess = (lastHash ++ proof.toString).toJson.toString val guessHash = Crypto.sha256Hash(guess) (guessHash take 4) == "0000" } }
The
validProof function is used to check if the proof we are testing is the correct one. The
powHelper function is a helper function that executes our loop using tail recursion, increasing the proof at each step. The
proofOfWork function wrap all the things up, and is exposed by the
ProofOfWork object.
The actor model
The actor model is a programming model designed for concurrent processing, scalability, and fault tolerance. The model defines the atomic elements that compose the software systems — the actors — and the way this elements interact between them. In this project we will use the actor model implemented in Scala by the Akka Framework.
Actor The actor is the atomic unit of the actor model. it is a computational unit that can send and receive messages. Every actor has an internal private state and a mailbox. When an actor receives and compute a message, it can react in 3 ways:
- Send a message to another actor.
- Change its internal state.
- Create another actor.
Communication is asynchronous, and messages are popped out from the mailbox and processed in series. To enable the parallel computation of messages you need to create several actors. Many actors together crate an actor system. The behavior of the application arises from the interaction between actors providing different functionalities.
Actors are independent Actors are independent one to another, and they do not share their internal state. This fact has a couple of important consequences:
- Actors can process messages without side-effects one to another.
- It’s not important where an actor is — be it your laptop, a sever, or in the cloud — once we know its address we can request its services sending it a message.
The first point makes concurrent computation very easy. We can be sure that the processing of a message will not interfere with the processing of another one. To achieve concurrent processing we can deploy several actors able to process the same kind of message.
The second point is all about scalability: we need more computational power? No problem: we can start a new machine and deploy new actors that will join the existing actor system. Their mailbox addresses will be discoverable by existing actors, that will start communicate with them.
Actors are supervised As we said in the description of the actor, one of the possible reaction to a message is the creation of other actors. When this happens, the father becomes the supervisor of its children. If a children fails, the supervisor can decide the action to take, may it be create a new actor, ignore the failure, or throw it up to its own supervisor. In this way the Actor System becomes a hierarchy tree, each node supervising its children. This is the way the actor model provides fault tolerance.
Broker, a simple actor
The first actor we are going to implement is the Broker Actor: it is the manager of the transactions of our blockchain. Its responsibilities are the addition of new transactions, and the retrieval of pending ones.
The Broker Actor reacts to three kind of messages, defined in the
companion object of the Broker class:
object Broker { sealed trait BrokerMessage case class AddTransaction(transaction: Transaction) extends BrokerMessage case object GetTransactions extends BrokerMessage case object Clear extends BrokerMessage val props: Props = Props(new Broker) }
We create a trait
BrokerMessage to identify the messages of the Broker Actor. Every other message will extend this trait.
AddTransaction adds a new transaction to the list of pending ones.
GetTransaction retrieve the pending transactions, and
Clear empties the list. The
props value is used to initialize the actor when it will be created.
class Broker extends Actor with ActorLogging { import Broker._ var pending: List[Transaction] = List() override def receive: Receive = { case AddTransaction(transaction) => { pending = transaction :: pending log.info(s"Added $transaction to pending Transaction") } case GetTransactions => { log.info(s"Getting pending transactions") sender() ! pending } case Clear => { pending = List() log.info("Clear pending transaction List") } } }
The Broker
class contains the business logic to react to the different messages. I won’t go into the details because it is trivial. The most interesting thing is how we respond to a request of the pending transactions. We send them to the
sender() of the
GetTransaction message using the
tell (
!) operator. This operator means “send the message and don’t wait for a response” — aka fire-and-forget.
Miner, an actor with different states
The Miner Actor is the one mining new blocks for our blockchain. Since we don’t want mine a new block while we are mining another one, the Miner Actor will have two states: ready, when it is
ready to mine a new block, and
busy, when it is mining a block.
Let’s start by defining the
companion object with the messages of the Miner Actor. The pattern is the same, with a sealed trait —
MinerMessage — used to define the kind of messages this actor reacts to.
object Miner { sealed trait MinerMessage case class Validate(hash: String, proof: Long) extends MinerMessage case class Mine(hash: String) extends MinerMessage case object Ready extends MinerMessage val props: Props = Props(new Miner) }
The
Validate message asks for a validation of a proof, and pass to the Miner the hash and the proof to check. Since this component is the one interacting with the PoW algorithm, it is its duty to execute this check. The
Mine message asks for the mining starting from a specified hash. The last message,
Ready, triggers a state transition.
Same actor, different states The peculiarity of this actor is that it reacts to the messages according to its state:
busy or
ready. Let’s analyze the difference in the behavior:
- busy: the Miner is busy mining a block. If a new mining request comes, it should deny it. If it is requested to be ready, the Miner should change its state to the ready one.
- ready: the Miner is idle. If a mining request come, it should start mining a new block. If it is requested to be ready, it should say: “OK, I’m ready!”
- both: the Miner should be always available to verify the correctness of a proof, both in a ready or busy state.
Time so see how we can implement this logic in our code. We start by defining the common behavior, the validation of a proof.
def validate: Receive = { case Validate(hash, proof) => { log.info(s"Validating proof $proof") if (ProofOfWork.validProof(hash, proof)){ log.info("proof is valid!") sender() ! Success } else{ log.info("proof is not valid") sender() ! Failure(new InvalidProofException(hash, proof)) } } }
We define a function
validate that reacts to the
Validate message: if the proof is valid we respond to the sender with a success, otherwise with a failure. The
ready and the
busy states are defined as functions that “extends” the
validate one, since that is a behavior we want in both states.
def ready: Receive = validate orElse { case Mine(hash) => { log.info(s"Mining hash $hash...") val proof = Future {(ProofOfWork.proofOfWork(hash))} sender() ! proof become(busy) } case Ready => { log.info("I'm ready to mine!") sender() ! Success("OK") } } def busy: Receive = validate orElse { case Mine(_) => { log.info("I'm already mining") sender ! Failure(new MinerBusyException("Miner is busy")) } case Ready => { log.info("Ready to mine a new block") become(ready) } }
A couple of things to highlight here.
- The state transition is triggered using the
becomefunction, provided by the Akka Framework. This takes as an argument a function that returns a
Receiveobject, like the ones we defined for the
validation,
busy, and
readystate.
- When a mining request is received by the Miner, it responds with a
Futurecontaining the execution of the PoW algorithm. In this way we can work asynchronously, making the Miner free to do other tasks, such as the validation one.
- The supervisor of this Actor controls the state transition. The reason of this choice is that the Miner is agnostic about the state of the system. It doesn’t know when the mining computation in the
Futurewill be completed, and it can’t know if the block that it is mining has been already mined from another node. This would require to stop mining the current hash, and start mining the hash of the new block.
The last thing is to provide an initial state overriding the
receive function.
override def receive: Receive = { case Ready => become(ready) }
We start waiting for a
Ready message. When it comes, we start our Miner.
Blockchain, a persistent actor
The Blockchain Actor interacts with the business logic of the blockchain. It can add a new block to the blockchain, and it can retrieve information about the state of the blockchain. This actor has another superpower: it can persist and recover the state of the blockchain. This is possible implementing the
PersistentActor trait provided by the Akka Framework.
object Blockchain { sealed trait BlockchainEvent case class AddBlockEvent(transactions: List[Transaction], proof: Long) extends BlockchainEvent sealed trait BlockchainCommand case class AddBlockCommand(transactions: List[Transaction], proof: Long) extends BlockchainCommand case object GetChain extends BlockchainCommand case object GetLastHash extends BlockchainCommand case object GetLastIndex extends BlockchainCommand case class State(chain: Chain) def props(chain: Chain, nodeId: String): Props = Props(new Blockchain(chain, nodeId)) }
We can see that the
companion object of this actor has more elements than the other ones. The
State class is where we store the state of our blockchain, that is its
Chain. The idea is to update the state every time a new block is created.
For this purpose, there are two different traits:
BlockchainEvent and
BlockchainCommand. The former is to handle the events that will trigger the persistence logic, the latter is used to send direct commands to the actor. The
AddBlockEvent message is the event that will update our state. The
AddBlockCommand,
GetChain,
GetLastHash, and
LastIndex commands are the one used to interact with the underlying blockchain.
The usual
props function initializes the Blockchain Actor with the initial
Chain and the
nodeId of the Scalachain node.
class Blockchain(chain: Chain, nodeId: String) extends PersistentActor with ActorLogging{ import Blockchain._ var state = State(chain) override def persistenceId: String = s"chainer-$nodeId" //Code... }
The Blockchain Actor extends the trait
PersistentActor provided by the Akka framework. In this way we have out-of-the-box all the logic required to persist and recover our state.
We initialize the state using the
Chain provided as an argument upon creation. The
nodeId is part of the
persistenceId that we override. The persistence logic will use it to identify the persisted state. Since we can have multiple Scalachain nodes running in the same machine, we need this value to correctly persist and recover the state of each node.
def updateState(event: BlockchainEvent) = event match { case AddBlockEvent(transactions, proof) => { state = State(ChainLink(state.chain.index + 1, proof, transactions) :: state.chain) log.info(s"Added block ${state.chain.index} containing ${transactions.size} transactions") } }
The
updateState function executes the update of the Actor state when the
AddBlockEvent is received.
override def receiveRecover: Receive = { case SnapshotOffer(metadata, snapshot: State) => { log.info(s"Recovering from snapshot ${metadata.sequenceNr} at block ${snapshot.chain.index}") state = snapshot } case RecoveryCompleted => log.info("Recovery completed") case evt: AddBlockEvent => updateState(evt) }
The
receiveRecover function reacts to the recovery messages sent by the persistence logic. During the creation of an actor a persisted state (snapshot) may be offered to it using the
SnapshotOffer message. In this case the current state becomes the one provided by the snapshot.
RecoveryCompleted message informs us that the recovery process completed successfully. The
AddBlockEvent triggers the
updateState function passing the event itself.
override def receiveCommand: Receive = { case SaveSnapshotSuccess(metadata) => log.info(s"Snapshot ${metadata.sequenceNr} saved successfully") case SaveSnapshotFailure(metadata, reason) => log.error(s"Error saving snapshot ${metadata.sequenceNr}: ${reason.getMessage}") case AddBlockCommand(transactions : List[Transaction], proof: Long) => { persist(AddBlockEvent(transactions, proof)) {event => updateState(event) } // This is a workaround to wait until the state is persisted deferAsync(Nil) { _ => saveSnapshot(state) sender() ! state.chain.index } } case AddBlockCommand(_, _) => log.error("invalid add block command") case GetChain => sender() ! state.chain case GetLastHash => sender() ! state.chain.hash case GetLastIndex => sender() ! state.chain.index }
The
receiveCommand function is used to react to the direct commands sent to the actor. Let’s skip the
GetChain,
GetLastHash, and
GetLastIndex commands, since they are trivial. The
AddBlockCommand is the interesting part: it creates and fires an
AddBlock event, that is persisted in the event journal of the Actor. In this way events can be replayed in case of recovery.
The
deferAsync function waits until the state is updated after the processing of the event. Once the event has been executed the actor can save the snapshot of the state, and inform the sender of the message with the updated last index of the
Chain. The
SaveSnapshotSucces and
SaveSnapshotFailure messages helps us to keep track of possible failures.
Node, an actor to rule them all
The Node Actor is the backbone of our Scalachain node. It is the supervisor of all the other actors (Broker, Miner, and Blockchain), and the one communicating with the outside world through the REST API.
object Node { sealed trait NodeMessage case class AddTransaction(transaction: Transaction) extends NodeMessage case class CheckPowSolution(solution: Long) extends NodeMessage case class AddBlock(proof: Long) extends NodeMessage case object GetTransactions extends NodeMessage case object Mine extends NodeMessage case object StopMining extends NodeMessage case object GetStatus extends NodeMessage case object GetLastBlockIndex extends NodeMessage case object GetLastBlockHash extends NodeMessage def props(nodeId: String): Props = Props(new Node(nodeId)) def createCoinbaseTransaction(nodeId: String) = Transaction("coinbase", nodeId, 100) }
The Node Actor has to handle all the high level messages that coming from the REST API. This is the reason why we find in the
companion object more or less the same messages we implemented in the children actors. The props function takes a nodeId as an argument to create our Node Actor. This will be the one used for the initialization of Blockchain Actor. The
createCoinbaseTransaction simply creates a transaction assigning a predefined coin amount to the node itself. This will be the reward for the successful mining of a new block of the blockchain.
class Node(nodeId: String) extends Actor with ActorLogging { import Node._ implicit lazy val timeout = Timeout(5.seconds) val broker = context.actorOf(Broker.props) val miner = context.actorOf(Miner.props) val blockchain = context.actorOf(Blockchain.props(EmptyChain, nodeId)) miner ! Ready //Code... }
Let’s look at the initialization of the Node Actor. The timeout value is used by the
ask (
?) operator (this will be explained shortly). All our actors are created in the actor
context, using the
props function we defined in each actor.
The Blockchain Actor is initialized with the
EmptyChain and the
nodeId of the Node. Once everything is created, we inform the Miner Actor to be ready to mine sending it a
Ready message. Ok, we are now ready to receive some message and react to it.
override def receive: Receive = { case AddTransaction(transaction) => { //Code... } case CheckPowSolution(solution) => { //Code... } case AddBlock(proof) => { //Code... } case Mine => { //Code... } case GetTransactions => broker forward Broker.GetTransactions case GetStatus => blockchain forward GetChain case GetLastBlockIndex => blockchain forward GetLastIndex case GetLastBlockHash => blockchain forward GetLastHash }
This is an overview of the usual
receive function that we should override. I will analyze the logic of the most complex
cases later, now let’s look at the last four. Here we forward the messages to the Blockchain Actor, since it isn’t required any processing. Using the
forward operator the
sender() of the message will be the one that originated the message, not the Node Actor. In this way the Blockchain Actor will respond to the original sender of the message (the REST API layer).
override def receive: Receive = { case AddTransaction(transaction) => { val node = sender() broker ! Broker.AddTransaction(transaction) (blockchain ? GetLastIndex).mapTo[Int] onComplete { case Success(index) => node ! (index + 1) case Failure(e) => node ! akka.actor.Status.Failure(e) } } //Code... }
The
AddTransaction message triggers the logic to store a new transaction in the list of pending ones of our blockchain. The Node Actor responds with the
index of the block that will contain the transaction.
First of all we store the “address” of the
sender() of the message in a node value to use it later. We send to the Broker Actor a message to add a new transaction, then we
ask to the Blockchain Actor the last index of the chain. The
ask operator — the one expressed with
? — is used to send a message to an actor and wait for a response. The response (mapped to an
Int value) can be a
Success or a
Failure.
In the first case we send back to the sender (
node) the
index+1, since it will be the index of the next mined block. In case of failure, we respond to the sender with a
Failure containing the reason of the failure. Remember this pattern:
ask → wait for a response → handle success/failure
because we will see it again.
override def receive: Receive = { //Code... case CheckPowSolution(solution) => { val node = sender() (blockchain ? GetLastHash).mapTo[String] onComplete { case Success(hash: String) => miner.tell(Validate(hash, solution), node) case Failure(e) => node ! akka.actor.Status.Failure(e) } } //Code... }
This time we have to check if a solution to the PoW algorithm is correct. We ask to the Blockchain Actor the hash of the last block, and we tell the Miner Actor to validate the solution against the hash. In the
tell function we pass to the Miner the
Validate message along with the address of the sender, so that the miner can respond directly to it. This is another approach, like the
forward one we saw before.
override def receive: Receive = { //Code... case AddBlock(proof) => { val node = sender() (self ? CheckPowSolution(proof)) onComplete { case Success(_) => { (broker ? Broker.GetTransactions).mapTo[List[Transaction]] onComplete { case Success(transactions) => blockchain.tell(AddBlockCommand(transactions, proof), node) case Failure(e) => node ! akka.actor.Status.Failure(e) } broker ! Clear } case Failure(e) => node ! akka.actor.Status.Failure(e) } } //Code... }
Other nodes can mine blocks, so we may receive a request to add a block that we didn’t mine. The proof is enough to add the new block, since we assume that all the nodes share the same list of pending transactions.
This is a simplification, in the Bitcoin network there cannot be such assumption. First of all we should check if the solution is valid. We do this sending a message to the node itself:
self ? CheckPowSolution(proof). If the proof is valid, we get the list of pending transaction from the Broker Actor, then we
tell to the Blockchain Actor to add to the chain a new block containing the transactions and the validated proof. The last thing to do is to command the Broker Actor to clear the list of pending transactions.
override def receive: Receive = { //Code... case Mine => { val node = sender() (blockchain ? GetLastHash).mapTo[String] onComplete { case Success(hash) => (miner ? Miner.Mine(hash)).mapTo[Future[Long]] onComplete { case Success(solution) => waitForSolution(solution) case Failure(e) => log.error(s"Error finding PoW solution: ${e.getMessage}") } case Failure(e) => node ! akka.actor.Status.Failure(e) } } //Code... } def waitForSolution(solution: Future[Long]) = Future { solution onComplete { case Success(proof) => { broker ! Broker.AddTransaction(createCoinbaseTransaction(nodeId)) self ! AddBlock(proof) miner ! Ready } case Failure(e) => log.error(s"Error finding PoW solution: ${e.getMessage}") } }
The last message is the request to start mining a new block. We need the hash of the last block in the chain, so we request it to the Blockchain Actor. Once we have the hash, we can start mining a new block.
The PoW algorithm is a long-running operation, so the Miner Actor responds immediately with a
Future containing the computation. The
waitForSolution function waits for the computation to complete, while the Node Actor keeps doing its business.
When we have a solution, we reward ourselves adding the coinbase transaction to the list of pending transactions. Then we add the new block to the chain and tell the Miner Actor to be ready to mine another block.
REST API with Akka HTTP
This last section describes the server and REST API. This is the most “external” part of our application, the one connecting the outside world to the Scalachain node. We will make use of Akka HTTP library, which is part of the Akka Framework. Let’s start looking at the server, the entry point of our application.
object Server extends App with NodeRoutes { val address = if (args.length > 0) args(0) else "localhost" val port = if (args.length > 1) args(1).toInt else 8080 implicit val system: ActorSystem = ActorSystem("scalachain") implicit val materializer: ActorMaterializer = ActorMaterializer() val node: ActorRef = system.actorOf(Node.props("scalaChainNode0")) lazy val routes: Route = statusRoutes ~ transactionRoutes ~ mineRoutes Http().bindAndHandle(routes, address, port) println(s"Server online at") Await.result(system.whenTerminated, Duration.Inf) }
Since the
Server is our entry point, it needs to extend the
App trait. It extends also
NodeRoutes, a trait that contains all the http routes to the various endpoint of the node.
The
system value is where we store our
ActorSystem. Every actor created in this system will be able to talk to the others inside it. Akka HTTP requires also the definition of another value, the
ActorMaterializer. This relates to the Akka Streams module, but since Akka HTTP is built on top of it, we still need this object to be initialized in our server (if you want to go deep on the relation with streams, look here).
The Node Actor is created along with the HTTP routes of the node, that are chained using the
~ operator. Don’t worry about the routes now, we will be back to them in a moment.
The last thing to do is to start our server using the function
Http().bindHandle, that will also bind the routes we pass to it as an argument. The
Await.result function will wait the termination signal to stop the server.
The server will be useless without the routes to trigger the business logic of the application. We define the routes in the trait
NodeRoutes, differentiating them according to the different logic they trigger:
statusRoutescontains the endpoints to ask the Scalachain node for its status.
transactionRouteshandles everything related to transactions.
mineRouteshas the endpoint to start the mining process
Notice that this differentiation is a logic one, just to keep things ordered and readable. The three routes will be chained in a single one after their initialization in the server.
//Imports... import com.elleflorio.scalachain.utils.JsonSupport._ // Imports... trait NodeRoutes extends SprayJsonSupport { implicit def system: ActorSystem def node: ActorRef implicit lazy val timeout = Timeout(5.seconds) //Code... }
The
NodeRoutes trait extends
SprayJsonSupport to add
JSON serialization/deserialization. SprayJson is a Scala library analogous to Jackson in Java, and it comes for free with Akka HTTP.
To convert our objects to a
JSON string we import the class
JsonSupport defined in the
utils package, which contains custom reader/writer for every object. I won’t go into the details, you can find the class in the repository if you want to look at the implementation.
We have a couple of implicit values. The
ActorSystem is used to define the system of actors, while the
Timeout is used by the
OnSuccess function that waits for a response from the actors. The
ActorRef is defined by overriding in the server implementation.
//Code... lazy val statusRoutes: Route = pathPrefix("status") { concat( pathEnd { concat( get { val statusFuture: Future[Chain] = (node ? GetStatus).mapTo[Chain] onSuccess(statusFuture) { status => complete(StatusCodes.OK, status) } } ) } ) } //Code...
The endpoint to get the status of the blockchain is defined in the
statusRoutes. We define the
pathPrefix as "
status" so the node will respond to the path
http://<address>:<port>/status. After that there is the definition of the HTTP actions we want to enable on the path. Here we want to get the status of the blockchain, so we define only the
get action. Inside that we ask the Node Actor to get the current
Chain. When the actor responds, the
Chain is sent as a
JSON along with an
ok status in the
complete method.
//Code... lazy val transactionRoutes: Route = pathPrefix("transactions") { concat( pathEnd { concat( get { val transactionsRetrieved: Future[List[Transaction]] = (node ? GetTransactions).mapTo[List[Transaction]] onSuccess(transactionsRetrieved) { transactions => complete(transactions.toList) } }, post { entity(as[Transaction]) { transaction => val transactionCreated: Future[Int] = (node ? AddTransaction(transaction)).mapTo[Int] onSuccess(transactionCreated) { done => complete((StatusCodes.Created, done.toString)) } } } ) } ) } //Code...
The
transactionRoutes allows the interaction with the pending transactions of the node. We define the HTTP action
get to retrieve the list of pending transactions. This time we also define the HTTP action
post to add a new transaction to the list of pending ones. The
entity(as[Transaction]) function is used to deserialize the
JSON body into a
Transaction object.
//Code... lazy val mineRoutes: Route = pathPrefix("mine") { concat( pathEnd { concat( get { node ! Mine complete(StatusCodes.OK) } ) } ) } //Code...
The last route is the
MineRoutes. This is a very simple one, used only to ask the Scalachain node to start mine a new block. We define a
get action since we do not need to send anything to start the mining process. It is not required to wait for a response, since it may take some time, so we immediately respond with an
ok status.
The API to interact with the Scalachain node are documented here.
Conclusion
With the last section, we concluded our tour inside Scalachain. This prototype of a blockchain is far from a real implementation, but we learned a lot of interesting things:
- How a blockchain works, at least from an high level perspective.
- How to use functional programming (Scala) to build a blockchain.
- How the Actor Model works, and its application to our use case using the Akka Framework.
- How to use the Akka HTTP library to create a sever to run our blockchain, along with the APIs to interact with it.
The code is not perfect, and some things can be implemented in a better way. For this reason, feel free to contribute to the project! ;-)
Originally published on medium.freecodecamp.org
|
https://functional.works-hub.com/learn/how-to-build-a-simple-actor-based-blockchain-8ade6?utm_source=rss&utm_medium=automation&utm_content=8ade6
|
CC-MAIN-2020-16
|
refinedweb
| 5,936 | 56.15 |
US20080305792A1 - Method and Apparatus for Performing Network Based Service Access Control for Femtocells - Google PatentsMethod and Apparatus for Performing Network Based Service Access Control for Femtocells Download PDF
Info
- Publication number
- US20080305792A1US20080305792A1 US11/927,599 US92759907A US2008305792A1 US 20080305792 A1 US20080305792 A1 US 20080305792A1 US 92759907 A US92759907 A US 92759907A US 2008305792 A1 US2008305792 A1 US 2008305792A1
- Authority
- US
- United States
- Prior art keywords
- fap
- ganc
- network
- request
- 97
- 230000001808 coupling Effects 0.000 claims description 8
- 238000010168 coupling process Methods 0.000 claims description 8
- 238000005859 coupling reactions Methods 0.000 claims description 8
- 238000004590 computer program Methods 0.000 claims description 2
- 239000010410 layers Substances 0.000 abstract description 115
- 238000007726 management methods Methods 0.000 abstract description 3
- 238000000034 methods Methods 0.000 description 143
- 235000010384 tocopherol Nutrition 0.000 description 123
- 235000019731 tricalcium phosphate Nutrition 0.000 description 123
- 210000004027 cells Anatomy 0.000 description 110
- 230000011664 signaling Effects 0.000 description 80
- 230000004044 response Effects 0.000 description 54
- 230000000875 corresponding Effects 0.000 description 38
- 239000003570 air Substances 0.000 description 35
- 239000009033 nas Substances 0.000 description 32
- 101710063661 AGFG1 Proteins 0.000 description 25
- 239000002609 media Substances 0.000 description 18
-IuMzE5LDIyNC4wNDQgTCAyMTIuMzE5LDE2OSMTksMTMwLjI1NSBMIDIxMi4zMTksNzUu5NCwxNTAgxLjc0NSwxNTAgTCAxNzQuMQuMDYsMTUwIEwgMTU2LjM3Ni45MjksMTMwLjI1NSBMIDEwOS4zNDEsMTEwLjEM0MSwxMTAuMTc2IEwgOTQuNzUyOSw5MC4wMuOTI5LDE2OS43NDUgTCAxMDkuMzQxLDE4OS444zNDEsMTg5LjgyNCBMIDk0Ljc1MjksMjA5LjzUyOSw5MC4wOTY5IEwgMjQuMzMyNiwxMTIu43NjYxLDEwNy42MTMgTCAzOS40NzE5LDEyMyNiwxMTIuOTc4IEwgMjQuMzMyNiwxzI2LDE0MC4xMjcgTCAyNC4zMzI2LDE2Ny4yNQzMzMsMTkyLjkwMyBMIDY4LjU5MzEsMjAxuNTkzMSwyMDEuNDAzIEwgOTQuNzUyOSwyMDkuNTc1LDE4MS4zNjkgTCA3My4xNjkzLDE4Ny4jE2OTMsMTg3LjMxOSBMIDkxLjQ4MTIsMTkzLIuMzE5JyB5PScxNTMuNzMC4wNDcnIHk9JzE1My43MDInTYwOCcgeT0nMTkwLjcyNCc42NTcyLDYyLjk3OTIgTCA1OS42NTcyLDQ1LjNzIsMzguNTAzNSBMIDU5LjY1NzIsMjEuMDIMuMzg4Nyw0MiBMIDkyNTYsNDIgTCA0OC44MTOC44MTcxLDQyIEwgNDEuNzATM3NiwzOC41MDM1IEwgMzEuMjQyMSwzMS43NjUyNDIxLDMxLjc2NTUgTCAyNi4zNDY3LDI1LjAyEzNzYsNDUuNDk2NSBMIDMxLjI0MjEsNTIuMuMjQyMSw1Mi4yMzQNDY3LDI1LjAyNzUgTCA2LjM5NDI1LDMxLjUx1MDQsMjkuOTkwNCBMIDEwLjY4MzcsMzQuNTi4zOTQyNSwzMS41MTA0IEwgNi4zOTQyNSw0MC4yNTjM5NDI1LDQwLjI1MTcgTCA2LjM5NDI1LDQ4Ljk5MuNDI0ODYsNTMuNDc0MyBMIDE3Ljg4NTgsNTYuMjIzcuODg1OCw1Ni4yMjMyNTk3LDUwLjMwODYgTCAxOS4xODIzLDUyLjIzjE4MjMsNTIuMjMyOSBMIDI1LjEwNSw1NC4xY1NzInM0NjYnzI1NTUnIHk9JzUzLjUz[Si](C)(C)N1C=CN=C1 YKFRUJSEPGHZFJ-UHFFFAOYSA-N 0.000 description 17
- 239000003138 indicators Substances 0.000 description 14
- 238000003860 storage Methods 0.000 description 14
- 101710035102 CURT1B Proteins 0.000 description 12
- 101710046638 MTCH1 Proteins 0.000 description 12
- 101710056057 PSAP Proteins 0.000 description 12
- 101710064756 Pulmonary Surfactant-Associated Protein A Proteins 0.000 description 12
- 102100007574 Pulmonary surfactant-associated protein A2 Human genes 0.000 description 12
- 101710034013 SFTPA2 Proteins 0.000 description 12
- 230000004913 activation Effects 0.000 description 12
- 230000001413 cellular Effects 0.000 description 12
- 280000964116 and, Inc. companies 0.000 description 10
- 230000000737 periodic Effects 0.000 description 10
- 240000006240 Linum usitatissimum Species 0.000 description 9
- 235000004431 Linum usitatissimum Nutrition 0.000 description 9
- 238000010586 diagrams Methods 0.000 description 9
- 230000001960 triggered Effects 0.000 description 8
- 102000018059 CS domain Human genes 0.000 description 7
- 108050007176 CS domain Proteins 0.000 description 7
- 241000169635 Lacistemataceae Species 0.000 description 7
- XCCTYIAWTASOJW-XVFCMESISA-N Uridine-5'-Diphosph 7
- 239000000463 materials Substances 0.000 description 7
- 230000000576 supplementary Effects 0.000 description 7
- 241001128145 Resedaceae Species 0.000 description 6
- 239000000203 mixtures Substances 0.000 description 6
- 230000002265 prevention Effects 0.000 description 6
- 230000002633 protecting Effects 0.000 description 6
- 239000003999 initiators Substances 0.000 description 5
- 229920004880 RTP PEK Polymers 0.000 description 4
- 235000008984 brauner Senf Nutrition 0.000 description 4
- 244000275904 brauner Senf Species 0.000 description 4
- 230000001010 compromised Effects 0.000 description 4
- 230000004048 modification Effects 0.000 description 4
- 238000006011 modification reactions Methods 0.000 description 4
- 230000003287 optical Effects 0.000 description 4
- 241000033383 Bradybaenidae Species 0.000 description 3
- 239000006244 Medium Thermal Substances 0.000 description 3
- 239000004165 Methyl esters of fatty acids Substances 0.000 description 3
- 101710066540 PSTN Proteins 0.000 description 3
- 230000002159 abnormal effects Effects 0.000 description 3
- 230000006399 behavior Effects 0.000 description 3
- 239000000969 carriers Substances 0.000 description 3
- 230000001419 dependent Effects 0.000 description 3
- 238000009826 distribution Methods 0.000 description 3
- 230000002708 enhancing Effects 0.000 description 3
- 230000000977 initiatory Effects 0.000 description 3
- 238000004846 x-ray emission Methods 0.000 description 3
- 241000212893 Chelon labrosus Species 0.000 description 2
- 208000009863 Chronic Kidney Failure Diseases 0.000 description 2
- 101710052056 DROSHA Proteins 0.000 description 2
- 280000749855 Digital Network companies 0.000 description 2
- 229930012924 Indole-3-acetamide Natural products 0.000 description 2
- 280000086786 Radio Service companies 0.000 description 2
- 281000074146 Slaight Communications companies 0.000 description 2
- 241001246288 Succineidae Species 0.000 description 2
- 230000003044 adaptive Effects 0.000 description 2
- 230000005540 biological transmission Effects 0.000 description 2
- 238000006243 chemical reactions Methods0000000694 effects Effects 0.000 description 2
- 238000005516 engineering processes Methods 0.000 description 2
- 210000003702 immature single positive T cell Anatomy 0.000 descriptionMC45MjkgTCAyNjEuODU5LDIxOSNC45MDgsMTgxLjg2MyBMIDI1Ny43NTQsMjATgwLjkyOSBMIDI2NC45MjgsMTQwLYxLjg1OSwyMTkuODI5IEwgMjE1LjkxOCwyMTguMUuOTE4LDIxOC4wNTYgTCAxOTQuNDgzLDE3Ny444MzcsMjA3LjY2OCBMIDIwNS44MzIsMTc0LjQ4MywxNzcuMzg0IEwgMTQ5LjkxNSwxNj4MywxNzcuMzg0IEwgMjE4Ljk4OCwxMzkuOTE1LDE2Ni4wOTkgTCAxMTQuNTg4LDE5NS41OS45MTUsMTY2LjA5OSBMIDE0Ni44NzUsMTIwjYzNCwxNTguNjEgTCAxNTYuNTA2LDEyNi41ODgsMTk1LjUyMiBMIDcxLjQ0NDEsMTc45NzQ2LDE3OC44NTkgTCA3My4xMjM0LDE2MiEyMzQsMTYyLjMzNiBMIDcwLjI3MjMsMTQOTEzNiwxODAuNDIyIEwgNjQuMDYyNCwxNjMuuMDYyNCwxNjMuOSBMIDYxLjIxMTIsMTQuNDQ0MSwxNzkuNjQgTCA1OS40MDAzLDE4wMDMsMTg5LjY3MiBMIDQ3LjM1NjYsMTk5Ljc2Ljg3NSwxMjAuMjI1IEwgMTYyLjYwMSwxMTMuuNjAxLDExMy45MzkgTCAxNzguMzI2LDEwNy42kuNzc2LDExNS40MTkgTCAyMDkuMzgyLDEyNi45zgyLDEyNi45NTIgTCAyMTguOTg4LDEzguOTg4LDEzOC40ODUgTCAyNjQuOTI4LDE0MCjUuNTI0LDE0Ny45MzkgTCAyNTcuNjgzLDE0AwMjEnIHk9JzEzNi42EuMDczNCcgeT0nMjExLjUkuNTY1JyB5PScxMDUuNDjQ1NicgeT0nOTAuMTMywLjc2MzMgTCA3My42OTMyLDYxLjcM5MDYsNTEuMDI3OSBMIDcyLjUzMDQsNTguNNTAuNzYzMyBMIDc0LjU2MywzOS4yM42OTMyLDYxLjc4NDggTCA2MC42NzY4LDYxLjI3NjgsNjEuMjgyNiBMIDU0LjYwMzQsNDkuNzUDcwNSw1OC4zMzk0IEwgNTcuODE5Miw1MC4yN42MDM0LDQ5Ljc1ODkgTCA0MS45NzU4LDQ2LjU42MDM0LDQ5Ljc1ODkgTCA2MS41NDY2LDM4Ljcz3NTgsNDYuNTYxNSBMIDMxLjk2NjcsNTQu45NzU4LDQ2LjU2MTUgTCA0MS4xMTQ3LDMzLjU0NjIsNDQuNDM5NiBMIDQzLjg0MzQsMzUuMOTY2Nyw1NC44OTggTCAxOS43NDI1LDUwLjMjAyNjEsNTAuMTc2NiBMIDIwLjEwNTksNDQuTA1OSw0NC44NDM5IEwgMTkuMTg1NywzOS4140NTg4LDUwLjYxOTYgTCAxNy41Mzg2LDQ1LjIUzODYsNDUuMjg2OSBMIDE2LjYxODQsMzkuOTzQyNSw1MC4zOTgxIEwgMTUuNjc4OCw1MyNzg4LDUzLjc4MjcgTCAxMS42MTUxLDU3LjEExNDcsMzMuNTYzOCBMIDQ2LjIyMTUsMzEuNTuMjIxNSwzMS41MjIyIEwgNTEuMzI4MywyOSUuMDE4MywzMC44OTkzIEwgNTguMjgyNCwzNC44MTgyNCwzNC44MTg0IEwgNjEuNTQ2NiwzOC43uNTQ2NiwzOC43Mzc0IEwgNzQuNTYzLDM5LjzOTg2LDQxLjQxNiBMIDcyLjUxMDEsNDEuNkzMzknIHk9JzM4LjIxEzNzUnIHk9JzU5LjQ1MTEnIxJyB5PScyOS4zNzMS43NjI1JyB5PScyNS4wMz1=CC=C2C(CC(=O)N)=CNC2=C1 ZOAMBXDOGPRZLP-UHFFFAOYSA-N 0.000 description 2
- 230000004301 light adaptation Effects 0.000 description 2
- 201000008048 nemaline myopathy 5 Diseases 0.000 description 2
- 235000013615 non-nutritive sweetener Nutrition 0.000 description 2
- 235000010956 sodium stearoyl-2-lactylate Nutrition 0.000 description 2
- 230000003068 static EffectsNyz42MDE0LDE0Mi43ODUgTCAzNC43NTQ0LDE0NyMxMzEsMTM3LjQyNyBMIDM3LjQ2NjIsMTQxLjccuNDY2MiwxNDEuNzU2IEwgMzguNjE5MiwxNDYuM40NzI2LDEyNi43NjEgTCAzMi4zMTk2LDEyMi40MzInMxOTYsMTIyLjQzMiBMIDMxLjE2NjUsMTEjA3OCwxMjcuNzkgTCAyOC40NTQ3LDEyMy40N1NDcsMTIzLjQ2MSBMIDI3LjMwMTcsMTE5LjEzuNjI5LDEzMS4zNjUgTCA0Mi40MDA0LDEzMC4QwMDQsMTMwLjA5NCBMIDQ3LjE3MTksMTI4LjgyNzk3MiwxMzIuNTkgTCA2MS45MDA1LDEzNy4kwMDUsMTM3LjEwNyBMIDY2LjQwMzcsMTQxLjAzNywxNDEuNjI0IEwgODUuNzI3OCwxMzYNS43Mjc4LDEzNi40NzcgTCA5MC4zNDMxLDE0MS4wLjM0MzEsMTQxLjEwNiBMIDk0Ljk1ODuNDA5NCwxNTUuOTcyIEwgOTYuNTI1NywxNjIjUyNTcsMTYyLjk2IEwgOTQuNjQyLDE2QuNzM2LDE0OS4zMzcgTCAxMTEuOTUzLDE0Ny40TEuOTUzLDE0Ny40MTUgTCAxMTkuMTcxLDE0NS40Y0MiwxNjkuOTQ3IEwgNzUuMzE3OSwxNzUuMuMzLjcsMTIxLjAzNyBMIDE1Ny44MTksMTM1LjEMi45ODYsMTI1Ljk4NSBMIDE1Mi44NjksMTM1LjNy44MTksMTM1LjE5OSBMIDE3Ny4xNDMsMTMwLNy44MTksMTM1LjE5OSBMIDE1Mi42MTQsMTU0LjU4wNzQsMTMwLjU3MyBMIDE4MC45NTgsMTIzL45NTgsMTIzLjU4NSBMIDE4Mi44NDIsMTE2LjU4yMTMsMTI5LjUzMiBMIDE3Ny4wOTYsMTIyLwOTYsMTIyLjU0NCBMIDE3OC45OCwxMT3LNTcsMTQwLjYyNSBMIDIxMi4xNCwxNDAuMEzLjEyNywxNDIuMTgzIEwgMjEzLjY5NCwxND0LjM5NywxNDMuNzQgTCAyMTUuMjQ3LDE0Mi44UuNjY4LDE0NS4yOTcgTCAyMTYuODAxLDE0NCTYuOTM4LDE0Ni44NTUgTCAyMTguMzU0LDE0NS40guMjA4LDE0OC40MTIgTCAyMTkuOTA4LDE0NiuNDc5LDE0OS45NjkgTCAyMjEuNDYxLDE0NyAuNzQ5LDE1MS41MjcgTCAyMjMuMDE1LDEIuMDE5LDE1My4wODQgTCAyMjQuNTY4LDE1MCMuMjksMTU0LjY0MiBMIDIyNi4xMjIsMTUxNi43MTUMyIuNzA0LDExMy44MzEgTCAyMDguMjAxLDEwOSQuMzc1LDEyMS4xNzEgTCAyMDkuODcyLDExNikuODcyLDExNi42NTQgTCAyMDUuMzY5LDExMiIuNjE0LDE1NC41MDggTCAxMzMuMjksMTUOC42ODYsMTUxLjQxNSBMIDEzNS4xNTksMTUMi45NjA1JyB5PScxMzMuN42NjA4JyB5PScxNTIuOTzNjc1JyB5PScxMTQuMjIuMjg0NicgeT0nMTI4Ljg0NycgeT0nMTUxLjYzDAyNScgeT0nMTk1Lj45MDInIHk9JzExMS43OTEuMjYzJyB5PScxNDUuMODkuMDQnIHk9JzE1MS44jAyNycgeT0nMTU4LjAOTgnIHk9JzE42NjknIHk9JzExNS42041NDI3OSwzOC4xNjI2IEwgOS4wMjAzOSwzOS45TE1NCwzOS42NjQyIEwgMTAuNTkzLDQxLjQuMTM0ODEsMzUuOTgyMyBMIDguNjU3MjEsMzY1NzIxLDM0LjE4OSBMIDguMTc5NjEsMzIuM4wMzk3OCwzNi4yNzM5IEwgNy41NjIxOCwzNC40jU2MjE4LDM0LjQ4MDcgTCA3LjA4NDU4LDMyk0OTUsMzYuODcxIEwgMTEuNTEzNSwzNi4zNj41MTM1LDM2LjM2MDEgTCAxMy40MzIsMzUuODQzg5NSwzOC4xNjg1IEwgMjUuMzgwNSwzOS43zODA1LDM5Ljc2NDMgTCAyNi45NzE1LDQxLjMUzNTQsNDMuMTI1NCBMIDI2LjkyNTMsNDUuMYuOTI1Myw0NS4zODg2IEwgMjYuMzE1Miw0Ny42jA4NSw0MS45NjMxIEwgMzAuOTM2OCw0MS4zNDAuOTM2OCw0MS4zNDI5IEwgMzMuMjY1MSw0MC43zMTUyLDQ3LjY1MTggTCAyMC44NDAxLDQ5LNDAxLDQ5LjExIEwgMjAuMjMsNTjMsNTEuMzczMiBMIDE5LjYxOTksNTMuNjjI2NTEsNDAuNzIyOCBMIDM0LjczOTksMzUuMjU4MDUsNDAuMTk3MiBMIDM1LjYxMjgsMzYuMjI2NTEsNDAuNzIyOCBczOTksMzUuMjUyMSBMIDQwLjIxNSwzMyAuMjE1LDMzLjc5MzkgTCA0NC4yMTU1LDM3LjwMTI2LDM1LjE5NTkgTCA0Mi44MTI5LDM4LjAwyMTU1LDM3LjgwNjQgTCA0OS42OTA2LDM2LjM4yMTU1LDM3LjgwNjQgTCA0Mi43NDA3LDQzLjI4yMzc3LDM2LjQ5NTcgTCA1MC44NDc4LDM0LjIz44NDc4LDM0LjIzMjUgTCA1MS40NTc5LDMxLj42OTA2LDM2LjM0ODIgTCA1MS4yODE2LDM4MTYsMzcuOTQ0IEwgNTIuODcyNSwzOS41MuNTA5NSw0MC4xNDI4IEwgNTYuODM3OSwzOS41MYuODM3OSwzOS41MjI2IEwgNTkuMTY2MiwzOC45MDuNTI2MSwzOS4zNDM4IEwgNTkuNjA2NCwzOS4yNkuODg2LDM5Ljc4NTEgTCA2MC4wNDY1LDjI0Niw0MC4yMjYzIEwgNjAuNDg2NywzOS45AuNjA1OSw0MC42Njc2IEwgNjAuOTI2OSw0MC4zAuOTY1OCw0MS4xMDg4IEwgNjEuMzY3LDQwLjcMS4zMjU3LDQxLjU1MDEgTCA2MS44MDcyLDQxjg1Niw0MS45OTEzIEwgNjIuMjQ3NCw0MS40IuMDQ1NSw0Mi40MzI2IEwgNjIuNjg3NSw0MS43uNDA1NSw0Mi44NzM4IEwgNjMuMTI3Nyw0Mi4xuNzY1NCw0My4zMTUxIEwgNjMuNTY3OSw0MiOS4xNjYyLDM4LjkwMjUgTCA2MC42NDA5LDMzLjxNjY2LDQyLjkxNTEgTCA2OC42NDg45Mzg4LDQ0Ljg1NzcgTCA3Ny4yMzU0LDQ0LjI4wOTUxLDQ1LjMyMTkgTCA3MS40ODUxLDQ3LjUODUxLDQ3LjU4NTEgTCA3MC44NzUsNDkuODyLjkzNzUsMzIuODIwMiBMIDY1LjIzNDEsMzIuMjAjA0MjIsMzMuMDMxOCBMIDU5LjQ4MywzMS40kuNDgzLDMxLjQ2NzggTCA1Ny45MjM4LDI5Lj4yMzk3LDMzLjgzMTggTCA1OC42ODA1LDMyLjI42ODALjgzODgnIHk9JzM3LjM1kuNjAzODknIHk9JzQyLjgzMDuNjg3NDcnIHk9JzMxLjNC4zMTQnIHk9JzM1Ljg5OScgeT0nNDIuNDYuNDg0JyB5PSc1NC44NzIyJyB5PSczMS4xNjAMuNjkxJyB5PSc0MC42jA2MTQnIHk9JzQyLjUzQyNDMnIHk9JzQ0LjI540NzQ0JyB5PSc1MS4yMjjMnIHk9JzMyLjIcuMzMzNicgeT0nMjkuNzAy== CS(=O)(=O)OCCN(CCCl)C1=CC=C(C(=O)N[C@@H](CCC(O)=O)C(O)=O)C=C1 QVWYCTGTGHDWFQ-AWEZNQCLSA-N 0.000 description 1
- 280000842411 1020, Inc. companies 0.000 description 1
- 241000203716 Actinomycetaceae Species 0.000 description 1
- 280000405767 Alphanumeric companies9000004709 Chlorinated polyethylene Substances 0.000 description 1
- 241000723668 Fax Species 0.000 description 1
- 281999990625 Government0000000691 Houttuynia cordata Species 0.000 description 1
- 241000218195 Lauraceae Species 0.000 description 1
- 101710053600 MALD1 Proteins 0.000 description 1
- 101710067197 MT-I Proteins 0.000 description 1
- 101710066905 MTP1 Proteins 0.000 description 1
- 101710066908 MTP3 Proteins 0.000 description 1
- 101710080749 MTPA2 Proteins 0.000 description 1
- 229920000168 Microcrystalline cellulose Polymers 0.000 description 1
- 280000099600 NEXT, Inc. companies 0.000 description 1
- 229920000265 Polyparaphenylene Polymers 0.000 description 1
- 229920001299 Polypropylene fumarate Polymers 0.000 description 1
- 239000004793 Polystyrene Substances 0.000 description 1
- 101710018701 SLC40A1 Proteins 0.000 description 1
- 239000003677 Sheet moulding compound Substances 0.000 description 1
- 102100017041 Solute carrier family 40 member 1 Human genes 0.000 description 1
- 241001671220 Stachyuraceae Species 0.000 description 1
- 241000660331 Strophocheilidae Species 0.000 description 1
- 210000001138 Tears Anatomy 0.000 description 1
- 102100004325 Telethonin Human genes 0.000 description 1
- 281000184684 The Radio Network companies 0.000 description 1
- 230000036526 Transport Rate Effects 0.000 description 1
- 280000907835 Version 4 companies 0.000 description 1
- 280000990167 Web Access companies 0.000 description 1
- 280000157242 another, Inc. companies 0.000 description 1
- 230000002457 bidirectional Effects 0.000 description 1
- 125000004122 cyclic group Chemical group 0.000 description 1
- 238000001514 detection method Methods 0.000 description 1
- 238000005538 encapsulation Methods 0.000 description 1
- 229920005618 ethylene copolymer bitumen Polymers 0.000 description 1
- 239000000284 extracts Substances 0.000 description 1
- 101710051593 growth inhibitory factor Proteins 0.000 description 1
- 239000001981 lauryl tryptose broth Substances 0.000 description 1
- 239000004973 liquid crystal related substances Substances 0.000 description 1
- 230000014759 maintenance of location Effects 0.000 description 1
- 238000005259 measurements Methods 0.000 description 1
- 235000019813 microcrystalline cellulose Nutrition 0.000 description 1
- 238000010295 mobile communication Methods 0.000 description 1
- 238000005457 optimization Methods 0.000 description 1
- 230000002093 peripheral Effects 0.000 description 1
- 230000002085 persistent Effects 0.000 description 1
- 101710020605 phoN Proteins 0.000 description 1
- 239000004800 polyvinyl chloride Substances 0.000 description 1
- 229920000915 polyvinyl chlorides Polymers 0.000 description 1
- 238000003825 pressing Methods 0.000 description 1
- 230000001105 regulatory Effects 0.000 description 1
- 238000001228 spectrum Methods 0.000 description 1
- 239000000725 suspensions Substances 0.000 description 1
- 230000001360 synchronised Effects 0.000 description 1
- 230000002123 temporal effects Effects 0.000 description 1
- 101710073152 teneurin-C terminal associated peptide Proteins 0.000 description 1
Images
Classifications
- H—ELECTRICITY
- H04—ELECTRIC COMMUNICATION TECHNIQUE
- H04W—WIRELESS COMMUNICATION NETWORKS
- H04W88/00—Devices specially adapted for wireless communication networks, e.g. terminals, base stations or access point devices
- H04W88/12—Access point controller devices
-609—Authentication using certificates or pre-shared keys
-
- H04W12/1201—Wireless intrusion detection system [WIDS]; Wireless intrusion prevention system [WIPS]
- H04W12/1202—Protecting against rogue
- H—ELECTRICITY
- H04—ELECTRIC COMMUNICATION TECHNIQUE
- H04W—WIRELESS COMMUNICATION NETWORKS
- H04W92/00—Interfaces specially adapted for wireless communication networks
- H04W92/04—Interfaces between hierarchically different network devices
Abstract.
Description
- This application claims the benefit of U.S. Provisional Application 60/826,700, entitled “Radio Access Network—Generic Access to the Iu Interface for Femtocells”, filed Sep. 22, 2006; U.S. Provisional Application 60/869,900, entitled “Generic Access to the Iu Interface for Femtocells”, filed Dec. 13, 2006; U.S. Provisional Application 60/911,862, entitled “Generic Access to the Iu Interface for Femtocells”, filed Apr. 13, 2007; U.S. Provisional Application 60/949,826, entitled “Generic Access to the Iu Interface”, filed Jul. 13, 2007; U.S. Provisional Application 60/884,889, entitled “Methods to Provide Protection against service Theft for Femtocells”, filed Jan. 14, 2007; U.S. Provisional Application 60/893,361, entitled “Methods to Prevent Theft of Service for Femtocells Operating in Open Access Mode”, filed Mar. 6, 2007; U.S. Provisional Application 60/884,017, entitled “Generic Access to the Iu Interface for Femtocell—Stage 3”, filed Jan. 8, 2007; U.S. Provisional Application 60/911,864, entitled “Generic Access to the Iu Interface for Femtocell—Stage 3”, filed Apr. 13, 2007; U.S. Provisional Application 60/862,564, entitled “E-UMA—Generic Access to the Iu Interface”, filed Oct. 23, 2006; U.S. Provisional Application 60/949,853, entitled “Generic Access to the Iu Interface”, filed Jul. 14, 2007; and U.S. Provisional Application 60/954,549, entitled “Generic Access to the Iu Interfaces—Stage 2 Specification”, filed Aug. 7, 2007. The contents of each of the above mentioned provisional applications are hereby incorporated by reference.
- The invention relates to telecommunication. More particularly, this invention relates to a technique for seamlessly integrating voice and data telecommunication services across a licensed wireless system and a short-ranged licensed. The unlicensed wireless communication systems, however, require the use of dual-mode wireless transceivers to communicate with the licensed system over the licensed wireless frequencies and with the unlicensed system over the unlicensed wireless frequencies. The use of such dual-mode transceivers requires the service providers to upgrade the existing subscribers' transceivers which operate only on licensed wireless frequencies to dual-mode transceivers. Therefore, there is a need in the art to develop a system that provides the benefits of the systems described above, without the need for dual-mode transceivers.
-.
- The novel features of the invention are set forth in the appended claims. However, for purpose of explanation, several embodiments of the invention are set forth in the following figures.
FIG. 1illustrates an integrated communication system (ICS) of some embodiments. FIG. 2illustrates several applications of an ICS in some embodiments. FIG. 3illustrates the overall A/Gb-mode GAN functional architecture of some embodiments. FIG. 4illustrates the overall Iu-mode GAN functional architecture of some embodiments. FIG. 5illustrates the Femtocell functional architecture of some embodiments. FIG. 6illustrates Femtocell network architecture of some embodiments with an asynchronous transfer mode (ATM) interface towards the core network. FIG. 7illustrates Femtocell network architecture of some embodiments with IP interface towards the core network. FIG. 8illustrates CS Domain Control Plane Architecture of some embodiments. FIG. 9illustrates CS Domain User Plane Protocol Architecture of some embodiments. FIG. 10illustrates PS Domain Control Plane Architecture of some embodiments. FIG. 11illustrates PS Domain User Plane Protocol Architecture of some embodiments. FIG. 12illustrates the state diagram for Generic Access in the FAP of some embodiments. FIG. 13illustrates the state diagram in some embodiments for GA-CSR in the FAP for each UE. FIG. 14illustrates the state diagram in some embodiments for GA-PSR in the FAP for each UE. FIG. 15illustrates FAP initiated GA-CSR connection establishment in some embodiments. FIG. 16illustrates GA-CSR connection release of some embodiments. FIG. 17illustrates FAP initiated GA-PSR connection establishment of some embodiments. FIG. 18illustrates GA-PSR connection release in some embodiments. FIG. 19illustrates FAP power on discovery procedure of some embodiments. FIG. 20illustrates FAP power on registration procedure in some embodiments. FIG. 21illustrates the messages associated with the FAP initiated synchronization procedure in some embodiments. FIG. 22illustrates UE registration in some embodiments. FIG. 23illustrates UE Rove out in some embodiments. FIG. 24illustrates a scenario where the UE powers down and performs an IMSI detach in some embodiments. FIG. 25illustrates a scenario for loss of Up interface connectivity in some embodiments. FIG. 26illustrates FAP-initiated register update scenario of some embodiments. FIG. 27illustrates INC-initiated register update scenario in some embodiments. FIG. 28illustrates the FAP initiated synchronization procedure in some embodiments. FIG. 29illustrates voice bearer establishment procedures (for MO/MT calls, using Iu-UP over AAL2) in some embodiments. FIG. 30illustrates the mobile originated mobile-to-PSTN call in some embodiments. FIG. 31illustrates a mobile terminated PSTN-to-mobile call in some embodiments. FIG. 32illustrates call release by Femtocell subscriber in some embodiments. FIG. 33illustrates an example of relay of DTAP supplementary service messages in some embodiments. FIG. 34illustrates FAP initiated GA-PSR Transport Channel activation in some embodiments. FIG. 35illustrates FAP initiated Transport Channel deactivation in some embodiments. FIG. 36illustrates network initiated Transport Channel Activation for user data service in some embodiments. FIG. 37illustrates network initiated Transport Channel deactivation in some embodiments. FIG. 38illustrates Femtocell User Plane Data Transport procedures in some embodiments. FIG. 39illustrates Uplink Control Plane Data Transport of some embodiments. FIG. 40illustrates Downlink Control Plane Data Transport of some embodiments. FIG. 41illustrates the protocol architecture for CS mode SMS in some embodiments. FIG. 42illustrates the GAN protocol architecture for packet mode SMS in some embodiments. FIG. 43illustrates a mobile originated SMS transfer via GAN circuit mode in some embodiments. FIG. 44illustrates a CS mode mobile terminated SMS transfer via Femtocell in some embodiments. FIG. 45illustrates a service area based routing scenario of some embodiments. FIG. 46illustrates GAN Femtocell security mechanisms in some embodiments. FIG. 47illustrates EAP-SIM authentication procedure in some embodiments. FIG. 48illustrates EAP-AKA authentication procedure of some embodiments. FIG. 49illustrates the message flow for security mode control in some embodiments. FIG. 50illustrates the AKA procedure used for mutual authentication in some embodiments. FIG. 51illustrates the high level procedure which can result in theft of service by a rogue FAP. FIG. 52illustrates the Femtocell service theft prevention approach of some embodiments. FIG. 53illustrates the Femtocell service theft prevention in some embodiments. FIG. 54illustrates the Service Access Control for new FAP connecting to Femtocell network in some embodiments. FIG. 55illustrates the Service Access Control for the FAP getting redirected in Femtocell network in some embodiments. FIG. 56illustrates the Service Access Control for FAP registering in restricted UMTS coverage area in some embodiments. FIG. 57illustrates the Service Access Control for Unauthorized UE accessing authorized FAP in some embodiments. FIG. 58conceptually illustrates a computer system with which some embodiments are implemented.
-.
- Throughout the following description, acronyms commonly used in the telecommunications industry for wireless services are utilized along with acronyms specific to the present invention. A table of acronyms used in this application is included in Section XV.
-.
- Several more detailed embodiments of the invention are described in sections below. Specifically, Section I describes the overall integrated communication system in which some embodiments are incorporated. The discussion in Section I is followed by a discussion of the system architecture of a Femtocell system in Section II. Next, Section III describes the protocol architecture of the Femtocell system. Section IV then describes the resource management procedures of the Femtocell system in some embodiments. Next, Section V presents the mobility management functions of the Femtocell system in some embodiments.
- Next, Section VI describes the call management procedures of the Femtocell system. This section is followed by Section VII which describes the packet services of the Femtocell system in some embodiments. Error handling procedures are described in Section VIII. Lists of messages and information elements used in different embodiments are provided in Section IX. Short Message Services support of the Femtocell system is described in Section X followed by the description of the emergency services in Section XI.
- The Femtocell system security functions are described in Section XII. This description is followed by Femtocell system service access control discussed in Section XIII. Next, Section XIV description of a computer system with which some embodiments of the invention are implemented. Finally, Section XV lists the abbreviations used.
- A. Integrated Communication Systems (ICS)
FIG. 1illustrates an integrated communication system (ICS) architecture 100 in accordance with some embodiments of the present invention. ICS architecture 100 enables user equipment (UE) 102 to access a voice and data network 165 via either a licensed air interface 106 or an ICS access interface 110 through which components of the licensed wireless core network 165 are alternatively accessed. In some embodiments, a communication session through either interface includes voice services, data services, or both.
- The mobile core network 165 includes one or more Home Location Registers (HLRs) 150 and databases 145 for subscriber authentication and authorization. Once authorized, the UE 102 may access the voice and data services of the mobile core network 165. In order to provide such services, the mobile core network 165 includes a mobile switching center (MSC) 160 for providing access to the circuit switched services (e.g., voice and data). Packet switched mobile core network 165 to various external data packet services networks (not shown). Moreover, as the user equipment of a licensed wireless network traverses multiple service regions and thus multiple SGSNs, it is the role of the GGSN 157 to provide a static gateway into the external data networks.
- In the illustrated embodiment, components such the GSM/EDGE Radio Access Network (GERAN). An example of a system using A and Gb interfaces to access GERAN is shown in
FIG. 3described further below.
- The licensed wireless channel 106 may comprise any licensed wireless service having a defined UTRAN or GERAN interface protocol (e.g., Iu-cs and Iu-ps interfaces for UTRAN or A and Gb interfaces for GERAN) for a voice/data network. The UTRAN 185 typically includes at least one Node B 180 and a Radio Network Controller (RNC) 175 for managing the set of Node Bs 180. Typically, the multiple Node Bs 180 are configured in a cellular configuration (one per each cell) that covers a wide service area. A licensed wireless cell is sometimes referred to as a macro cell which is a logical term used to reference, e.g., the UMTS radio cell (i.e., 3G cell) under Node-B/RNC which is used to provide coverage typically in the range of tens of kilometers. Also, the UTRAN or GERAN is sometimes referred to as a macro network.
- Each RNC 175 communicates with components of the core network 165 through a standard radio network controller interface such as the Iu-cs and Iu-ps interfaces depicted in
FIG. 1. For example, a RNC 175 communicates with MSC 160 via the UTRAN Iu-cs interface for circuit switched services. Additionally, the RNC 175 communicates with SGSN 155 via the UTRAN Iu-ps interface for packet switched services through GGSN 157. Moreover, one of ordinary skill in the art will recognize that in some embodiments, other networks with other standard interfaces may apply. For example, the RNC 175 in a GERAN network is replaced with a Base Station Controller (BSC) that communicates with the MSC 160 via an A interface for the circuit switched services and the BSC communicates with the SGSN via a Gb interface of the GERAN network for packet switched services.
- In some embodiments of the ICS architecture, the user equipment 102 use the services of the mobile core network (CN) 165 via a second communication network facilitated by the ICS access interface 110 and a Generic Access Network Controller (GANC) 120 (also referred to as a Universal Network Controller or UNC).
- In some embodiments, the voice and data services over the ICS access interface 110 are facilitated via an access point 114 communicatively coupled to a broadband IP network 116. In some embodiments, the access point 114 is a generic wireless access point that connects the user equipment 102 to the ICS network through an unlicensed wireless network 118 created by the access point 114. In some other embodiments, the access point 114 is a Femtocell access point (FAP) 114 communicatively coupled to a broadband IP network 116. The FAP facilitates short-range licensed wireless communication sessions 118 that operate independent of the licensed communication session 106. In some embodiments, the GANC, FAP, UE, and the area covered by the FAP are collectively referred to as a Femtocell System. A Femtocell spans a smaller area (typically few tens of meters) than a macro cell. In other words, the Femtocell is a micro cell that has a range that is 100, 1000, or more times less than a macro cell. In case of the Femtocell system, the user equipment 102 connects to the ICS network through a short-range licensed wireless network created by the FAP 114. Signals from the FAP are then transmitted over the broadband IP network 116.
- The signaling from the UE 102 is passed over the ICS access interface 110 to the GANC 120. After the GANC 120 performs authentication and authorization of the subscriber, the GANC 120 communicates with components of the mobile core network 165 using a radio network controller interface that is the same or similar to the radio network controller interface of the UTRAN described above, and includes a UTRAN Iu-cs interface for circuit switched services and a UTRAN Iu-ps interface for packet switched services (e.g., GPRS). In this manner, the GANC 120 uses the same or similar interfaces to the mobile core network as a UTRAN Radio Access Network Subsystem (e.g., the Node B 180 and RNC 175).
- In some embodiments, the GANC 120 communicates with other system components of the ICS system through one or more of between the AAA server 170 and the HLR 160. Optionally, some embodiments use the “Gn′” interface which is a modified interface for direct communications with the data services gateway (e.g., GGSN) of the mobile core network. Some embodiments optionally include the “S1” interface. In these embodiments, the “S1” interface provides an authorization and authentication interface from the GANC 120 to an AAA sever 140. In some embodiments, the AAA server 140 that supports the S1 interface and the AAA server 170 that supports Wm interface may be the same. More details of the S1 interface are described in U.S. application Ser. No. 11/349,025, entitled “Service Access Control Interface for an Unlicensed Wireless Communication System”, filed Feb. 6, 2006.
- (a UE is camped on a cell when the UE has completed the cell selection/reselection process and has chosen a cell; the UE monitors system information and, in most cases, paging information). In some embodiments, the GANC 120 may pass this information to the AAA server 140 to authenticate the subscriber and determine the services (e.g., voice and data) available to the subscriber. If approved by the AAA server 140 for access, the GANC 120 will permit the UE 102 to access voice and data services of the ICS system.
- These circuit switched and packet switched services are seamlessly provided by the ICS to the UE 102 through the various interfaces described above. In some embodiments, when data services are requested by the UE 102, the ICS uses the optional Gn′ interface for directly communicating with a GGSN 157. The Gn′ interface allows the GANC 120 to avoid the overhead and latency associated with communicating with the SGSN 155 over the Iu-ps interface of the UTRAN or the Gb interface of the GSM core networks prior to reaching the GGSN 157.
- B. Applications of ICS
- An ICS provides scalable and secure interfaces into the core service network of mobile communication systems.
FIG. 2illustrates several applications of an ICS in some embodiments. As shown, homes, offices, hot spots, hotels, and other public and private places 205 are connected to one or more network controllers 210 (such as the GANC 120 shown in FIG. 1) through the Internet 215. The network controllers in turn connect to the mobile core network 220 (such as the core network 165 shown in FIG. 1). FIG. 2also shows several user equipments. These user equipments are just examples of user equipments that can be used for each application. Although in most examples only one of each type of user equipments is shown, one of ordinary skill in the art would realize that other type of user equipments can be used in these examples without deviating from the teachings of the invention. Also, although only one of each type of access points, user equipment, or network controllers are shown, many such access points, user equipments, or network controllers may be employed in FIG. 2. For instance, an access point may be connected to several user equipment, a network controller may be connected to several access points, and several network controllers may be connected to the core network. The following sub-sections provide several examples of services that can be provided by an ICS.
- 1. Wi-Fi
- A Wi-Fi access point 230 enables a dual-mode cellular/Wi-Fi UEs 260-265 to receive high-performance, low-cost mobile services when in range of a home, office, or public Wi-Fi network. With dual-mode UEs, subscribers can roam and handover between licensed wireless communication system and Wi-Fi access and receive a consistent set of services as they transition between networks.
- 2. Femtocells
- A Femtocell enables user equipments, such as standard mobile stations 270 and wireless enabled computers 275 shown, to receive low cost services using a short-range licensed wireless communication sessions through a FAP 235.
- 3. Terminal Adaptors
- Terminal adaptors 240 allow incorporating fixed-terminal devices such as telephones 245, Faxes 250, and other equipments that are not wireless enabled within the ICS. As far as the subscriber is concerned, the service behaves as a standard analog fixed telephone line. The service is delivered in a manner similar to other fixed line VoIP services, where a UE is connected to the subscriber's existing broadband (e.g., Internet) service.
- 4. WiMAX
- Some licensed wireless communication system operators are investigating deployment of WiMAX networks in parallel with their existing cellular networks. A dual mode cellular/WiMAX UE 255 enables a subscriber to seamlessly transition between a cellular network and such a WiMAX network through a WiMax access point 290.
- 5. SoftMobiles
- Connecting laptops 280 to broadband access at hotels and Wi-Fi hot spots has become popular, particularly for international business travelers. In addition, many travelers are beginning to utilize their laptops and broadband connections for the purpose of voice communications. Rather than using mobile phones to make calls and pay significant roaming fees, they utilize SoftMobiles (or SoftPhones) and VoIP services when making long distance calls.
- To use a SoftMobile service, a subscriber would place a USB memory stick 285 with an embedded SIM into a USB port of their laptop 280. A SoftMobile client would automatically launch and connect over IP to the mobile service provider. From that point on, the subscriber would be able to make and receive mobile calls as if she was in her home calling area.
- Several examples of Integrated Communication Systems (ICS) are given in the following sub-sections. A person of ordinary skill in the art would realize that the teachings in these examples can be readily combined. For instance, an ICS can be an IP based system and have an A/Gb interface towards the core network while another ICS can have a similar IP based system with an Iu interface towards the core network.
- C. Integrated Systems with A/Gb and/or Iu Interfaces Towards the Core Network
FIG. 3illustrates the A/Gb-mode Generic Access Network (GAN) functional architecture of some embodiments. The GAN includes one or more Generic Access Network Controllers (GANC) 310 and one or more generic IP access networks 315. One or more UEs 305 (one is shown for simplicity) can connect to a GANC 310 through a generic IP access network 315. The GANC 310 has the capability to appear to the core network 325 as a GSM/EDGE Radio Access Network (GERAN) Base Station Controller (BSC). The GANC 310 includes a Security Gateway (SeGW) 320 that terminates secure remote access tunnels from the UE 305, providing mutual authentication, encryption and data integrity for signaling, voice and data traffic.
- The generic IP access network 315 provides connectivity between the UE 305 and the GANC 310. The IP transport connection extends from the GANC 310 to the UE 305. A single interface, the Up interface, is defined between the GANC 310 and the UE 305.
- The GAN co-exists with the GERAN and maintains the interconnections with the Core Network (CN) 325 via the standardized interfaces defined for GERAN. These standardized interfaces include the A interface to Mobile Switching Center (MSC) 330 for circuit switched services, Gb interface to Serving GPRS Support Node (SGSN) 335 for packet switched services, Lb interface to Serving Mobile Location Center (SMLC) 350 for supporting location services, and an interface to Cell Broadcast Center (CBC) 355 for supporting cell broadcast services. The transaction control (e.g. Connection Management, CC, and Session Management, SM) and user services are provided by the core network (e.g. MSC/VLR and the SGSN/GGSN).
- As shown, the SeGW 320 is connected to a AAA server 340 over the Wm interface. The AAA server 340 is used to authenticate the UE 305 when it sets up a secure tunnel. Some embodiments require only a subset of the Wm functionalities for the GAN application. In these embodiments, as a minimum the GANC-SeGW shall support the Wm authentication procedures.
FIG. 4illustrates the Iu-mode Generic Access Network (GAN) functional architecture of some embodiments. The GAN includes one or more Generic Access Network Controllers (GANC) 410 and one or more generic IP access networks 415. One or more UEs 405 (one is shown for simplicity) can be connected to a GANC 410 through a generic IP access network 415. In comparison with the GANC 310, the GANC 410 has the capability to appear to the core network 425 as a UMTS Terrestrial Radio Access Network (UTRAN) Radio Network Controller (RNC). In some embodiments, the GANC has the expanded capability of supporting both the Iu and A/Gb interfaces to concurrently support both Iu-mode and A/Gb-mode UEs. Similar to the GANC 310, the GANC 410 includes a Security Gateway (SeGW) 420 that terminates secure remote access tunnels from the UE 405, providing mutual authentication, encryption and data integrity for signaling, voice and data traffic.
- The generic IP access network 415 provides connectivity between the UE 405 and the GANC 410. The IP transport connection extends from the GANC 410 to the UE 405. A single interface, the Up interface, is defined between the GANC 410 and the UE 405. Functionality is added to this interface, over the UP interface shown in
FIG. 3, to support the Iu-mode GAN service.
- The GAN co-exists with the UTRAN and maintains the interconnections with the Core Network (CN) 425 via the standardized interfaces defined for UTRAN. These standardized interfaces include the Iu-cs interface to Mobile Switching Center (MSC) 430 for circuit switched services, Iu-ps interface to Serving GPRS Support Node (SGSN) 435 for packet switched services, Iu-pc interface to Serving Mobile Location Center (SMLC) 450 for supporting location services, and Iu-bc interface to Cell Broadcast Center (CBC) 455 for supporting cell broadcast services. The transaction control (e.g. Connection Management, CC, and Session Management, SM) and user services are provided by the core network (e.g. MSC/VLR and the SGSN/GGSN).
- As shown, the SeGW 420 is connected to a AAA server 440 over the Wm interface. The AAA server 440 is used to authenticate the UE 405 when it sets up a secure tunnel. Some embodiments require only a subset of the Wm functionalities for the Iu mode GAN application. In these embodiments, as a minimum the GANC-SeGW shall support the Wm authentication procedures.
FIG. 5illustrates the Femtocell system functional architecture of some embodiments. As shown, many components of the system shown in FIG. 5are similar to components of FIG. 4. In addition, the Femtocell system includes a Femtocell Access Point (FAP) 560 which communicatively couples the UE 505 to the GANC 510 through the Generic IP Access Network 515. The interface between the UE 505 and the FAP 560 is referred to as the Uu interface in this disclosure. The UE 505 and the FAP 560 communicate through a short-range wireless air interface using licensed wireless frequencies. The GANC 510 is an enhanced version of the GANC 410 shown in FIG. 4. The Security Gateway (SeGW) 520 component of the GANC 510 terminates secure remote access tunnels from the FAP 560, providing mutual authentication, encryption and data integrity for signaling, voice and data traffic.
- The Femtocell Access Point (AP) Management System (AMS) 570 is used to manage a large number of FAPs. The AMS 570 functions include configuration, failure management, diagnostics, monitoring and software upgrades. The interface between the AMS 570 and the FAP 560 is referred to as the S3 interface. The S3 interface enables secure access to Femtocell access point management services for FAPs. All communication between the FAPs and AMS is exchanged via the Femtocell secure tunnel that is established between the FAP and SeGW 520. As shown, the AMS 570 accesses to the AP/subscriber databases (Femtocell DB) 575 which provides centralized data storage facility for Femtocell AP (i.e., the FAP) and subscriber information. Multiple Femtocell system elements may access Femtocell DB via AAA server.
- The IP Network Controller (INC) 565 component of the GANC 510 interfaces with the AAA/proxy server 540 through the S1 interface for provisioning of the FAP related information and service access control. As shown in
FIG. 5, the AAA/proxy server 540 also interfaces with the AP/subscriber databases 575.
- A. ATM and IP Based Architectures
- In some embodiments, the Femtocell system uses Asynchronous Transfer Mode (ATM) based Iu (Iu-cs and Iu-ps) interfaces towards the CN. In some embodiments, the Femtocell system architecture can also support an IP based Iu (Iu-cs and Iu-ps) interface towards the CN.
- A person of ordinary skill in the art would realize that the same examples can be readily applied to other types of ICS. For instance, these examples can be used when the ICS access interface 110 (shown in
FIG. 1) uses unlicensed frequencies (instead of Femtocell's licensed frequencies), the access point 114 is a generic WiFi access point (instead of a FAP), etc. Also, a person of ordinary skill in the art would realize that the same examples can be readily implemented using A/Gb interfaces (described above) instead of Iu interfaces. FIG. 6illustrates the basic elements of the Femtocell system architecture with Asynchronous Transfer Mode (ATM) based Iu (Iu-cs and Iu-ps) interfaces towards the CN in some embodiments. These elements include the user equipment (UE) 605, the FAP 610, and the Generic Access Network Controller (GANC) 615, and the AMS 670.
- For simplicity, only one UE and one FAP are shown. However, each GANC can support multiple FAPs and each FAP in turn can support multiple UEs. As shown, the GANC 615 includes an IP Network Controller (INC) 625, a GANC Security Gateway (SeGW) 630, a GANC Signaling Gateway 635, a GANC Media Gateway (MGW) 640, an ATM Gateway (645). Elements of the Femtocell are described further below.
FIG. 7illustrates the basic elements of the Femtocell system architecture with an IP based Iu (Iu-cs and Iu-ps) interface towards the CN in some embodiments. For simplicity, only one UE and one FAP are shown. However, each GANC can support multiple FAPs and each FAP in turn can support multiple UEs. This option eliminates the need for the GANC Signaling gateway 635 and also the ATM gateway 645. Optionally for IP based Iu interface, the GANC Media Gateway 640 can also be eliminated if the R4 MGW 705 in the CN can support termination of voice data i.e. RTP frames as defined in “Real-Time Transport Protocol (RTP) Payload Format and File Storage Format for the Adaptive Multi-Rate (AMR) and Adaptive Multi-Rate Wideband (AMR-WB) Audio Codecs”, IETF RFC 3267, hereinafter “RFC 3267”.
- Also shown in
FIGS. 6 and 7are components of the licensed wireless communication systems. These components are 3G MSC 650, 3G SGSN 655, and other Core Network System (shown together) 665. The 3G MSC 650 provides a standard Iu-cs interface towards the GANC. Another alternative for the MSC is shown in FIG. 7. As shown, the MSC 750 is split up into a MSS (MSC Server) 775 for Iu-cs based signaling and MGW 780 for the bearer path. R4 MSC 750 is a release 4 version of a 3G MSC with a different architecture i.e. R4 MSC is split into MSS for control traffic and a MGW for handling the bearer. A similar MSC can be used for the ATM architecture of FIG. 6. Both architectures shown in FIGS. 6 and 7are also adaptable to use any future versions of the MSC.
- The 3G SGSN 655 provides packet services (PS) via the standard Iu-ps interface. The SGSN connects to the INC 625 for signaling and to the SeGW 630 for PS data. The AAA server 660 communicates with the SeGW 630 and supports the EAP-AKA and EAP-SIM procedures used in IKEv2 over the Wm interface and includes a MAP interface to the HLR/AuC. This system also supports the enhanced service access control functions over the S1 interface.
- For simplicity, in several diagrams throughout the present application, only the INC component of the GANC is shown. Also, whenever the INC is the relevant component of the GANC, references to the INC and GANC are used interchangeably.
- B. Functional Entities
- 1. User Equipment (UE)
- The UE includes the functions that are required to access the Iu-mode GAN. In some embodiments, the UE additionally includes the functions that are required to access the A/Gb-mode GAN. In some embodiments, the User Equipment (UE) is a dual mode (e.g., GSM and unlicensed radios) handset device with capability to switch between the two modes. The user equipment can support either Bluetooth® or IEEE 802.11 protocols. In some embodiments, the UE supports an IP interface to the access point. In these embodiments, the IP connection from the GANC extends all the way to the UE. In some other embodiments, the User Equipment (UE) is a standard 3G handset device operating over licensed spectrum of the provider.
- In some embodiments, the user equipment includes a cellular telephone, smart phone, personal digital assistant,.
- 2. Femtocell Access Point (FAP)
- The FAP is a licensed access point which offers a standard radio interface (Uu) for UE connectivity. The FAP provides radio access network connectivity for the UE using a modified version of the standard GAN interface (Up). In some embodiments, the FAP is equipped with either a standard 3G USIM or a 2G SIM.
- In accordance with some embodiments, the FAP 610 will be located in a fixed structure, such as a home or an office building. In some embodiments, the service area of the FAP includes an indoor portion of a building, although it will be understood that the service area may include an outdoor portion of a building or campus.
- 3. Generic Access Network Controller (GANC)
- The GANC 510 is an enhanced version of the GANC defined in “Generic access to the A/Gb interface; Stage 2”, 3GPP TS 43.318 standard, hereinafter “TS 43.318 standard”. The GANC appears to the core network as a UTRAN Radio Network Controller (RNC). The GANC includes a Security Gateway (SeGW) 520 and IP Network Controller (INC) 565. In some embodiments (not shown in
FIG. 5), the GANC also includes GANC Signaling Gateway 635, a GANC Media Gateway (MGW) 640, and/or an ATM Gateway (645).
- The SeGW 520 provides functions that are defined in TS 43.318 standard and “Generic access to the A/Gb interface; Stage 3”, 3GPP TS 44.318 standard. The SeGW terminates secure access tunnels from the FAP, providing mutual authentication, encryption and data integrity for signaling, voice and data traffic. The SeGW 520 is required to support EAP-SIM and EAP-AKA authentication for the FAP 560.
- The INC 565 is the kay GANC element. In some embodiments, the INC is front-ended with a load balancing router/switch subsystem which connects the INC to the other GAN systems; e.g., GANC security gateways, local or remote management systems, etc.
- The GANC MGW 640 provides the inter-working function between the Up interface and the Iu-CS user plane. The GANC MGW would provide inter-working between RFC 3267 based frames received over the Up interface and Iu-UP frames towards the CN. The GANC Signaling GW 635 provides protocol conversion between SIGTRAN interface towards the INC and the ATM based Iu-cs interface towards the CN. The ATM GW 645 provides ATM/IP gateway functionality, primarily routing Iu-ps user plane packets between the SeGW (IP interface) and CN (AAL5 based ATM interface).
- 4. Broadband IP Network
- The Broadband IP Network 515 represents all the elements that collectively, support IP connectivity between the GANC SeGW 520 function and the FAP 560. This includes: (1) Other Customer premise equipment (e.g., DSL/cable modem, WLAN switch, residential gateways/routers, switches, hubs, WLAN access points), (2) Network systems specific to the broadband access technology (e.g., DSLAM or CMTS), (3) ISP IP network systems (edge routers, core routers, firewalls), (4) Wireless service provider (WSP) IP network systems (edge routers, core routers, firewalls), and (5) Network address translation (NAT) functions, either standalone or integrated into one or more of the above systems.
- 5. AP Management System (AMS)
- The AMS 570 is used to manage a large number of FAPs 560 including configuration, failure management, diagnostics, monitoring and software upgrades. The access to AMS functionality is provided over secure interface via the GANC SeGW 520.
- Some embodiments of the above mentioned devices, such as the user equipment, FAP, or GANC, include electronic components, such as microprocessors and memory (not shown), that store computer program instructions (such as including higher-level code that are executed by a computer, an electronic component, or a microprocessor using an interpreter.
- The GAN Femtocell architecture of some embodiments in support of the CS Domain control plane is illustrated in
FIG. 8. The figure shows different protocol layers for the UE 805, FAP 810, Generic IP Network 815, SeGW 820, INC 825, and MSC 830. FIG. 8also shows the three interfaces Uu 840, Up 845 and Iu-cs 850.
- 1. Up Interface for the CS Domain Control Plane
- The main features of the Up interface 845 for the CS domain control plane are as follows. The underlying Access Layers 846 and Transport IP layer 848 provide the generic connectivity between the FAP 810 and the GANC (which includes SeGW 820 and INC 825). The IPSec encapsulation security payload (ESP) layer 850 provides encryption and data integrity.
- The TCP 852 provides reliable transport for the GA-RC 854 between FAP 810 and GANC and is transported using the Remote IP layer 856. The GA-RC 854 manages the IP connection, including the Femtocell registration procedures.
- The GA-CSR 858 protocol performs functionality equivalent to the UTRAN RRC protocol, using the underlying connection managed by the GA-RC 854. Protocols, such as MM 860 and above, are carried transparently between the UE 805 and MSC 830. The GANC terminates the GA-CSR 858 protocol and inter-works it to the Iu-cs 850 interface using Radio Access Network Application Part (RANAP) 862 messaging.
- The Remote IP layer 856 is the ‘inner’ IP layer for IPSec tunnel mode and is used by the FAP 810 to be addressed by the INC 825. Remote IP layer 856 is configured during the IPSec connection establishment. In some embodiments, the Iu-cs signaling transport layers 870 are per “UTRAN Iu interface signalling transport”, 3GPP TS 25.412 standard, hereinafter “TS 25.412”.
- The GAN Femtocell protocol architecture of some embodiments in support of the CS domain user plane is illustrated in
FIG. 9. The figure shows different protocol layers for the UE 905, FAP 910, Generic IP Network 915, SeGW 920, Media GW 925, and MSC 930. FIG. 9also shows the three interfaces Uu 935, Up 940, and Iu-cs 945.
- The main features of the CS domain user plane are as follows. The underlying Access Layers 950 and Transport IP layer 952 provide the generic connectivity between the FAP 910 and the GANC. The IPSec layer 954 provides encryption and data integrity.
- The FAP 910 frames the CS user data 956 (received over the air interface) into RFC 3267 defined frames. RFC 3267 user data 958 is transported over the Up interface to the GANC Media GW 925. The GANC Media GW 925 will provide inter-working function 960 with Iu-UP (e.g., Support Mode) towards the CN. In some embodiments, Iu-UP uses ATM as a transport mechanism between the CN and the GANC Media GW 925. In some embodiments, Iu-Up uses IP as a transport mechanism between the CN and the GANC Media GW 925. In some embodiments, the CS domain user plane architecture supports AMR codec, as specified in “AMR speech codec; General description”, 3GPP TS 26.071 standard with support for other codec being optional. In some embodiments, the Iu-cs Data transport layers 970 are per TS 25.414.
- The GAN Femtocell architecture of some embodiments in support of the PS Domain Control Plane is illustrated in
FIG. 10. The figure shows different protocol layers for the UE 1005, FAP 1010, Generic IP Network 1015, SeGW 1020, INC 1025, and SGSN 1030. FIG. 10also shows the three interfaces Uu 1040, Up 1045, and Iu-ps 1050.
- The main features of the Up interface 1045 for the PS domain control plane are as follows. The underlying Access Layers 1052 and Transport IP layer 1054 provide the generic connectivity between the FAP 1010 and the GANC. The IPSec layer 1056 provides encryption and data integrity.
- TCP 1058 provides reliable transport for the GA-PSR 1060 signaling messages between FAP 1010 and GANC. The GA-RC 1062 manages the IP connection, including the Femtocell registration procedures. The GA-PSR 1060 protocol performs functionality equivalent to the UTRAN RRC protocol.
- Upper layer protocols 1064, such as for GMM, SM and SMS, are carried transparently between the UE 1005 and CN. The GANC terminates the GA-PSR 1060 protocol and inter-works it to the Iu-ps interface 1050 using RANAP 1070. In some embodiments, the Iu-ps signaling transport layers 1080 are per TS 25.412.
FIG. 11illustrates the GAN Femtocell architecture for the PS Domain User Plane of some embodiments. The figure shows different protocol layers for the UE 1105, FAP 1110, Generic IP Network 1115, SeGW 1120, Packet Gateway (Packet GW) 1125, and SGSN 1130. FIG. 11also shows the three interfaces Uu 1135, Up 1140, and Iu-ps 1145.
- The main features of the Up interface 1140 for PS domain user plane are as follows. The underlying Access Layers 1150 and Transport IP layer 1155 provides the generic connectivity between the FAP 1110 and the GANC. The IPSec layer 1160 provides encryption and data integrity. The GTP-U 1170 protocol operates between the FAP 1110 and the SGSN 1130 transporting the upper layer payload (i.e. user plane data) across the Up 1140 and Iu-ps interfaces 1145.
- The packet GW 1125 provides either ATM GW functionality for ATM transport or IP GW functionality for IP transport. In some embodiment, the Packet GW 1125 functionality is combined in the SeGW 1120. Additionally, in some embodiments, the Packet GW provides a GTP-U proxy functionality as well, where the GTP-U is optionally terminated in the Packet GW 1125 on either side. In the embodiments that the Packet GW 1125 provides ATM GW functionality, the packet GW 1125 provides transport layer conversion between IP (towards the FAP 1110) and ATM (towards the CN). User data 1180 is carried transparently between the UE 1105 and CN. In some embodiments, the Iu-ps Data transport layers 1180 are per TS 25.414.
- In some embodiments, instead of using separate CSR and PSR protocols for communication between the FAP and the GANC, as described in this Specification, a single protocol, Generic Access Radio Resource Control (GA-RRC) is used. In these embodiments, the GA-CSR 858 (shown in
FIG. 8) and GA-PSR 1060 (shown in FIG. 10) protocol layers are replaced with one protocol layer GA-RRC. Details of the GA-RRC protocol architecture and messaging are further described in the U.S. patent application Ser. No. 11/778,040, entitled “Generic Access to the Iu Interface”, filed on Jul. 14, 2007. This Application is incorporated herein by reference. One of ordinary skill in the art would be able to apply the disclosure of the present application regarding the GA-CSR and GA-PSR protocols to the GA-RRC protocol.
- A. GA-RC (Generic Access Resource Control)
- The GA-RC protocol provides a resource management layer, with the following functions. (1) Discovery and registration with GANC, (2) Registration update with GANC, (3) Application level keep-alive with GANC, and (4) Support for identification of the FAP being used for Femtocell access.
- 1. States of the GA-RC Sub-Layer
FIG. 12illustrates different states of the GA-RC sub-layer in the FAP in some embodiments. As shown, the GA-RC sub-layer in the FAP can be in one of two states: GA-RC-DEREGISTERED 1205 or GA-RC-REGISTERED 1210.
- The FAP creates and maintains a separate state for the GA-RC sub-layer for each device it registers. For instance, if the FAP registers three UEs, the FAP creates and maintains three separate GA-RC sub-layers for these three UEs. Also, the FAP supports registration for two types of devices i.e. the FAP and the UE. Based on the type of device, the functionality of the GA-RC sub-layer can vary.
- a) GA-RC Sub-Layer for Device Type FAP
- For the FAP device type, the GA-RC sub-layer is in the GA-RC-DEREGISTERED state 1205 upon power-up of the FAP. In this state, the FAP has not registered successfully with the GANC. The FAP may initiate the Registration procedure when in the GA-RC-DEREGISTERED state 1205. The FAP returns to GA-RC-DEREGISTERED state 1205 on loss of TCP or IPSec connection or on execution of the De-registration procedure. Upon transition to GA-RC-DEREGISTERED state 1205, the FAP must trigger an implicit deregistration all the UEs currently camped on the FAP.
- In the GA-RC-REGISTERED state 1210, the FAP is registered with the Serving GANC. The FAP has an IPSec tunnel and a TCP connection established to the Serving GANC through which the FAP may exchange GA-RC, GA-CSR and GA-PSR signaling messages with the GANC. While the FAP remains in the GA-RC-REGISTERED state 1210 it performs application level keep-alive with the GANC.
- b) GA-RC Sub-Layer for Device Type UE
- For the UE device type, the GA-RC sub-layer in the FAP (for each UE) is in the GA-RC-DEREGISTERED state 1205 upon UE rove-in and creation of a subsequent TCP connection between the FAP and the GANC. In this state, the UE has not been registered successfully (by the FAP) with the GANC. The FAP may initiate the Registration procedure when UE specific GA-RC sub-layer is in the GA-RC-DEREGISTERED state 1205. The GA-RC sub-layer returns to GA-RC-DEREGISTERED state 1205 on loss of TCP or IPSec connection or on execution of the De-registration procedure. Upon loss of TCP connection, FAP may attempt to re-establish the corresponding TCP session and perform the synchronization procedure. A failure to successfully re-establish the TCP session will result in GA-RC layer transitioning to GA-RC-DEREGISTERED state 1205. The GA-RC sub-layer for UE can also transition to the GA-RC-DEREGISTERED state 1205 if the corresponding GA-RC sub-layer for the FAP is in GA-RC-DEREGISTERED state 1205.
- In the GA-RC-REGISTERED state 1210, the UE has been registered successfully (by the FAP) with the Serving GANC. The FAP has a shared IPSec tunnel and a new TCP connection established to the Serving GANC through which the FAP may exchange GA-RC, GA-CSR and GA-PSR signaling messages (for each registered UE) with the GANC. For each of the UE device types, the FAP will perform an application level keep-alive with the GANC on the corresponding TCP session.
- In the GA-RC-REGISTERED state, the UE is camped on the Femtocell and may either be idle or the UE may be active in the Femtocell (e.g., a RRC connection may have been established). In some embodiments, an idle UE is a UE that is not currently engaged in a voice or data communication.
- B. GA-CSR (Generic Access Circuit Switched Resources)
- The GA-CSR protocol provides a circuit switched services resource management layer which supports the following functions: (1) setup of transport channels for CS traffic between the FAP and GANC, (2) direct transfer of NAS messages between the UE (or the FAP if the FAP supports local services) and the core network, and (3) other functions such as CS paging and security configuration.
- 1. States of the GA-CSR Sub-Layer
FIG. 13illustrates the state diagram in some embodiments for GA-CSR in the FAP for each UE. As shown, the GA-CSR sub-layer in the FAP (for each UE) can be in two states: GA-CSR-IDLE 1305 or GA-CSR-CONNECTED 1310.
- The GA-CSR state for each UE enters the GA-CSR-IDLE state 1305-CSR moves from the GA-CSR-IDLE state 1305 to the GA-CSR-CONNECTED state 1310 when the GA-CSR connection is established and returns to GA-CSR-IDLE state 1305 when the GA-CSR connection is released. Upon GA-CSR connection release, an indication that no dedicated CS resources exist is passed to the upper layers.
- A GA-CSR connection for each UE is typically established by the FAP when upper layers messages (NAS layer) for the specific UE need to be exchanged with the network. The GA-CSR connection release can be triggered by the GANC or the FAP. If a FAP supports local services (Terminal Adaptor functionality) using the FAP SIM, there would be similar GA-CSR state for the FAP.
- C. GA-PSR (Generic Access Packet Switched Resources)
- The GA-PSR protocol provides a packet switched services resource management layer which supports the following functions: (1) setup of transport channels for PS traffic between the FAP (for each UE) and network, (2) direct transfer of NAS messages between the UE and the PS core network, (3) transfer of GPRS user plane data, and (4) other functions such as PS paging and security configuration.
- 1. States of the GA-PSR Sub-Layer
FIG. 14illustrates the state diagram in some embodiments for GA-PSR in the FAP for each UE. As shown, the GA-PSR sub-layer for each UE can be in two states: GA-PSR-IDLE 1405 or GA-PSR-CONNECTED 1410.
- The GA-PSR state for each UE enters the GA-PSR-IDLE state 1405-PSR moves from the GA-PSR-IDLE state to the GA-PSR-CONNECTED state 1410 when the GA-PSR connection is established and returns to GA-PSR-IDLE state 1405 when the GA-PSR connection is released. Upon GA-PSR connection release, an indication that no dedicated PS resources exist is passed to the upper layers. A GA-PSR connection for each UE is typically established by the FAP when upper layers messages (NAS layer) for the specific UE need to be exchanged with the network. The GA-PSR connection release can be triggered by the GANC or the FAP.
- The GA-PSR Transport Channel (GA-PSR TC) provides the association between the FAP (for each UE) and GANC for the transport of PS user data over the Up interface. It is further described in “GA-PSR Transport Channel Management Procedures” Section, below. If a FAP supports local services (Terminal Adaptor functionality) using the FAP SIM, there would be similar GA-PSR state and GA-PSR TC for the FAP.
- D. GA-CSR and GA-PSR Connection Handling
- The GA-CSR and GA-PSR connections are logical connections between the FAP and the GANC for the CS and PS domain respectively. The GA-CSR (or the GA-PSR) connection is established when the upper layers in the FAP request the establishment of a CS (or PS) domain signaling connection and the corresponding GA-CSR (or GA-PSR) is in GA-CSR-IDLE (or GA-PSR-IDLE) state, i.e. no GA-CSR (or GA-PSR) connection exists between the FAP and GANC for the specific UE. In some embodiments, the upper layer in the FAP requests the establishment of GA-CSR (or the GA-PSR) connection, when the FAP receives a corresponding higher layer (i.e. NAS layer) message over the air interface (i.e. over the RRC connection) for the specific UE. In some embodiments, between the UE and the FAP, a single RRC connection is utilized for both CS and PS domain.
- When a successful response is received from the network, GA-CSR (or GA-PSR) replies to the upper layer that the CS (or PS) domain signaling has been established and enters the corresponding connected mode (i.e., the GA-CSR-CONNECTED or GA-PSR-CONNECTED state). The upper layers have then the possibility to request transmission of a NAS messages for CS (or PS) services to the network over the corresponding GA-CSR (or GA-PSR) connection.
- 1. FAP Initiated GA-CSR Connection Establishment
FIG. 15illustrates successful establishment of the GA-CSR connection when initiated by the FAP 1505 in some embodiments. As shown, the FAP 1505 initiates GA-CSR connection establishment by sending (in Step 1) the GA-CSR REQUEST message to the INC 1510. This message includes the Establishment Cause indicating the reason for GA-CSR connection establishment.
- INC 1510 signals the successful response to the FAP 1505 by sending (in Step 2) the GA-CSR REQUEST ACCEPT and the FAP 1505 enters the GA-CSR-CONNECTED state. Alternatively, the INC 1510 may return (in Step 3) a GA-CSR REQUEST REJECT indicating the reject cause. As shown, MSC 1515 plays no role in the FAP initiated GA-CSR connection establishment.
- 2. GA-CSR Connection Release
FIG. 16shows release of the logical GA-CSR connection between the FAP 1605 and the INC 1610 in some embodiments. As shown, the MSC 1615 indicates (in Step 1) to the INC 1610 to release the CS resources (both control and user plane resources) allocated to the FAP 1605, via the Iu Release Command message. The INC 1610 confirms (in Step 2) resource release to MSC 1615 using the Iu Release Complete message.
- The INC 1610 commands (in Step 3) the FAP 1605 to release resources for the specific UE connection, using the GA-CSR RELEASE message. The FAP 1605 confirms (in Step 4) resource release to the INC 1610 using the GA-CSR RELEASE COMPLETE message and the GA-CSR state in the FAP 1605 changes to GA-CSR-IDLE.
- 3. FAP Initiated GA-PSR Connection Establishment
FIG. 17shows successful establishment of the GA-PSR Connection when initiated by the FAP 1705 in some embodiments. As shown, the FAP 1705 initiates GA-PSR connection establishment by sending (in Step 1) the GA-PSR REQUEST message to the INC 1710. This message includes the Establishment Cause indicating the reason for GA-PSR connection establishment.
- The INC 1710 signals the successful response to the FAP 1705 by sending the GA-PSR REQUEST ACCEPT and the FAP 1705 enters the GA-PSR-CONNECTED state. Alternatively, the INC 1710 may return (in Step 3) a GA-PSR REQUEST REJECT indicating the reject cause. As shown, SGSN 1715 plays no role in the FAP initiated GA-CSR connection establishment.
- 4. GA-PSR Connection Release
FIG. 18illustrates release of the logical GA-PSR connection between the FAP 1805 and the GANC in some embodiments. As shown, the SGSN 1815 indicates (in Step 1) to the INC 1810 to release the PS resources (both control and user plane resources) allocated to the FAP, via the Iu Release Command message.
- The INC 1810 confirms (in Step 2) resource release to SGSN 1815 by using the Iu Release Complete message. The INC 1810 commands (in Step 3) the FAP 1805 to release resources for the specific UE connection, using the GA-PSR RELEASE message. The FAP 1805 confirms (in Step 4) resource release to the GANC using the GA-PSR RELEASE COMPLETE message and the GA-PSR state in the FAP 1805 changes to GA-PSR-IDLE.
- A. UE Addressing
- The IMSI associated with the SIM or USIM in the UE is provided by the FAP to the INC when it registers a specific UE attempting to camp on the FAP. The INC maintains a record for each registered UE. For example, IMSI is used by the INC to find the appropriate UE record when the INC receives a RANAP PAGING message.
- B. Femtocell Addressing
- The IMSI associated with the SIM or USIM in the FAP is provided by the FAP to the INC when it registers. The INC maintains a record for each registered FAP.
- The Public IP address of the FAP is the address used by the FAP when it establishes an IPSec tunnel to the GANC Security Gateway. This identifier is provided by the GANC Security Gateway to the AAA server. In some embodiments, this identifier is used by the GANC network systems to support location services (including E911) and fraud detection. In some embodiments, this identifier is used by service providers to support QoS for IP flows in managed IP networks.
- The Private IP address of the FAP (also referred to as the “remote IP address”) is used by the FAP “inside the IPSec tunnel.” This identifier is provided by the INC to the AAA server via the S1 interface when the FAP registers for Femtocell service. This identifier may be used by the Femtocell network systems in the future to support location services (including E911) and fraud detection.
- In some embodiments, the Access Point ID (AP-ID) is the MAC address of the Femtocell access point through which the UE is accessing Femtocell services. This identifier is provided by the FAP to the INC via the Up interface, and by the INC to the AAA server via the S1 interface, when the FAP registers for Femtocell service. The AP-ID may be used by the Femtocell network systems to support location services (including E911, as described in “Location Based Routing” Section, below), and may also be used by the service provider to restrict Femtocell service access via only authorized FAPs (as described in “Femtocell Service Access Control” Section, below).
- C. Femtocell Identification
- The following points describe the Femtocell Identification strategy.
- 1. Location Area, Routing Area, Service Area Identification
- In order to facilitate the Mobility Management functions in UMTS, the coverage area is split into logical registration areas called Location Areas (for CS domain) and Routing Areas (for PS domain). UEs are required to register with the network each time the serving location area (or routing area) changes. One or more location areas identifiers (LAIs) may be associated with each MSC/VLR in a carrier's network. Likewise, one or more routing area identifiers (RAIs) may be controlled by a single SGSN.
- The LA and the RA are used in particular when the UE is in idle mode and the UE does not have any active RRC connection. The CN would utilize the last known LA (for CS domain) and RA (for PS domain) for paging of the mobile when active radio connection is not available.
- The Service Area Identifier (SAI) identifies an area consisting of one or more cells belonging to the same Location Area. The SAI is a subset of location area and can be used for indicating the location of a UE to the CN. SAI can also be used for emergency call routing and billing purposes.
- The Service Area Code (SAC) which in some embodiments is 16 bits, together with the PLMN-Id and the Location Area Code (LAC) constitute the Service Area Identifier.
- SAI=PLMN-Id∥LAC∥SAC
- In some embodiments, it is necessary to assign a distinct LAI to each FAP in order to detect UE's mobility from the macro network to a FAP or from one FAP to another FAP. When a UE moves from the macro network to a FAP, the UE can camp on a FAP via its internal cell selection logic. However, if the UE is in idle mode, there will be no messages exchanged between the UE and the FAP, thus making it difficult for the FAP to detect the presence of the UE. In order to trigger an initial message from UE, upon its camping on a specific FAP, the FAP will need to be assigned distinct location areas than the neighboring macro cells. This will result in the UE's MM layer triggering a Location Update message to the CN via the camped cell i.e. FAP.
- UE's mobility from one FAP to another FAP must also be detected. The UE's cell selection could select a neighboring FAP and it will camp on the neighboring FAP without any explicit messaging. The neighboring FAP's Service Access Control (SAC) may not allow the camping of that specific UE, but without an initial explicit messaging there wouldn't be a way for the neighboring FAP to detect and subsequently to reject the UE.
- Assuming the MCC and MNC components of the LAI remain fixed for each operator, LAI distinctiveness would be ensured by allocating a distinct LAC to each FAP, such that the LAC assigned to the FAP is different from the neighboring macro network cells and other neighboring FAPs.
- However, the LAC space is limited to maximum of 64K (due to the limitation of a 16 bit LAC attribute as specified in “Numbering, addressing and identification”), 3GPP TS 23.003, hereinafter “TS 23.003”. As a result, the LAC allocation scheme must provide a mechanism to re-use the LACs for a scalable solution, and at the same time minimize the operational impact on existing CN elements (MSC/SGSN).
- In some embodiments, the following solution is utilized to meet the above requirements. The LAC allocation is split into two separate categories: (1) A pool of LACs managed by the FAP/AMS, and (2) A small set of LACs (one per “Iu” interface) managed by the INC.
- The first set of LACs is used by the FAP/AMS to assign a unique LAC to each FAP such that it meets the following requirements (at the minimum): (1) Uniqueness with regards to the neighboring macro cells as well as other FAPs (this will ensure an initial message from the UE upon Femtocell selection and rove-in), and (2) Resolve conflicts with shared LACs where multiple FAPs sharing the same LAC are not neighbors but are accessed by the same UE (this is to allow the use of “LA not allowed” rejection code for UE rejection).
- The second set of LACs (a much smaller set) is managed within each INC as follows, with the following key requirements: (1) Minimize the impact on the existing CN elements (such as minimal configuration and operational impact), (2) Seamlessly integrate the existing functionality for routing of emergency calls to appropriate PSAPs, and (3) Seamlessly integrate existing functionality for the generation of appropriate call detail records (CDRs) for billing purposes.
- To meet the above requirements for the second set of LACs, each INC represents a “SuperLA” for a given Iu interface (i.e. MSC+SGSN interface). This implies the MSC/SGSN can be configured with single Super LAI/Super RAI information for that INC. Note: this does not limit the operator from configuring multiple Super LAI/Super RAI if necessary (e.g., to further subdivide the region served by a single INC into multiple geographic areas).
- In addition, the INC shall utilize the following mapping functionality for assignment of SuperLA: (1) When macro coverage is reported by the FAP, INC shall support mapping of the reported macro coverage to a Super LAC, Super RAC and Service Area Code (SAC). The number of SACs utilized will be dependent on the granularity which the operator chooses for regional distribution (e.g. for emergency call routing, billing, etc), and (2) When no macro coverage is reported by the FAP, the INC shall have the following logic for the Super LAC/RAC/SAC assignment: (a) Query the AAA via the S1 interface for information on the “provisioned macro coverage” for the given FAP IMSI. If S1 reports macro coverage (based on information stored in the subscriber DB), INC uses S1 macro information to map Super LAC/RAC/SAC as above, and (b) If there is no information about the macro coverage from the S1 query, INC maps the FAP to default Super LAC/RAC/SAC; (this could result in the INC routing traffic to CN in sub-optimal mechanism). To prevent this sub-optimal routing of UE traffic to default MSC/SGSN, the following additional enhancement on the FAP may be utilized: (i) Upon a UE rove-in to this “no coverage” FAP, the FAP can gather information from the UE's initial location update (LU) request (since the UE will report last camped LAI), (ii) The FAP can collect information from multiple UEs and construct a “derived” macro coverage information (the number of UEs utilized to derive macro coverage could be algorithmic), (iii) Using this derived macro coverage information, the FAP shall send a GA-RC Register Update Uplink message to the INC, and (iv) The INC shall utilize the macro coverage information reported via the GA-RC Register Update Uplink message to map the FAP to an appropriate Super LAC/RAC/SAC as above.
- A distinct LAI for each FAP also implies a distinct RAI since the RAI is composed of the LAI and Routing Area Code (RAC). The LAI and RAI are sent to the FAP via the “System Information” attribute upon successful registration of FAP. The SAI, on the other hand, is relayed to the CN in the “Initial UE message” (used to transfer initial L3 message from UE to the CN).
- The FAP is expected to provide Super LAC/RAC replacement in the NAS messages from the network to the UE (e.g. LU Accept or RAU accept). The FAP must replace the “Super LAC/RAC” included in the relevant NAS messages from the network, with the appropriate locally assigned LAC/RAC information in messages sent to the UEs camped on the FAP.
- 2. 3G Cell Identification
- A 3G Cell Id identifies a cell unambiguously within a PLMN. A 3G cell identifier is composed as below.
- 3G Cell Id=RNC-Id (12 bits)+cell Id (16 bits)
- In some embodiments, the RNC-Id is 12 bits and cell Id is 16 bits, making the 3G Cell ID a 28 bits value. The 3G Cell Id in UMTS are managed within the UTRAN and are not exposed to the CN. As a result, the cell assignment logic can be localized to the UTRAN as long as it can ensure uniqueness within a given PLMN.
- The 3G Cell Id assigned to each FAP must be distinct from its neighboring Femtocell primarily to avoid advertisement of the same cell Id in system information broadcast by two adjacent FAPs, considering the fact the physical deployment of the FAPs are ad-hoc and not controlled by the operator. In some embodiments, each INC will be statically provisioned with a unique RNC-Id and the RNC-id will be conveyed to the FAP via the System Information during registration. The FAP will be responsible for the assignment of the 16 bit cell Id locally and construct the 3G cell using the combination of INC supplied RNC-Id and locally assigned cell Id.
- D. Femtocell Operating Configurations
- Two Femtocell operating configurations are possible: common core configuration and separate core configuration. In common core configuration, the Femtocell LAI and the umbrella UTRAN's (e.g., the UTRAN that servers the subscriber's neighborhood) LAI are different, and the network is engineered such that the same core network entities (i.e., MSC and SGSN) serve both the Femtocells and the umbrella UMTS cells.
- The primary advantage of this configuration is that subscriber movement between the Femtocell coverage area and the UMTS coverage area does not result in inter-system (i.e., MAP) signaling (e.g., location updates and handovers are intra-MSC). The primary disadvantage of this configuration is that it requires coordinated Femtocell and UMTS traffic engineering; e.g., for the purpose of MSC & SGSN capacity planning.
- In separate core configuration, the Femtocell LAI and umbrella UTRAN's LAI are different, and the network is engineered such that different core network entities serve the Femtocells and the umbrella UMTS cells.
- The advantage of this configuration is that engineering of the Femtocell and UMTS networks can be more independent than in the Common Core Configuration. The disadvantage of this configuration is that subscriber movement between the Femtocell coverage area and the UMTS coverage area results in inter-system (i.e., MAP) signaling.
- E. Femtocell Registration
- The Femtocell registration process does not involve any signaling to the PLMN infrastructure and is wholly included within the Femtocell system (i.e., between the FAP, INC, and the AAA). There are two kinds of Femtocell registrations: FAP registration and UE registration.
- In FAP registration, upon power-up, the FAP registers with the INC. FAP registration serves the following purposes: (1) It informs the INC that a FAP is now connected and is available at a particular IP address. In some embodiments, the FAP creates a TCP connection to the INC before registration. The TCP connection is identified by using one or more of the following information: source IP address, destination IP address, source TCP port, destination TCP port. The INC can extract the FAP IP address from the TCP connection, (2) It provides the FAP with the operating parameters (such as LAI, Cell-Id, etc) associated with the Femtocell service at the current location. The “System Information” content that is applicable to the GAN Femtocell service is delivered to the FAP during the registration process as part of GA-RC REGISTRATION ACCEPT message sent from the INC to the FAP. The FAP utilizes the information to transmit system parameters to the UE over the broadcast control channel and (3) It allows the Femtocell system to provide the service access control (SAC) and accounting functions (e.g., AP restriction and redirection). In some embodiments, the SAC and accounting is done through the S1 interface.
- In UE registration, upon Femtocell selection and cell camping, the UE initiates a LU message towards the CN via the FAP. The FAP utilizes this message to detect presence of the UE on that specific FAP. The FAP then initiates a registration message towards INC for the camped UE. UE registration by the FAP serves the following purpose: (1) It informs the INC that a UE is now connected through a particular FAP and is available at a particular IP address. The INC keeps track of this information for the purposes of (for example) mobile-terminated calling, and (2) It allows the INC to provide SAC functionality (e.g. using the S1 interface, to validate if the specific UE should be allowed Femtocell services from a specific FAP).
- F. Mobility Management Scenarios
- The following scenarios illustrate the message flows involved for various mobility management scenarios via the Femtocell system.
- 1. FAP Power On
- In some embodiments, the FAP is initially provisioned with information (i.e. an IP address or a FQDN) about the Provisioning INC and the corresponding Provisioning SeGW related to that INC. This information can be in the format of either a FQDN or an IP-address or any combination of these. In case the FAP is not provisioned with information about the Provisioning SeGW, the FAP can derive a FQDN of the Provisioning SeGW from the IMSI (as described in TS 23.003). If the FAP does not have any information about either the Default INC or the Serving INC and the associated SeGW stored, then the FAP completes the Discovery procedure towards the Provisioning INC via the associated SeGW. If the FAP has stored information about the Default/Serving INC on which it registered successfully the last time, the FAP skips the discovery procedure and attempt registration with the Default/Serving INC as described below.
- a) FAP Discovery Procedure
FIG. 19illustrates the case in some embodiments when the FAP 1905 powers on and does not have stored information on the Default/Serving INC, and then performs a discovery procedure with the provisioning GANC 1910. The provisioning GANC 1910 includes a provisioning INC 1915, a DNS 1920, and a SeGW 1925.
- As shown, if the FAP 1905 has a provisioned or derived (as described in the FAP power on sub-section, above) FQDN of the Provisioning SeGW, the FAP 1905 performs (in Step 1) a DNS query (via the generic IP access network interface) to resolve the FQDN to an IP address. If the FAP 1905 has a provisioned IP address for the Provisioning SeGW 1925, the DNS steps (Steps 1 and 2) are omitted. In some embodiments, the DNS Server 1935 is a public DNS server accessible from the FAP. The DNS Server 1935 returns (in Step 2) a response including the IP Address of the Provisioning SeGW 1925.
- Next, the FAP 1905 establishes (in Step 3) a secure tunnel (e.g., an IPSec tunnel) to the Provisioning SeGW 1925. If the FAP 1905 has a provisioned or derived FQDN of the Provisioning INC 1915, the FAP 1905 performs (in Step 4) a DNS query (via the secure tunnel) to resolve the FQDN to an IP address. If the FAP has a provisioned IP address for the Provisioning INC 1915, the DNS steps (Steps 4 and 5) are omitted. The DNS Server 1920 of the provisioning GANC 1910 returns (in Step 5) a response including the IP Address of the Provisioning INC 1915.
- Next, the FAP 1905 sets up a TCP connection to a well-defined port on the Provisioning INC. It then queries (in Step 6) the Provisioning INC 1915 for the Default INC, using GA-RC DISCOVERY REQUEST. The message includes: (1) Cell Info: If the FAP detects macro network coverage then the FAP provides the detected UTRAN cell ID and the UTRAN LAI (for GSM, the FAP provides the GSM cell identification and the GSM LAI). If the FAP does not detect macro network coverage, the FAP provides the last LAI where the FAP successfully registered, along with an indicator that identifies the last GERAN/UTRAN cell (e.g., by including a GERAN/UTRAN coverage Indicator Information Element (IE) which identifies the GERAN or UTRAN cell coverage). The cell Info is the information of neighboring macro cells which can be either GSM or UTRAN cells. There are multiple ways for the FAP to obtain the neighboring cell information, e.g. using pre-configuration on the FAP, obtaining the macro neighbor configuration via AMS, or having the FAP radio scan the neighboring cells. If the macro coverage is GSM, then for the scan approach, the FAP must have the capability and mechanism for scanning GSM cells, (2) FAP Identity: IMSI, and (3) The physical MAC address of the FAP: AP-ID. Optionally, if the INC 1915 has been configured for Service Access Control (SAC) over S1 interface, the INC 1915 will via AAA server 1930 authorize the FAP 1905 using the information provided in the GA-RC DISCOVERY REQUEST (Steps 6 a-6 c).
- The Provisioning INC 1915 returns (in Step 7) the GA-RC DISCOVERY ACCEPT message, using the information provided by the FAP (e.g. the cell ID), to provide the FQDN or IP address of the Default INC and its associated Default SeGW. This is done so the FAP 1905 is directed to a “local” Default INC in the HPLMN to optimize network performance. The DISCOVERY ACCEPT message also indicates whether the INC and SeGW address provided shall or shall not be stored by the FAP 1905.
- If the Provisioning INC 1915 cannot accept the GA-RC DISCOVERY REQUEST message, it returns (in Step 8) a GA-RC DISCOVERY REJECT message indicating the reject cause. The secure IPSec tunnel to the Provisioning SeGW is released (Step 9).
- It is also be possible to reuse the same IPSec tunnel for FAP Registration procedures. This is the case where a discovery procedure results in the FAP to successfully find a “default” INC and a “default” SeGW. If the default SeGW is same as that used for discovery (i.e. the provisioning SeGW), then the same IPSEC tunnel can be reused. In this case the IPSec tunnel is not released.
- b) FAP Registration Procedure
- Following the Discovery procedure the FAP establishes a secure tunnel with the Security Gateway of the Default GANC, provided by the Provisioning GANC in the Discovery procedure, and attempts to register with the Default GANC.
FIG. 20illustrates FAP power on registration procedure of some embodiments. The Default GANC may become the Serving GANC for that connection by accepting the registration, or the Default GANC may redirect the FAP to a different Serving GANC. GANC redirection may be based on information provided by the FAP during the Registration procedure, operator chosen policy or network load balancing.
- As shown in
FIG. 20, if the FAP 2005 was only provided the FQDN of the Default or Serving SeGW 2015, the FAP 2005 performs (in Step 1) a DNS query (via the generic IP access network interface) to resolve the FQDN to an IP address. If the FAP 2005 has a provisioned IP address for the SeGW, the DNS steps (Steps 1 and 2) are omitted. The DNS Server 2010 returns (in Step 2) a response including the IP address of the Default/Serving SeGW 2015.
- Next, the FAP 2005 sets up (in Step 3) a secure IPSec tunnel to the SeGW 2015. This step may be omitted if an IPSec tunnel is being reused from an earlier Discovery or Registration. If the FAP 2005 was provided the FQDN of the Default or Serving INC, the FAP then perform (in Step 4) a DNS query (via the secure tunnel) to resolve the FQDN to an IP address. If the FAP 2005 has an IP address for the INC, the DNS steps (Steps 4 and 5) are omitted. The DNS Server 2020 returns (in Step 5) a response including the IP address of the Default/Serving INC 2025.
- The FAP then sets up a TCP connection to the INC 2025. The TCP port can either be a well-known or one that has been earlier received from the network during Discovery or Registration. The FAP attempts to register (in Step 6) on the INC 2025 by transmitting the GA-RC REGISTER REQUEST. In some embodiment, the message includes one or more of the following information: Registration Type, Cell Info, Neighboring FAP Info, the physical MAC address of the FAP, FAP Identity, and location information.
- The Registration Type indicates that the registering device is a Femtocell AP. This is indicated using the “GAN Classmark” IE (IEs are defined further below). The Cell Info is the neighboring UTRAN/GERAN cell ID retrieved as a result of system scan for neighbor information. The FAP must determine (using either scan results or pre-configuration), a single suitable macro cell information to be sent in the registration.
- Neighboring FAP Info is information about neighboring FAPs operating in the same PLMN and carrier frequency. This will help provide the INC with information such as the LAI and cell-ids in use by neighboring FAPs. In some embodiments, the neighboring FAP information will not be provided. The physical MAC address of the FAP is the AP-ID (in some embodiments, AP-ID is the MAC address of the FAP associated Ethernet port). The FAP Identity is the IMSI of the FAP. If GPS services are provided, location information is also supported.
- Optionally, if the INC 2025 has been configured for Service Access Control (SAC) over S1 interface, the GANC will via AAA server 2030 authorize the FAP using the information provided in the REGISTER REQUEST (Steps 6 a-6 c). If the INC 2025 accepts the registration attempt it responds (in Step 7) with a GA-RC REGISTER ACCEPT. The message includes: (1) GAN Femtocell specific system information (e.g.) (i) Location-area identification comprising the mobile country code, mobile network code, and location area code corresponding to the Femtocell, and (ii) 3G Cell identity identifying the cell within the location area corresponding to the Femtocell. The message also includes GAN Femtocell Capability Information indicated via the use of “GAN Control Channel” IE. In some embodiments, the GAN Femtocell Capability Information include indications as to whether early Classmark sending is allowed, the GAN mode of operation, whether GPRS is available, and whether the GAN supports dual transfer mode.
- In the case the INC 2025 accepts the registration attempt, the TCP connection and the secure IPSec tunnel are not released and are maintained as long as the FAP is registered to this GANC. INC does not provide operation parameters for radio management (such as carrier frequency, scrambling code, etc) to the FAP. It is expected that the FAP would obtain this information via the AMS or other pre-provisioning mechanisms.
- Alternatively, the INC 2025 may reject the request. In this case, it responds (in Step 8) with a GA-RC REGISTER REJECT indicating the reject cause. The TCP connection and the secure IPSec tunnel are released and the FAP 2005 shall act as defined in the “abnormal cases” Section, below. Alternatively, if the GANC has to redirect the FAP 2005 to (another) Serving GANC, it responds (in Step 9) with a GA-RC REGISTER REDIRECT providing the FQDN or IP address of the target Serving INC and the associated SeGW. In this case the TCP connection is released (in Step 10) and the secure IPSec tunnel is optionally released depending on if the network indicates that the same IPSec tunnel can be reused for the next registration. The GA-RC REGISTER REDIRECT message includes either a single Serving SeGW and GANC address or a list of PLMN identities and associated Serving SeGW and GANC addresses and an indication of whether GANC address(es) can be stored in the FAP for future use.
- c) Abnormal Cases
- If the Serving INC rejects the Register Request and does not provide redirection to another Serving INC, the FAP shall re-attempt Registration to the Default INC including a cause indicating the failed registration attempt and the Serving INC and SeGW with which the Register Request failed. The FAP should also delete all stored information about this Serving GANC.
- If the Default INC rejects a Registration Request and is unable to provide redirection to suitable Serving INC, the FAP may re-attempt the Discovery procedure to the Provisioning INC (including a cause indicating the failed registration attempt and the Default INC provided in the last Discovery procedure). The FAP should also delete all stored information about the Default GANC. The possible register reject causes for FAP registration attempts are Network Congestion, Location Not Allowed, Geo-Location not know, IMSI not allowed, AP not allowed, and Unspecified.
- 2. FAP Initiated FAP Synchronization after TCP Connection Reestablishment
- In some embodiments, when FAP receives TCP Reset (TCP RST) after TCP connection failure, the FAP tries to re-establish the signaling connection using GA-RC Synchronization procedure.
FIG. 21illustrates the messages associated with the FAP initiated synchronization procedure in some embodiments.
- a) Initiation of the FAP Synchronization Procedure by the FAP
- In some embodiments, when FAP receives TCP RESET after TCP connection failure, the FAP attempts to re-establish TCP connection once. After successfully re-establishing TCP connection, the FAP 2105 sends (in Step 1) GA-RC SYNCHRONIZATION INFORMATION to the GANC 2110 to synchronize the state information. When the FAP is unsuccessful in re-establishing the TCP connection, the FAP releases the related local GA-CSR or GA-PSR resources, and continues as per sub-section “Handling of Lower Layer faults” described further below.
- b) Processing of the FAP Synchronization Information Message by the GANC
- Upon receiving the GA-RC SYNCHRONIZATION INFORMATION message from the FAP, the GANC updates the FAP state information as specified in the request. The GANC also verifies that the binding (IMSI, inner IP address) as received in the GA-RC SYNCHRONIZATION INFORMATION is the same as the one that the FAP used as identity for authentication to the GANC-SeGW.
- 3. System Selection
- In some embodiments, in the combined 3G network, both standard UMTS RNS and UMA Femtocell network coexists within the same or different PLMN. Standard UMTS UEs utilize both access options whichever is more optimal in a specific scenario. In these embodiment, no changes are required to the PLMN selection procedures in the NAS layers (MM and above) in the UE as described in “Non-Access-Stratum functions related to Mobile Station (MS) in idle mode”, 3GPP TS 23.122. Also, in these embodiments, no changes are required to the standard cell selection mechanism as described in “User Equipment (UE) procedures in idle mode and procedures for cell reselection in connected mode”, 3GPP TS 25.304. The necessary configuration and the system behavior for rove-in to Femtocell coverage and rove-out to the macro network coverage are described in the following paragraphs.
- During the service activation or provisioning update, the UMA Femtocell Network provides the FAP with radio parameters such as the operating UARFCN and a list of primary scrambling codes for the Femtocell. The provisioning parameters will also include the list of UARFCNs/scrambling codes associated with the neighboring macro cells.
- The FAP then performs a neighborhood scan for the existence of macro coverage using the macro UARFCN information. If multiple macro network cells are detected in the FAP scan, the FAP selects the best suitable macro cell for the purpose of reporting it to the Serving INC during FAP registration. The FAP also stores the macro cell list to be provided as a neighbor list for the camping UEs.
- The FAP also scans the neighborhood for the existence of other FAPs within the same PLMN. It then selects unused {UARFCN, SC} pair from the provisioned list of available pairs such that the selected {UARFCN, SC} does not conflict with any neighboring FAP's {UARFCN, SC} combination.
- The FAP attempts to register with the Serving INC (obtained via Discovery/Registration mechanisms as described in the FAP discovery procedure and FAP registration procedure Sections above) and includes information about the selected macro cell and a list of neighboring FAPs. The Serving INC uses information provided during registration to assign network operating parameters for the registering FAP such as the LAI, 3G cell-id, service area, etc.
- The Serving INC returns the network operating parameters to the registering FAP using the register accept message. The FAP uses a combination of information obtained through the initial provisioning and Registration and broadcasts appropriate System Information to UEs to be able to select Femtocell service and camp on the FAP.
- The macro network RNCs are provisioned with the list of {UARFCN, SC} associated with Femtocell neighbors. Since the Femtocell network has to be able to scale to millions of FAPs and the deployment location cannot be controlled, the macro network RNCs are provisioned with a list of 5-10 {UARFCN, SC} combinations corresponding to the neighboring FAPs. As a result of the limitations associated with neighbor list provisioning on the macro RNC, the FAP will need to select one of the 5-10 provisioned {UARFC, SC} pairs for its operation such that no two neighboring FAPs (determined via FAPs' scan) shall re-use the same pair for its operation.
- The macro RNC shall provide the FAP neighbor list information to the UEs camped on the macro network and using the specific RNC. This will result in the UEs making periodic measurements on the FAP neighbor list.
- As the UE comes within the coverage area of the FAP and its signal level becomes stronger, the UE will select the Femtocell. The UE cell-reselection i.e. rove-in to FAP cell can be enhanced via two possible mechanisms: (1) The FAP cell can be in a different HPLMN (equivalent PLMN list) and will be selected via preferred equivalent PLMN selection. This assumes that the UE's current camped macro cell is not in the equivalent PLMN list, and (2) The FAP will broadcast system information (such as Qqualmin and Qrxlevmin) so that UE shall prefer the FAP cell in the presence of other macro cell coverage.
- Upon cell reselection and camping on the FAP cell, the UE will initiate a location registration since the FAP LAI is different than the LAI of the previously camped macro cell.
- 4. UE Registration
- The UE, illustrated in
FIG. 22. A person of ordinary skill in the art would appreciate that a UE always initiates location update procedure towards the core network, i.e., the UE uses the upper protocol layers that are directly exchanged with the core network. As described in this sub-section and several other sub-sections below, the disclosed FAP has the capability to intercept this message and to attempt to register the UE with the INC.
- As shown, the UE 2205 establishes (in Step 1 a) a radio resource control (RRC) connection with the FAP 2210 on which it camps. The UE 2205 starts (in Step 1 b) a Location Update procedure towards the CN. In some embodiments, for networks supporting network mode 1, where there is a Gs interface between the MSC and SGSG, the UE triggers a combined Routing Area (RA)/Location Area (LA) update instead of the initial LA update upon rove-in to FAP. The FAP 2210 will intercept the Location Update request (or the combined RA/LA update request) and attempts to register the UE with the associated Serving INC over the existing IPSec tunnel. Optionally, the FAP may request (in Step 1 c) the IMSI of the UE if the Location Update is done (in Step 1 d) using the TMSI, since the initial registration for the UE must be done using the permanent identity i.e. the IMSI of the UE.
- Next, the FAP 2210 sets up (in Step 2) a separate TCP connection (for each UE) to a destination TCP port on the INC 2215. The INC destination TCP port is the same as that used for FAP registration. The FAP 2210 attempts to register the UE 2205 on the INC 2215 using the UE specific TCP connection by transmitting (in Step 3) the GA-RC REGISTER REQUEST. The message includes Registration Type (which indicates that the registering device is a UE. This is indicated using the “GAN Classmark” IE), Generic IP access network attachment point information (i.e., AP-ID), UE Identity (i.e., UE-IMSI), and FAP identity (i.e., FAP-IMSI). In some embodiments, the AP-ID is the MAC address of the FAP.
- Optionally, if the INC 2215 has been configured for Service Access Control (SAC) over S1 interface, the INC 2215 will, via AAA server 2220, authorize the UE using the information provided in the REGISTER REQUEST (Steps 3 a-3 c). The authorization logic on the AAA server 2220 would also check to see if the UE 2205 is allowed Femtocell access using the specific FAP.
- If the INC 2215 accepts the registration attempt it responds (in Step 4) with a GA-RC REGISTER ACCEPT. Next, the FAP 2210 establishes (in Step 5) a GA-CSR connection with the INC 2215. The FAP 2210 encapsulates (in Step 6) the Location Update NAS PDU within a GA-CSR UL DIRECT TRANSFER message that is forwarded to the INC 2215 via the existing TCP connection.
- Next, the INC 2215 establishes a SCCP connection to the CN 2225 and forwards (in Step 7) the Location Update request (or the combined RA/LA update request) NAS PDU to the CN 2225 using the RANAP Initial UE Message. Subsequent NAS messages between the UE 2205 and core network 2225 will be sent between INC 2215 and CN 2225 using the RANAP Direct Transfer message.
- Next, the CN 2225 authenticates (in Step 8) the UE 2205 using standard UTRAN authentication procedures. The CN 2225 also initiates the Security Mode Control procedure described in the Security Mode Control Subsection under Femtocell Security Section further below. The CN 2225 indicates (in Step 9) it has received the location update and it will accept the location update using the Location Update Accept message to the INC 2215.
- The INC 2215 forwards (in Step 10) this message to the FAP 2210 in the GA-CSR DL DIRECT TRANSFER. The FAP 2210 will relay (in Step 11) the Location Update Accept over the air interface to the UE 2205. Once the UE 2205 has been successfully registered (by the FAP) with the INC 2215 and performed a successful location update, the FAP 2210 will expect a periodic LU for that UE (the enabling and the periodicity of the LU is controlled by the FAP via System Information broadcast from the FAP to the UE). This exchange will serve as a keep-alive between the FAP 2210 and the UE 2205 and will help the FAP 2210 detect idle UE's moving away from the camped FAP 2210 without explicit disconnect from the network.
- a) Abnormal Cases
- If the Serving INC rejects the UE specific Register Request, the FAP shall reject the corresponding “Location update” request from the UE using appropriate reject mechanisms (example: RRC redirection to another cell or reject the LU with reject cause of “Location Area not allowed”, etc). The FAP shall tear down the corresponding TCP session for the specific UE. The possible register reject causes for UE specific registration attempts are (1) AP not allowed (implies UE not allowed on FAP for the UE specific registration), (2) IMSI not allowed, (3) Location not allowed, (4) Unspecified, and (5) FAP not registered.
- 5. UE Rove Out
FIG. 23scenario illustrates the case when the UE leaves the Femtocell coverage area while idle. As shown, upon successful GAN registration and location update (LU) of the UE 2305, the FAP 2310 will monitor (in Step 1) the UE 2305 via periodic location updates. The enabling and the periodicity of the LU is controlled by the FAP 2310 via System Information broadcast from the FAP to the UE. This exchange will serve as a keep-alive between the FAP and the UE.
- Next, FAP 2310 determines (in Step 2) that the UE 2305 is no longer camped on the FAP (roved out), as a result of missing a number of periodic location updates from the UE. Once, the FAP determines that the UE has roved out, the FAP informs the GANC that the UE has detached by sending (in Step 3) a GA-RC DEREGISTER message to the INC 2315 using the associated TCP connection. Since a TCP connection from the FAP to the GANC is unique for each UE, sending GA-RC DEREGISTER message on the specific TCP connection implies deregistration of the specific UE. Next, the GANC removes (in Step 4) any associated UE context upon receiving the deregister message on the UE specific TCP connection. In some embodiments, the context associated with a UE includes states and other information that the GANC keeps for each UE which is successfully registered. The FAP 2310 also releases (in Step 4) the UE specific TCP connection to the INC.
- 6. UE Power Down with IMSI Detach
FIG. 24illustrates the case when the UE powers down and performs an IMSI detach via the GAN network in some embodiments. As shown, UE 2405 in idle mode initiates (in Step 1) power off sequence. Next, the UE 2405 establishes (in Step 2) an RRC Connection with the FAP 2410. The UE send (in Step 3) a MM Layer IMSI-Detach message over the air interface to the FAP. The FAP 2410 establishes (in Step 4) a GA-CSR connection with the INC 2415.
- The FAP 2410 encapsulates the IMSI-Detach NAS PDU within a GA-CSR UL DIRECT TRANSFER message that is forwarded (in Step 5) to the INC 2415 via the existing TCP connection. The INC 2415 establishes a SCCP connection to the CN 2420 and forwards (in Step 6) the IMSI-Detach NAS PDU to the CN 2420 using the RANAP Initial UE Message. The CN 2420 initiates (in Step 7) a normal resource cleanup via RANAP Iu Release Command to the INC 2415. The Iu Release from the CN 2420 results in INC 2415 tearing down (in Step 8) the corresponding GA-CSR connection.
- Next, INC 2415 acknowledges (in Step 9) resource cleanup via RANAP Iu Release Complete message to the CN. FAP 2410 deregisters (in Step 10) the UE using the UE specific TCP connection. In some embodiments, the FAP utilizes the mechanism described in Subsection “UE rove out” above to detect that the UE has roved and trigger the UE deregistration. As an optimization, the FAP can also monitors the IMSI-Detach NAS message from the UE and trigger deregistration of the UE.
- Next, the FAP 2410 releases (in Step 11) the UE specific TCP connection. FAP initiates (in Step 12) RRC Connection release procedure towards the UE. Finally, the UE powers off (in Step 13).
- 7. UE Power Down without IMSI Detach
- The sequence of events is same as UE Roving out of Femtocell as described in Subsection “UE rove out” above.
- 8. Loss of Up Interface Connectivity
FIG. 25illustrates the case when Up interface connectivity is lost. As shown, the UE 2505 is in idle mode. The FAP 2510 periodically sends (in Step 1) GA-RC KEEP ALIVE message to the INC 2515 to check that the TCP connection exists. In Step 2, the TCP (or IP) connectivity between the FAP 2510 and INC 2515 is lost (e.g., due to a broadband network problem).
- If the INC detects (in Step 3) the loss of connectivity, it releases the resources assigned to the FAP (e.g., TCP connection) and deletes the subscriber record (i.e., performs a local deregistration of the FAP). Optionally, the INC implementation may also delete UE specific connections originating on that FAP.
- If the FAP 2510 detects (in Step 4) the loss of TCP connectivity and if the loss is on the FAP specific TCP connection, the FAP 2510 attempts (in Step 5) to re-establish the TCP connection and re-register with the INC. If the FAP re-establishes connectivity and re-registers before the INC detects the problem, the INC must recognize that the FAP is already registered and adjust accordingly (e.g., release the old TCP connection resources). In some embodiment, the FAP specific TCP is a unique TCP connection dedicated to the FAP and is used for FAP IMSI related signaling to the INC such as FAP registration, FAP call setup if the FAP offers local calling using the FAP IMSI, etc.
- Different embodiments use different methods for the FAP to detect the loss of a TCP connection. In some embodiments, the TCP sub-layer (TCP stack) in the FAP indicates (to the upper layers) if the connectivity to the other end point (i.e., the INC) is lost. The notification from the TCP sub-layer on the FAP can happen either when the upper layers attempt to transmit data over the TCP connection or the stack can detect connectivity loss via a TCP Keep Alive mechanism.
- When the FAP is unsuccessful in re-establishing connectivity, the FAP will do the followings (not shown) to deregister all the UEs currently camped on the FAP: (1) The FAP sends a GA-RC DEREGISTER message to the INC using the currently established TCP connection for each UE, (2) releases the TCP connection towards the GANC, and (3) releases all resources associated with the deregistered UE.
- Additionally, the FAP 2510 forces (in Step 6) all the UEs, currently camped on that FAP, to do a cell-reselection and rove out of Femtocell coverage. If the TCP connectivity loss is detected on the UE specific connection, the FAP will deregister the UE and trigger cell reselection on the UE immediately without attempting to re-establish the UE specific TCP connection. Finally, the UE 2505, as a result of the cell re-selection, will switch (in Step 7) to UMTS macro cell 2520 (if UMTS macro network coverage is available).
- 9. INC-Initiated Deregister
- In some embodiments, the INC deregisters the FAP under the following error cases: (1) INC receives GA-RC REGISTER UPDATE UPLINK message, but FAP is not registered, (2) INC receives GA-RC REGISTER UPDATEUPLINK message, but encounters a resource error and cannot process the message, (3) INC receives GA-RC REGISTER UPDATE UPLINK message with new macro network cell information, and the macro cell is Femtocell-restricted, and (4) INC receives a GA-RC REGISTER UPDATE UPLINK message and sends a request to the AAA server for a registered FAP, and one of the following happens: (a) INC receives an authentication failure for the user from AAA server, (b) INC doesn't receive a response from AAA server, and transaction timer expires, or (c) S1 interface is enabled but no AAA server is configured, so the user couldn't be authenticated. In some embodiments, the INC deregisters the UE when the INC receives GA-RC SYNCHRONIZATION INFORMATION message for a UE that is not registered.
- 10. FAP-Initiated Register Update
FIG. 26illustrates a scenario where the FAP initiates a registration update in some embodiments. As shown, a register update is triggered (in Step 1) in the FAP 2605 (e.g., Detection of macro network coverage). The FAP sends (in Step 2) a GA-RC REGISTER-UPDATE-UPLINK to the INC 2610.
- The INC 2610 exchanges (in Steps 3 a-3 c) S1 RADIUS messages with the AAA server 2615 for service access control (SAC). Based on the outcome of SAC, additional procedures may be triggered (in Step 4) by this operation (e.g., deregistration or register update downlink).
- 11. INC-Initiated Register Update
FIG. 27illustrates a scenario where the INC initiates a registration update. As shown, a register update is triggered (in Step 1) in the INC 2715 (e.g. due to change in SAC list for the FAP, or change in System Information, etc).
- Next, the INC 2715 sends (in Step 2) a GA-RC REGISTER UPDATE DOWNLINK message to the FAP 2710. As shown, some other procedures may be triggered (in Step 3) by this operation (e.g. FAP 2710 rejecting UEs 2705 due to updated SAC list received from the INC).
- 12. FAP Initiated UE Synchronization after TCP Connection Reestablishment
- In some embodiments, when FAP receives TCP RST after TCP connection failure, the FAP tries to re-establish the signaling connection using GA-RC Synchronization procedure.
FIG. 28illustrates the FAP initiated synchronization procedure in some embodiments.
- a) Initiation of the UE Synchronization Procedure by the FAP
- In some embodiments, when FAP receives TCP RST after TCP connection failure, the FAP attempts to re-establish TCP connection once. As shown in
FIG. 28, after successfully re-establishing TCP connection, the FAP 2805 sends (in Step 1) GA-RC SYNCHRONIZATION INFORMATION to the GANC 2810 to synchronize the UE's state information. When unsuccessful, the FAP releases the resources for the UE and forces the UE to rove-out of the FAP and select an alternate cell (either a macro cell or another FAP) for camping
- b) Processing of the UE Synchronization Information Message by the GANC
- Upon receiving the GA-RC SYNCHRONIZATION INFORMATION message from the FAP on a UE's TCP connection, the GANC updates the UE state information as specified in the request. The GANC also verifies that the associated FAP is in the registered state. When the FAP is not in registered state, the GANC deregisters the UE by sending a GA-RC-DEREGISTER message (not shown) with reject cause code “FAP not registered” to the FAP on the UE's TCP connection. When the GA-RC layer in the GANC has submitted the GA-RC DEREGISTER message to the TCP layer, it initiates the release of its half of the bidirectional TCP connection. The GANC also verifies that the binding (IMSI, TCP connection) as received in the GA-RC SYNCHRONIZATION INFORMATION is valid.
- A. Voice Bearer Establishment (Using Iu-UP Over AAL2)
FIG. 29illustrates the normal procedures associated with successfully establishing the voice bearer between the UE and MSC for mobile originated (MO) or mobile terminated (MT) call purposes in some embodiments. As shown, the signaling for a call origination or termination is in progress (in Step 1) between UE 2905, FAP 2910, GANC MGW 2915, INC 2920, and MSC 2925. The MSC 2925 sends (in Step 2) a RANAP Assignment Request (RAB) message to the INC 2920. The assignment request includes the address for ALCAP signaling (an ATM E.164 or NSAP address) and also the binding-id.
- Next, the INC 2920 requests (in Step 3) the GANC MGW 2915 to prepare a bearer connection between the endpoints (VoIP towards the FAP and Iu-UP over AAL2 towards the MSC). The MGW 2915 initiates (in Step 4) ALCAP signaling towards the MSC 2925 using the ATM address and the binding-id.
- Next, the MSC 2925 acknowledges (in Step 5) the AAL2 connection request using the ALCAP Establish confirm message. At this point (Step 6) an AAL2 connection with appropriate QoS exists between the GANC MGW and the MSC. The GANC MGW then sends (in Step 7) an Iu-UP control (Iu-INIT) message over this AAL2 connection to request Iu-UP initialization
- The MSC 2925 responds (in Step 8) with Iu-UP init acknowledgement (Iu-INIT ACK). Next, the MGW 2915 assigns a MGW IP address and port for the VoIP side of the connection. The MGW sends (in Step 9) the VoIP information to the INC using a Prepare Bearer Ack message. Next, the INC 2920 sends (in Step 10) a GA-CSR ACTIVATE CHANNEL message to the FAP 2910 and starts a timer (e.g., Tqueuing, as described in “UTRAN Iu interface Radio Access Network Application Part (RANAP) signaling”, 3GPP TS 25.413) to ensure that the RANAP Assignment Response is sent to the MSC on or before the expiry of Tqueuing. The GA-CSR ACTIVATE CHANNEL message includes the VoIP connection description created by the GANC MGW.
- The FAP 2910 initiates (in Step 11) appropriate RRC layer Radio Bearer Setup message towards the UE 2905. The UE confirms (in Step 12) the setup via Radio Bearer Setup Complete message to the FAP. The FAP sends (in Step 13) a GA-CSR ACTIVATE-CHANNEL-ACKNOWLEDGE message to the INC, including the local IP address and port to be used for the VoIP connection.
- The INC requests (in Step 14 a) the GANC MGW, to modify the previously created connection and send the voice stream to the IP address and port provided by the FAP. The GANC MGW acknowledges (in Step 14 b) the connection modification. The INC 2920 acknowledges (in Step 15) completion of the traffic channel establishment to the FAP 2910 via the GA-CSR ACTIVATE-CHANNEL COMPLETE message.
- The INC 2920 signals (in Step 16) the MSC 2925 about the RAB assignment completion. At this point (Steps 17 a-17 c), there is voice bearer between the UE 2905 and MSC 2925 via the FAP 2910 and the GANC MGW 2915. The rest of the call establishment continues after the voice bearer establishment.
- B. Call Management Scenarios
- The following scenarios illustrate the message flows involved for various call management scenarios via the Femtocell.
- 1. Mobile Originated Call
FIG. 30illustrates a mobile originated call in some embodiments. The scenario shown is for a mobile-to-PSTN call. As shown, the UE 3005 in GAN idle mode originates (in Step 1) a call. The UE 3005 establishes (in Step 2) a RRC connection with the FAP 3010. Upon request from the upper layers, the UE sends (in Step 3) the CM Service Request to the FAP.
- The FAP performs (in Step 4) the GA-CSR Connection Establishment procedure with the INC as described in previous sections. The FAP 3010 then forwards (in Step 5) the CM Service Request to the INC 3015 using a GA-CSR UL DIRECT TRANSFER message. Next, the INC 3015 establishes a SCCP connection to the MSC 3020 and forwards (in Step 6) the CM Service Request to the MSC using the RANAP Initial UE Message. Subsequent NAS messages between the UE and MSC will be sent between INC and MSC using the RANAP Direct Transfer message.
- Next, the MSC 3020 authenticates (in Step 7) the UE 3005 using standard UTRAN authentication procedures. The MSC also initiates (in Step 7) the Security Mode Control procedure described in previous sections. The UE sends (in Step 8) the Setup message to the FAP providing details on the call to the MSC and its bearer capability and supported codecs.
- The FAP forwards (in Step 9) this message within the GA-CSR UL DIRECT TRANSFER between the FAP and the INC. The INC relays (in Step 10) the Setup message to the MSC using a RANAP Direct Transfer message.
- The MSC 3020 indicates (in Step 11) it has received the call setup and it will accept no additional call-establishment information using the Call Proceeding message to the INC. The INC forwards (in Step 12) this message to the FAP in the GA-CSR DL DIRECT TRANSFER. The FAP then relays (in Step 13) the Call Proceeding message to the UE over the air interface. At this point (Step 14) an end to end bearer path is established between the MSC and UE using one of the procedures shown in previous section.
- The MSC 3020 constructs (in Step 15) an ISUP IAM using the subscriber address, and sends it towards the called party's destination exchange 3025. The destination Exchange responds (in Step 16) with an ISUP ACM message. The MSC then signals to the UE, with the Alerting message, that the called party is ringing. The message is transferred (in Step 17) to the INC.
- The INC forwards (in Step 18) the Alerting message to the FAP in the GA-CSR DL DIRECT TRANSFER. The FAP relays (in Step 19) the Alerting message to the UE and if the UE has not connected the audio path to the user, it shall generate ring back to the calling party. Otherwise, the network-generated ring back will be returned to the calling party.
- The called party answers and the destination Exchange indicates this (in Step 20) with an ISUP ANM message. The MSC signals that the called party has answered, via the Connect message. The message is transferred (in Step 21) to the INC. The INC forwards (in Step 22) the Connect message to the FAP in the GA-CSR DL DIRECT TRANSFER.
- The FAP relays (in Step 23) the Connect message to the UE and the UE connects the user to the audio path. If the UE is generating ring back, it stops and connects the user to the audio path. The UE sends (in Step 24) the Connect Ack in response, and the two parties are connected for the voice call. The FAP relays (in Step 25) this message within the GA-CSR UL DIRECT TRANSFER between the FAP and the INC.
- The INC forwards (in Step 26) the Connect Ack message to the MSC. The end-to-end two way path is now (Step 27) in place and bi-directional voice traffic flows between the UE and MSC through the FAP and the INC. A FAP with local service can support MO using the FAP IMSI. The necessary message flows would be similar as above without the FAP-UE message exchanges over the air interface.
- 2. Mobile Terminated Call
FIG. 31illustrates a mobile terminated call. The scenario shown is for a PSTN-to-mobile call. As shown, the MSC (i.e., the GMSC function) receives (in Step 1) a call from party A intended for the Femtocell subscriber 3105. The MSC 3120 sends (in Step 2) a RANAP Paging message to the INC 3115 identified through the last Location Update received by it and includes the TMSI if available. The IMSI of the mobile being paged is always included in the request.
- The INC 3115 identifies the UE registration context using the IMSI provided by the MSC. It then pages (in Step 3) the associated FAP 3110 using the GA-CSR PAGING REQUEST message. The message includes the TMSI, if available in the request from the MSC, else it includes only the IMSI of the mobile.
- The FAP 3110 relays (in Step 4) the Paging request to the UE. The FAP may use Paging Type 1 or 2 based on the RRC state of the UE as described in “Radio Resource Control (RRC) protocol specification”, 3GPP TS 25.331, hereinafter “TS 25.331”. The UE 3105 establishes (in Step 4 a) a RRC connection with the FAP 3110 if one doesn't exist. This step is omitted if there is an already existing RRC connection (e.g. an RRC connection may have been established for PS domain).
- Next, the UE 3105 processes the paging request and sends (in Step 5) the Paging response to the FAP 3110. The FAP then performs (in Step 5 a) the GA-CSR Connection Establishment procedure with the INC as described in previous sections. The FAP responds (in Step 6) with a GA-CSR PAGING RESPONSE.
- The INC 3115 establishes an SCCP connection to the MSC 3120. The INC 3115 then forwards (in Step 7) the paging response to the MSC using the RANAP Initial UE Message. Subsequent NAS messages between the UE and core network will be sent using the RANAP Direct Transfer message. The MSC then authenticates (in Step 8) the UE using standard UTRAN authentication procedures. The MSC also initiates (in Step 8) the Security Mode Control procedure described in previous sections.
- The MSC initiates (in Step 9) call setup using the Setup message sent to the FAP via INC. The INC then forwards (in Step 10) this message to the FAP in the GA-CSR DL DIRECT TRANSFER message. The FAP relays (Step 11) the Setup message to the UE
- The UE 3105 responds (in Step 12) with Call Confirmed after checking it's compatibility with the bearer service requested in the Setup and modifying the bearer service as needed. If the Setup included the signal information element, the UE alerts the user using the indicated signal, else the UE alerts the user after the successful configuration of the user plane
- The FAP relays (in Step 13) the Call Confirmed to the INC using the GA-CSR UL DIRECT TRANSFER message. The INC then forwards (in Step 14) the Call Confirmed message to the MSC using RANAP direct transfer message. At this point (Step 15) an end to end bearer path is established between the MSC 3120 and UE 3105 using the procedure for voice bearer establishment as described in previous sections.
- The UE signals (in Step 16) that it is alerting the user, via the Alerting message to the FAP. The FAP relays (in Step 17) the Alerting message to the INC using the GA-CSR UL DIRECT TRANSFER. The INC (in Step 18) forwards the Alerting message to the MSC.
- The MSC 3120 returns (in Step 19) a ISUP ACM message towards the originating PSTN Exchange 3125. The UE signals (in Step 20) that the called party has answered, via the Connect message. The FAP relays (in Step 21) the Connect message to the INC in the GA-CSR UL DIRECT TRANSFER message.
- Next, the INC forwards (in Step 22) the Connect message to the MSC. The MSC then returns (in Step 23) an ISUP ANM message towards the originating PSTN exchange 3125. The MSC acknowledges (in Step 24) via the Connect Ack message to the INC. The INC forwards (in Step 25) this message to the FAP in the GA-CSR DL DIRECT TRANSFER.
- The FAP relays (in Step 26) the Connect Ack to the UE. The two parties on the call are connected on the audio path. The end-to-end two way path is now (Step 27) in place and bi-directional voice traffic flows between the UE and MSC through the FAP and the INC. A FAP with local service can support MT using the FAP IMSI. The necessary message flows would be similar as above without the FAP-UE message exchanges over the air interface.
- 3. Call Release by Femtocell Subscriber
FIG. 32illustrates a scenario where a Femtocell call is released by the Femtocell subscriber in some embodiments. As shown, the Femtocell subscriber 3205 requests (in Step 1) call release (e.g., by pressing the END button). Upon request from the upper layers, the UE sends (in Step 2) the Disconnect message to the FAP 3210. The FAP forwards (in Step 3) the Disconnect message to the INC (embedded in a GA-CSR UL DIRECT TRANSFER message).
- The INC 3220 relays (in Step 4) the Disconnect message to the MSC 3225 via RANAP Direct Transfer message. The MSC 3225 sends (in Step 5) an ISUP RELEASE message towards the other party 3230. The MSC sends (in Step 6) a Release to the INC using RANAP Direct Transfer message.
- Next, the INC forwards (in Step 7) the Release message to FAP using GA-CSR DL DIRECT TRANSFER message. The FAP then sends (in Step 8) the Release message to the UE over the air interface. The UE 3205 confirms (in Step 9) the Release via the Release Complete message to the FAP. The FAP relays (in Step 10) the Release Complete message to the INC using GA-CSR UL DIRECT TRANSFER message
- The INC forwards (in Step 11) the message to the MSC using RANAP Direct Transfer message. At this point, the MSC considers the connection released. Sometime after Step 5, the MSC receives (in Step 12) an ISUP RLC message from the other party's exchange.
- The MSC 3225 sends (in Step 13) an Iu Release command to the INC 3220 indicating a request to release the call resources. The SCCP Connection Identifier is used to determine the corresponding call. The INC 3220 requests (in Step 14) the GANC MGW 3215 to release associated resources with the call. The GANC MGW 3215 confirms (in Step 15) release of associated resources.
- The INC initiates (in Step 16) a GA-CSR Connection Release procedure towards the FAP (as described in previous sections). The FAP in turn releases (in Step 17) any radio resource associated for the specific call. If there is an active PS session for the UE, the RRC connection may not be released by the FAP, and only the corresponding CS radio bearers are released. Finally, the INC acknowledges (in Step 18) the resource release to the MSC using the Iu Release Complete message to the MSC. The SCCP connection associated with the call between the INC and the MSC is released as well
- 4. Other Calling Scenarios
- The following services are supported by the Femtocell solution:
- Calling Line Identification Presentation (CLIP)
- Calling Line Identification Restriction (CLIR)
- Connected Line Identification Presentation (CoLP)
- Connected Line Identification Restriction (CoLR)
- Call Forwarding Unconditional
- Call Forwarding Busy
- Call Forwarding No Reply
- Call Forwarding Not Reachable
- Call Waiting (CW)
- Call Hold (CH)
- Multi Party (MPTY)
- Closed User Group (CUG)
- Advice of Charge (AoC)
- User User Signaling (UUS)
- Call Barring (CB)
- Explicit Call Transfer (ECT)
- Name Identification
- Completion of Calls to Busy Subscriber (CCBS)
- These supplementary services involve procedures that operate end-to-end between the UE and the MSC. Beyond the basic Direct Transfer Application Part (DTAP) messages already described for MO and MT calls, the following DTAP messages are used for these additional supplementary service purposes:
- HOLD
- HOLD-ACKNOWLEDGE
- HOLD-REJECT
- RETRIEVE
- RETRIEVE-ACKNOWLEDGE
- RETRIEVE-REJECT
- FACILITY
- USER-INFORMATION
- CONGESTION-CONTROL
- CM-SERVICE-PROMPT
- START-CC
- CC-ESTABLISHMENT
- CC-ESTABLISHMENT-CONFIRMED
- RECALL
- These DTAP message are relayed between the UE and MSC by the INC in the same manner as in the other call control and mobility management scenarios described in this disclosure. A generic example is illustrated in
FIG. 33. As shown (in Step 1), there is an existing MM connection established between the UE and the MSC for an ongoing call. The user requests (in Step 2) a particular supplementary service operation (e.g., to put the call on hold).
- The UE 3305 sends (in Step 3 a) the HOLD message to the FAP 3310 over the air. The FAP in turn forwards (in Step 3 b) the message to INC 3315), embedded in a GA-CSR UPLINK DIRECT TRANSFER message. The INC relays (in Step 3 c) the DTAP HOLD message to the MSC 3320 over the Iu-interface.
- Next, the DTAP HOLD-ACK message is sent (in Steps 4 a-4 c) from MSC 3320 to UE 3305 through the INC and FAP. Later in the call, the user requests (in Step 5) another supplementary service operation (e.g., to initiate a MultiParty call).
- The UE sends (in Step 6 a) the FACILITY message to the FAP over the air. The FAP in turn forwards (in Step 6 b) the message to the INC. The INC relays (in Step 6 c) the DTAP FACILITY message to the MSC over the Iu-interface. Finally, the DTAP FACILITY message including the response is sent (in Steps 7 a-7 c) from MSC to UE through the INC and FAP.
- A. GA-PSR Transport Channel Management Procedures
- The GA-PSR Transport Channel (GA-PSR TC) provides an association between the FAP and INC for the transport of the user data over the Up interface. Given that the Femtocell user data transport is UDP based, the GA-PSR Transport Channel is associated with corresponding FAP and INC IP addresses and UDP ports used for user data transfer. The FAP and INC manage the GA-PSR Transport Channel based on the requests for data transfer and the configurable GA-PSR TC Timer.
- 1. States of the GA-PSR Sub-Layer
- The GA-PSR Transport Channel (GA-PSR TC) management procedures are the basic procedures for PS services specified to facilitate the control of the GA-PSR connection for user data transfer. Given that the GTP-U user data transport is extended to the FAP in GAN solution for Femtocell support, these procedures are tightly integrated with RAB Assignment procedures for user data. GTP-U based connection between the FAP and the SGSN for user data transfer is referred to as the GA-PSR Transport Channel.
- The GA-PSR Transport Channel consists of the following: (1) The IP address and destination UDP port number to be used for user data transfer at both the SGSN and FAP, and (2) The GA-PSR TC Timer. The FAP or INC will activate a GA-PSR Transport Channel only when needed; i.e., when the user data transfer is initiated.
- The GA-PSR maintains a separate PS entity for each PDP context that is established. Each individual GA-PSR PS entity can be in two different states, GA-PSR-PS-STANDBY or GA-PSR-PS-ACTIVE state. The state of the GA-PSR PS entity and the corresponding transport channel are always synchronized.
- In GA-PSR-PS-STANDBY state the FAP is not able to send or receive user data associated with the specific PDP context to and from the SGSN. The INC or the FAP needs to activate the GA-PSR Transport Channel before sending any user data for that PDP context. In this state a corresponding GA-PSR Transport Channel does not exist. When the GA-PSR Transport Channel is activated, the GA-PSR entity associated with that PDP context enters the GA-PSR-PS-ACTIVE state.
- In GA-PSR-PS-ACTIVE state the FAP and UE are able to send and receive user data associated with the specific PDP context to and from the SGSN. Furthermore there exists a corresponding GA-PSR Transport Channel for this FAP/UE.
- A GA-PSR TC Timer is also defined to control the transition from GA-PSR-PS-ACTIVE to GA-PSR-PS-STANDBY state as follows. The FAP GA-PSR layer implements a timer associated with each GA-PSR Transport Channel. The timer is started when that entity enters GA-PSR-PS-ACTIVE state and restarted each time a data packet for that PDP context is transmitted to or received from the network. When the timer expires, the FAP deactivates the GA-PSR Transport Channel and the corresponding PDP service entity enters GA-PSR-PS-STANDBY state.
- The GA-PSR TC Timer value is provided to the FAP as part of the Femtocell Registration procedure (i.e., in GA-RC REGISTER ACCEPT message).
- 2. FAP Initiated GA-PSR Transport Channel Activation
FIG. 34depicts the FAP initiated GA-PSR Transport Channel activation procedure of some embodiments. Initially, the corresponding GA-PSR PS PDP entity is in GA-PSR-PS-IDLE state when the uplink data transfer for that PDP context is requested. The FAP has to establish the GA-PSR Transport channel prior to resuming the uplink data transfer.
- As shown, if the RRC connection does not exist, the UE 3405 initiates (in Step 1) RRC Connection establishment procedure as per standard 3GPP procedure. Upon successful RRC Connection establishment, the UE 3405 forwards (in Step 2) a Service Request message to the SGSN via the FAP 3410 indicating data transfer. The FAP performs (in Step 2 a) the GA-PSR Connection Establishment procedure with the INC as described in “FAP initiated GA-PSR connection establishment” Subsection under “Resource Management” Section, above.
- The FAP 3410 then encapsulates the request within the GA-PSR-UPLINK-DIRECT-TRANSFER message and forwards (in Step 3) the request to the INC 3415. The INC forwards (in Step 4) the Service Request to the CN (SGSN) 3420 encapsulated within the Initial Iu Message or within the Direct Transfer message depending on PMM state. Optionally, the CN (SGSN) may initiate (in Step 5) security function as specified in “Security Mode Control” Subsection and “Core network authentication” Subsections under “Femtocell Security” Section, further below. Optionally, upon receiving the request and if the UE was in PMM-CONNECTED state, the CN (SGSN) responds (in Step 6) with a Service Accept message.
- Optionally, if the Service Accept message was received, the INC 3415 forwards (in Step 7) the message to the FAP 3410. The FAP then forwards (in Step 8) the message to the UE 3405. The CN (SGSN) 3420 initiates (in Step 9) RAB Assignment procedure and includes the RAB-ID, the CN Transport Layer Address (IP address) and the CN Iu Transport Association (GTP-U Terminal Endpoint Identifier (TEID)) for user data to be used with this GA-PSR Transport Channel.
- Next, the INC forwards (in Step 10) the GA-PSR ACTIVATE TC REQ to the FAP to activate the Transport Channel for user data transfer. The message includes the RAB-ID, and the INC IP Address and INC TEID. To allow the FAP to send GA-PSR TC packets (i.e., GTP-U messages) directly to the SGSN, the INC sets the INC IP Address to the CN IP Address and the INC TEID to the CN TEID. In an alternate embodiment, it is possible for the GANC to assume the role of a GTP-U proxy gateway, where two separate GTP-U tunnels exist for a given GA-PSR TC i.e. first GTP-U between FAP and GANC and the corresponding GTP-U between the GANC and the SGSN. The GANC is responsible for relaying the actual PS data packets between the two GTP-U tunnels. Next, corresponding Radio Bearers are established (in Step 11) between the FAP 3410 and UE 3405.
- The FAP then responds (in Step 12) to the INC with acknowledgment. The message includes the RAB-ID and a GTP-U TEID assigned by the FAP for the specific PS session. Upon receiving the acknowledgment, the INC sends (in Step 13) the RAB Assignment Rsp message to the CN (SGSN) to complete the RAB Assignment procedure. To allow the SGSN to send GTP-U messages directly to the FAP, the INC sets the RAN IP Address to the FAP's IP Address and the RAN TEID to the TEID allocated by the FAP for the UE specific PS session.
- The INC notifies (in Step 14) the FAP that the procedure is complete and the FAP modifies the state of the corresponding GA-PSR PS PDP entity to GA-PSR-PS ACTIVE and starts GA-PSR PS TC Timer. The UE initiates (in Step 15) uplink user data transfer via the established transport channel and the SGSN may use the same transport channel to send downlink user data packets. While the transport channel is active, both FAP and SGSN can continue sending user data associated with the same PDP context directly using this transport channel.
- 3. FAP Initiated Deactivation of the GA-PSR Transport Channel
FIG. 35illustrates the scenario in some embodiments when the FAP deactivates the GA-PSR Transport Channel after the GA-PSR TC Timer expires. As shown, GA-PSR TC Timer associated with one of the active GA-PSR Transport Channels expires (in Step 1). The FAP 3510 sends (in Step 2) GA-PSR DEACTIVATE TC REQ message to the INC 3515 including the RAB-ID to identify the GA-PSR Transport Channel and indicating the normal release as a cause for deactivation.
- The INC 3515 forwards (in Step 3) RAB Release Req message to the CN (SGSN) 3520 to request the release of the associated RAB. The CN (SGSN) responds (in Step 4) with the RAB Assignment Request indicating release for the requested RAB.
- Next, the INC 3515 responds (in Step 5) to the FAP with a GA-PSR DEACTIVATE TC ACK message to acknowledge successful deactivation. Upon receiving acknowledgment message, the FAP initiates (in Step 6) release of the associated Radio Bearers. Finally, the INC sends (in Step 7) RAB Assignment Rsp message to notify the SGSN that the RAB Release procedure is complete.
- 4. Network Initiated Transport Channel Activation for PS Service
FIG. 36depicts a scenario when the CN (SGSN) initiates activation of a PS Transport Channel for user data service. This scenario covers the case when the SGSN receives a downlink user data packet from the GGSN and the RAB for that PDP context is not established. Initially, the CN (SGSN) received downlink user data to transfer to the UE and the associated RAB is not established. The UE is in PMM-IDLE state. The UE 3605 is in PMM-IDLE state and the CN (SGSN) 3610 sends (in Step 1) the RANAP Paging request to the UE 3605 via the INC 3615 to locate the user. The paging request indicates paging for PS Domain. The INC 3615 forwards (in Step 2) the GA-PSR PAGING message to the FAP 3610.
- Next, the FAP forwards (in Step 3) the PS Page to the UE 3605 as per standard 3GPP procedure. The FAP may use Paging Type 1 or 2 based on the RRC state of the UE as described in TS 25.331. Next, an RRC connection is established (in Step 4) between the UE 3605 and FAP 3610. This step is omitted if there is an already existing RRC connection (e.g. a RRC connection may have been established for CS domain)
- Next, the UE responds (in Step 5) to the SGSN via the FAP with a Service request indicating PS paging response. The message is encapsulated within the RRC INITIAL DIRECT TRANSFER message. The FAP performs (in Step 5 a) the GA-PSR Connection Establishment procedure with the INC as described in Subsection “FAP initiated GA-PSR connection establishment” under “RESOURCE MANAGEMENT” Section, above. The FAP forwards (in Step 6) the PS paging response to the INC using GA-PSR PAGING RESPONSE message.
- The INC forwards (in Step 7) the Service Request message to the SGSN encapsulated in the RANAP Initial UE Message. Security function is performed (in Step 8) as specified in “Security mode control” Subsection and “Core network authentication” under “FEMTOCELL SECURITY” Section, below. Steps 9 to 15 are same as described in the “FAP initiated GA-PSR transport channel activation” Subsection, above.
- 5. Network Initiated Transport Channel Deactivation
FIG. 37depicts a network initiated GA-PSR Transport Channel deactivation procedure that includes Radio Access Barer release in some embodiments. Initially, active GA-PSR Transport Channel associated with the UE 3705 that is registered for Femtocell service is active.
- As shown, optionally, the INC 3715 may initiate (in Step 1) RAB Release procedure as a result of error handling procedure. This would trigger CN (SGSN) 3720 to release the corresponding RAB. The CN (SGSN) 3720 sends (in Step 2) a RAB Assignment Request to request the release of the associated RAB. The release request may include one or more RABs.
- The INC 3715 requests (in Step 3) deactivation of the associated GA-PSR Transport Channel. As a result, the corresponding Radio Bearers are (in Step 4) released. The FAP 3710 then updates (in Step 5) the state of the corresponding GA-PSR PS PDP entity to STANDBY, stops GA-PSR TC Timer and sends the acknowledgment back to the INC. Steps 3, 4 and 5 are repeated for each additional RAB that needs to be released. Finally, the INC 3715 notifies (in Step 6) the CN (SGSN) 3720 that the release was successful.
- B. User Data and Signaling Transport
- 1. User Data Transport Procedures
FIG. 38illustrates the transport of user data packets via Femtocell in some embodiments. As shown, if the corresponding GA-PSR Transport Channel is not active, the GA-PSR TC activation procedure is initiated (in Step 1) as specified in the “FAP initiated GA-PSR transport channel activation” Subsection, above. Upon the GA-PSR Transport Channel establishment, the FAP 3810 starts (in Step 2) GA-PSR TC Timer.
- The UE 3805 initiates (in Step 3) the transfer of an uplink user data packet using PDCP Data service. The FAP 3810 forwards (in Step 4) the packet using the standard GTP-U protocol as specified in “GPRS Tunnelling Protocol (GTP) across the Gn and Gp interface”, 3GPP TS 29.060, and restarts (in Step 5) GA-PSR TC Timer.
- The CN (SGSN) 3820 transfers (in Step 6) downlink user data packet utilizing the same GA-PSR Transport Channel associated with the specific PDP context. Downlink user data packets are transferred using the standard GTP-U protocol as specified in 3GPP TS 29.060. Upon receiving the downlink data packet, the FAP restarts (in Step 7) GA-PSR TC Timer associated with the corresponding GA-PSR Transport Channel and forwards (in Step 8) the packet to the UE via the PDCP.
- Additional uplink and downlink user data packets are transferred (in Step 9) via the same GA-PSR Transport Channel as described in steps 2 and 3 respectively. After the GA-PSR TC Timer expires (Step 10), the FAP initiates (in Step 11) GA-PSR Transport Channel deactivation procedure as described in the “FAP initiated deactivation of the GA-PSR transport channel” Subsection, above. A FAP with local service can support PS user plane activity using the FAP IMSI. The necessary message flows would be similar as above without the FAP-UE message exchanges over the air interface.
- 2. GA-PSR Signaling Procedures
- A single TCP connection per UE is established for the transport of signaling messages within the Femtocell. This TCP connection is used to transport all CS and PS related signaling and SMS messages.
- a) UE Initiated PS Signaling Procedure
- For UE initiated PS related signaling, the UE sends a PS signaling message to the CN, via the INC which forwards it to the CN over the Iu-ps interface as per standard UMTS; e.g. the signaling message may include GMM attach or SM PDP context activation message. The INC encapsulates the received signaling message within a RANAP Direct Transfer message that is forwarded to the SGSN over the Iu-ps interface.
FIG. 39illustrates Uplink Control Plane Data Transport of some embodiments.
- Initially, the UE 3905 is ready to send an uplink signaling message for PS services to the CN (SGSN) 3920. This could be any of the GMM or SM signaling messages. As shown, if the RRC connection does not exist, the UE 3905 initiates (in Step 1) RRC Connection establishment procedure as per standard 3GPP procedure.
- Upon successful RRC Connection establishment, the UE forwards (in Step 2) a Service Request message to the SGSN via the FAP 3910 indicating PS Signaling message. The FAP performs (in Step 2 a) the GA-PSR Connection Establishment procedure with the INC as described in the “FAP initiated GA-PSR connection establishment” Subsection under the “RESOURCE MANAGEMENT” Section, above. The FAP encapsulates the Service Request within the GA-PSR-UPLINK-DIRECT-TRANSFER message and forwards (in Step 3) the request to the INC 3910.
- Next, the INC forwards (in Step 4) the Service Request to the SGSN encapsulated within the Initial Iu Message or within the Direct Transfer message depending on PMM state. Optionally, the CN (SGSN) may initiate (in Step 5) security function as specified in Sections “Security Mode Control” and “Core Network Authentication”, below. The UE 3805 sends (in Step 6) the PS signaling message to the FAP 3910 using RRC Uplink Direct Transfer service.
- The FAP 3910 forwards (in Step 7) the PS signaling message to the INC encapsulated within the GA-PSR-UPLINK-DIRECT-TRANSFER message. Finally, the INC 3915 forwards (in Step 8) the PS signaling message to the CN (SGSN) 3920 using RANAP Direct Transfer procedure.
- b) Network Initiated PS Signaling Procedure
- For Network initiated PS related signaling, the Core Network sends a PS signaling message to the INC via the IuPS interface as per standard UMTS; e.g. the signaling message may include GMM attach accept or SM PDP context activation accept message. The INC encapsulates the received signaling message within a GA-PSR-DOWNLINK-DIRECT-TRANSFER OR GA-PSR PAGING message that is forwarded to the FAP via the existing TCP signaling connection.
FIG. 40illustrates Downlink Control Plane Data Transport of some embodiments. Initially, the CN (SGSN) 4020 is ready to send a downlink signaling message for PS services to the UE 4005. This could be any of the GMM or SM signaling messages. Given that the signaling procedure is network initiated and if the UE is in PMM-IDLE state, the SGSN will first page the UE. If the UE is in PMM-CONNECTED state the SGSN will send the downlink PS signaling message using RANAP Direct Transfer procedure starting with Step 9.
- As shown, optionally, if the UE 4005 is in PMM-IDLE state, the CN (SGSN) 4020 sends (in Step 1) the RANAP Paging request to the UE via the INC 4015 to locate the user. The paging request indicates paging for PS Domain. Optionally, if the paging request was received, the INC forwards (in Step 2) the paging request using the GA-PSR PAGING message to the FAP 4010.
- Also, optionally, if the paging message is received, the FAP forwards (in Step 3) the PS page to the UE as per standard 3GPP procedure. Optionally, if the RRC connection does not exist for that UE, it is established (in Step 4) as per standard 3GPP procedure. Optionally, if the page for PS services was received, the UE responds (in Step 5) to the SGSN via the FAP with a Service Request message indicating PS paging response. The Service Request message is encapsulated within the RRC INITIAL DIRECT TRANSFER message.
- The FAP 4010 performs (in Step 5 a) the GA-PSR Connection Establishment procedure with the INC as described in the “FAP initiated GA-PSR connection establishment” Subsection under the “RESOURCE MANAGEMENT” Section, above. The FAP forwards (in Step 6) the response encapsulated within the GA-PSR PAGING RESPONSE message to the INC.
- Next, the INC 4015 forwards (in Step 7) the Service Request message to the SGSN 4020 encapsulated in the RANAP Initial UE Message. Optionally, the CN (SGSN) initiates (in Step 8) Security Function.
- The CN (SGSN) forwards (in Step 9) the PS signaling message to the INC using RANAP Direct Transfer procedure. The INC forwards (in Step 10) the PS signaling message to the FAP encapsulated within the GA-PSR-DOWNLINK-DIRECT-TRANSFER message. Finally, the FAP sends (in Step 11) the signaling message to the UE using RRC Downlink Direct Transfer service. A FAP with local service can support PS signaling plane activity using the FAP IMSI. The necessary message flows would be similar as above without the FAP-UE message exchanges over the air interface.
- In some embodiments, the checks described in this section are applied to all messages exchanged in the Femtocell system. This section also specifies procedures for the handling of unknown, unforeseen, and erroneous protocol data by the receiving entity. These procedures are called “error handling procedures”, but in addition to providing recovery mechanisms for error situations they define a compatibility mechanism for future extensions of the protocols. In some embodiments, Sub-sections A to F, below, are applied in order of precedence.
- In this section the following terminology is used (1) An information element (IE) is defined to be syntactically incorrect in a message if it includes at least one value defined as “reserved” in the corresponding message, or if its value part violates rules of any corresponding messages. However it is not a syntactical error that an IE specifies in its length indicator a greater length than defined in for the specific message, and (2) A message is defined to have semantically incorrect contents if it includes information which, possibly dependent on the state of the receiver, is in contradiction to the resources of the receiver and/or to the procedural part of this specification. The procedures described in this sub-section apply to both GA-CSR and GA-PSR messages, unless explicitly specified otherwise.
- A. Message Too Short
- When a message is received that is too short to include a complete message header and all the mandatory information elements, that message is ignored.
- B. Invalid Message Header
- When the FAP receives a message over UDP with message type not defined or not implemented, the FAP ignores the message. When the FAP receives a message over TCP with protocol discriminator not defined or not implemented, the FAP ignores the message. When the FAP receives a message with Skip Indicator IE not encoded as 0000 or Length IE greater than 2048, the FAP ignores the message.
- When the FAP receives a message over TCP with message type not defined for the specific PD (GA-CSR or GA-PSR) or not implemented, the FAP returns a GA-CSR STATUS or GA-PSR STATUS respectively, with cause “message type non-existent or not implemented”. When the FAP receives a message not compatible with the protocol state, the FAP ignores the message and shall return a (GA-CSR or GA-PSR) STATUS message with cause “Message type not compatible with protocol state”.
- C. Invalid Information Elements
- When the FAP receives a GA-RC OR GA-CSR OR GA-PSR message with a missing or syntactically incorrect mandatory IE, the FAP ignores the message and returns a (GA-RC or GA-PSR) STATUS message with cause “Invalid mandatory information”. The FAP also ignores all unknown IEs in received messages. The FAP further treats all optional IEs that are syntactically incorrect in a message as not present in the message.
- When the FAP diagnoses a missing or unexpected conditional IE or when it receives at least one syntactically incorrect conditional IE, the FAP ignores the message and returns a (GA-RC or GA-PSR) STATUS message with cause value “conditional IE error”. When the FAP receives a message with semantically incorrect contents, the FAP ignores the message and returns a (GA-RC or GA-PSR) STATUS message with cause value “semantically incorrect message”.
- D. Handling of Lower Layer Faults
- The handling of lower layer failures in the FAP while in the GA-RC-DEREGISTERED state is as follows. If a TCP connection was established towards the Provisioning GANC, the FAP releases the connection. If a secure connection was established towards SeGW of the Provisioning GANC, the FAP releases the secure connection (as defined in “Internet Key Exchange (IKEv2) Protocol”, IETF RFC 4306. additionally, when the lower layer failures happen during a Discovery procedure, the FAP doubles the current timer value for TU3903 but not exceeding the maximum value (32 minutes). The FAP also starts timer TU3903.
- When the lower layer failures happen during a Registration procedure, and if the registration is still unsuccessful after a number of attempts defined the FAP parameter “Up Connect Attempt Count” (maximum value of 3), and if the FAP had attempted the registration towards the Default GANC, then the FAP deletes the stored information about the Default GANC, increments Redirection Counter, and initiates the Discovery Procedure. When the lower layer failures happen during a Registration procedure, the registration is still unsuccessful after a number of attempts defined the FAP parameter “Up Connect Attempt Count” (maximum value of 3), and the FAP had attempted the registration towards a Serving GANC, then the FAP increments Redirection Counter and initiates Registration Procedure towards the Default GANC.
- When the lower layer failures happen during a Registration procedure and the registration is successful before a number of attempts defined the FAP parameter “Up Connect Attempt Count” (maximum value of 3), then the FAP starts timer TU3905 and waits for it to expire.
- The handling of lower layer failures in the FAP while not in the GA-RC-DEREGISTERED state is as follows. For all lower layer failures in the FAP (for example related to DNS, IPSec or TCP failures other than RST) except the TCP connection failure which is handled as described in the “FAP initiated FAP Synchronization after TCP connection reestablishment” sub-section described above, the FAP (1) releases the TCP connection towards the current GANC, if established, (2) releases the secure connection towards SeGW of the current GANC, if established, (3) starts timer TU3905 (for FAP TCP connection) or TU3955 (for UE specific TCP connection), and (4) enters GA-RC-DEREGISTERED state.
- E. Out of Sequence IEs
- The FAP ignores all out of sequence IEs in a message. In some embodiments, the GANC also takes the same approach and ignores all out of sequence IEs in a message.
- F. Unexpected Messages
- The FAP silently discards all unexpected messages (unless specific behavior is defined for certain messages) which are either inconsistent with the current state of the device or out of sequence. The network should take the same approach.
- This section provides a list of messages and Information elements (IEs) used in some embodiments. IEs are similar to “attributes” or “parameters” and are used in messages to exchange information across interfaces.
- Table IX-1 summarizes the messages for Generic Resources management.
TABLE IX-1 Messages for Unlicensed Radio Resources management Discovery messages: GA-RC DISCOVERY REQUEST GA-RC DISCOVERY ACCEPT GA-RC DISCOVERY REJECT Registration messages: GA-RC REGISTER REQUEST GA-RC REGISTER ACCEPT GA-RC REGISTER REDIRECT GA-RC REGISTER REJECT GA-RC DEREGISTER GA-RC REGISTER UPDATE UPLINK GA-RC REGISTER UPDATE DOWNLINK Miscellaneous message: GA-RC KEEP ALIVE GA-RC SYNCHRONIZATION INFORMATION
- Table IX-2 summarizes the messages for Generic Access Circuit Switched Resources (GA-CSR) management
TABLE IX-2 Messages for GA-CSR management GA-CSR connection establishment messages: GA-CSR REQUEST GA-CSR REQUEST ACCEPT GA-CSR REQUEST REJECT Traffic Channel establishment messages: GA-CSR ACTIVATE CHANNEL GA-CSR ACTIVATE CHANNEL ACK GA-CSR ACTIVATE CHANNEL FAILURE GA-CSR ACTIVATE CHANNEL COMPLETE Channel release messages: GA-CSR RELEASE GA-CSR RELEASE COMPLETE GA-CSR CLEAR REQUEST Paging messages: GA-CSR PAGING REQUEST GA-CSR PAGING RESPONSE Security Mode messages: GA-CSR SECURITY MODE COMMAND GA-CSR SECURITY MODE COMPLETE GA-CSR SECURITY MODE REJECT Miscellaneous messages: GA-CSR UPLINK DIRECT TRANSFER GA-CSR DOWNLINK DIRECT TRANSFER GA-CSR STATUS
- Table IX-3 summarizes the messages for Generic Access Packet Services Resource (GA-PSR) management.
TABLE IX-3 Messages for Generic Access Radio Link Control management Transport Layer used GA-PSR Connection Management messages: GA-PSR-REQUEST TCP GA-PSR REQUESTACCEPT TCP GA-PSR REQUEST REJECT TCP GA-PSR-RELEASE TCP GA-PSR RELEASE COMPLETE TCP GA-PSR TC Management messages: GA-PSR-ACTIVATE-TC-REQ TCP GA-PSR-ACTIVATE-TC-ACK TCP GA-PSR-ACTIVATE-TC-CMP TCP GA-PSR-DEACTIVATE-TC-REQ TCP GA-PSR-DEACTIVATE-TC-ACK TCP GPRS Tunneling messages: GA-PSR-UPLINK-DIRECT-TRANSFER TCP GA-PSR-DOWNLINK-DIRECT-TRANSFER TCP GAN Specific Signaling messages: GA-PSR-PAGING TCP GA-PSR-PAGING RESPONSE TCP GA-PSR-STATUS TCP Security messages: GA-PSR SECURITY MODE COMMAND TCP GA-PSR SECURITY MODE COMPLETE TCP GA-PSR SECURITY MODE REJECT TCP GA-PSR CLEAR REQUEST TCP TABLE 9.2.1 IE type and identifiers for Unlicensed Radio Resources management IE Identifier Mobile Identity (FAP) 1 GAN Release Indicator 2 Access Identity 3 GERAN Cell Identity 4 Location Area Identification 5 GERAN/UTRAN coverage Indicator 6 GAN Classmark 7 Geographical Location 8 GANC-SeGW IP Address 9 GANC-SeGW Fully Qualified Domain/Host Name 10 Redirection Counter 11 Discovery Reject Cause 12 GAN Cell Description 13 GAN Control Channel Description 14 Cell Identifier List 15 TU3907 Timer 16 GSM RR/UTRAN RRC State 17 Routing Area Identification 18 GAN Band 19 GA-RC/GA-CSR State 20 Register Reject Cause 21 TU3906 Timer 22 TU3910 Timer 23 TU3902 Timer 24 L3 Message 26 Channel Mode 27 Mobile Station Classmark 2 28 RR Cause 29 Cipher Mode Setting 30 GPRS Resumption 31 Handover From GAN Command 32 UL Quality Indication 33 TLLI 34 Packet Flow Identifier 35 Suspension Cause 36 TU3920 Timer 37 QoS 38 GA-PSR Cause 39 User Data Rate 40 Routing Area Code 41 AP Location 42 TU4001 Timer 43 Location Status 44 Cipher Response 45 Ciphering Command RAND 46 Ciphering Command MAC 47 Ciphering Key Sequence Number 48 SAPI ID 49 Establishment Cause 50 Channel Needed 51 PDU in Error 52 Sample Size 53 Payload Type 54 Multi-rate Configuration 55 Mobile Station Classmark 3 56 LLC-PDU 57 Location Black List indicator 58 Reset Indicator 59 TU4003 Timer 60 AP Service Name 61 GAN Service Zone Information 62 RTP Redundancy Configuration 63 UTRAN Classmark 64 Classmark Enquiry Mask 65 UTRAN Cell Identifier List 66 Serving GANC table indicator 67 Registration indicators 68 GAN PLMN List 69 Required GAN Services 71 Broadcast Container 72 3G Cell Identity 73 FAP Radio Identity 96 GANC IP Address 97 GANC Fully Qualified Domain/Host Name 98 IP address for GPRS user data transport 99 UDP Port for GPRS user data transport 100 GANC TCP port 103 RTP UDP port 104 RTCP UDP port 105 GERAN Received Signal Level List 106 UTRAN Received Signal Level List 107 Integrity Protection Information 75 Encryption Information 76 Key Status 77 Chosen Integrity Algorithm 78 Chosen Encryption Algorithm 79 Security Mode Reject Cause 80 RAB ID 81 RAB Parameters 82 GTP TEID 83 Service Handover 84 PDP Type Information 85 Data Volume Reporting Indicator 86 DL GTP-PDU Sequence Number 86 UL GTP-PDU Sequence Number 88 DL N-PDU Sequence Number 89 UL N-PDU Sequence Number 90 Alternate RAB Parameter Values 91 Assigned RAB Parameter Values 92 Data Volume List 93 DRX Cycle Length Coefficient 94 Paging Cause 95 URA Identity 110 GA-PSR State 111 Mobile Identity (UE) 112 RABS Data Volume Report List 113 Allocation/Retention Priority Information 114 NAS Synchronization Indicator 115
- The Femtocell system provides support for both circuit mode (CS mode) and packet mode (PS mode) SMS services. CS/PS mode of operation UEs may be able to send and receive short messages using either the MM sub-layer or the GMM sub-layer. PS mode of operation UEs may be able to send and receive short messages using only GMM sub-layer. Inter-working with Femtocell related to SMS services is described in the following sections.
- A. Circuit Mode (CS Mode) SMS Services
- The Femtocell protocol architecture related to CS mode SMS support builds on the circuit services signaling architecture described in the “CS domain—control plane architecture” Subsection under the “FEMTOCELL SYSTEM ARCHITECTURE” Section, above.
FIG. 41illustrates the protocol architecture for CS mode SMS in some embodiments.
- The Femtocell CS mode SMS support is based on the same mechanism that is utilized for CS mobility management and call control. On the UE 4105 side, the SMS layers 4110 (including the supporting CM sub-layer functions) utilize the services of the MM layer 4115 to transfer SMS messages per standard circuit mode implementation. The SM-CP protocol is effectively tunneled between the UE 4105 and the MSC 4115 using the message relay functions in the GA-CSR protocol. As with CS mobility management and call control procedures, SMS uses the UE specific TCP signaling connection between the FAP and the INC 4120, providing reliable SMS delivery over the Up interface 4125.
- B. Packet Mode (PS Mode) SMS Services
- The Femtocell protocol architecture related to PS mode SMS support builds on the packet services signaling architecture described in the “PS domain—control plane architecture” Subsection under the “FEMTOCELL SYSTEM ARCHITECTURE” Section, above.
FIG. 42illustrates the GAN protocol architecture for packet mode SMS in some embodiments.
- On the UE 4205 side, the SMS layers 4210 (including the supporting CM sublayer functions) utilize the services of the GMM layer 4215 to transfer SMS messages per the standard packet mode implementation. The SM-CP protocol is effectively tunneled between the UE 4205 and the SGSN 4220 using the message relay functions in the GA-PSR protocol. As with the packet services signaling procedures, SMS uses the UE specific TCP signaling connection between the FAP and the INC 4225, providing reliable SMS delivery over the Up interface 4230.
- C. SMS Scenarios
- The following scenarios illustrate the message flows involved for various SMS scenarios via the Femtocell.
- 1. Circuit Mode Mobile-Originated SMS
FIG. 43illustrates a mobile originated SMS transfer via GAN circuit mode in some embodiments. As shown, the user enters a message and invokes the mobile-originated SMS function on the UE 4305 in idle mode. Steps 4 to 10 in FIG. 43are Steps 2 to 7 in the “Mobile originated call” Subsection under the “CALL MANAGEMENT” Section, above. Next, the UE 4305 sends (in Step 8) the SMS message encapsulated in a CP-DATA message to the FAP 4310 over the air interface.
- The FAP relays (in Step 9) the CP-DATA message encapsulated in a GA-CSR UL DIRECT TRANSFER message to the INC 4315. The INC forwards (in Step 10) the CP-DATA message to the MSC 4320 using RANAP Direct Transfer message. The MSC forwards (in Step 11) the message to the SMSC via the SMS interworking MSC (IWMSC) 4325 using the MAP-MO-FORWARD-SM Invoke message.
- The MSC sends (in Step 12) CP-DATA-ACK to acknowledge the receipt of the CP-DATA message. The SM-CP is designed in a way that every CP-DATA block is acknowledged on each point-to-point connection between the UE and SMSC (SM Service Center) to ensure that the under-laying transport layer (in this case RANAP) works error free since there is no explicit ack to a RANAP Direct Transfer message.
- The INC 4315 relays (in Step 13) the acknowledgement to the FAP 4310. The FAP forwards (in Step 14) the CP-DATA-ACK to the UE 4305 over the air interface. The SMSC sends (in Step 15) a SMS message in response to the IWMSC and the IWMSC sends the response to the MSC in the MAP-MO-FORWARD-SM Return Result message.
- Next, the MSC 4320 relays the response (in Step 16) to the INC 4315 in the CP-DATA message. The INC 4315 relays (in Step 17) this to the FAP 4310 using GA-CSR DL DIRECT TRANSFER. The FAP relays (in Step 18) the response to the UE over the air interface using the existing RRC connections.
- As part of SM-CP ack process, the UE acknowledges (in Step 19) the receipt of CP-DATA to the FAP. The FAP relays (in Step 20) the acknowledgement to the INC. The INC forwards (in Step 21) the acknowledgement to the MSC using the RANAP Direct Transfer message.
- Next, the MSC 4320 sends (in Step 22) Iu Release message to the INC indicating a request to release the session resources. The SCCP Connection Identifier is used to determine the corresponding session. The INC 4315 in turn releases (in Step 23) the GA-CSR connection to the FAP for the specific session. Also, the FAP 4310 releases (in Step 24) corresponding radio resources towards the UE. Finally, the INC acknowledges (in Step 25) the release in an Iu Release Complete message to the MSC. The SCCP connection associated with the call between the INC and the MSC is released.
- 2. CS Mode Mobile-Terminated SMS
FIG. 44illustrates a CS mode mobile terminated SMS transfer via Femtocell in some embodiments. As shown, the SMSC 4425 sends (in Step 1) a SMS message destined for the UE 4405 to the SMS gateway MSC (GMSC) 4420. The GMSC queries the HLR for routing information using the MAP-SEND-ROUTING-INFO-SM Invoke message.
- The HLR responds (in Step 2) with the MSC number associated with the serving MSC. The SMS GMSC delivers (in Step 3) the SMS message to the MSC using the MAP MT-FORWARD-SM Invoke message. Steps 4 to 10 are the same as Steps 2 to 8 in “Mobile Terminated Call” Section above, except that the user is attempting to terminate an SMS message; therefore, only a signaling channel is necessary.
- Next, the MSC 4420 sends (in Step 11) the SMS message encapsulated in a CP-DATA message to the INC 4415. The INC relays (in Step 12) this to the FAP 4410 using GA-CSR DL DIRECT TRANSFER. The FAP relays (in Step 13) the CP-DATA message to the UE 4405 over the air interface using the existing RRC connections.
- As part of SM-CP ack process, the UE acknowledges (in Step 14) the receipt of CP-DATA to the FAP. The FAP relays (in Step 15) the acknowledgement to the INC. The INC forwards (in Step 16) the acknowledgement to the MSC using the RANAP Direct Transfer message.
- The SMS entity on the UE acknowledges (in Step 17) the SMS message via another CP-DATA message (response) which is sent to the FAP over the air interface. The FAP relays (in Step 18) the response CP-DATA message encapsulated in a GA-CSR UL DIRECT TRANSFER message to the INC. The INC forwards (in Step 19) the response CP-DATA message to the MSC using RANAP Direct Transfer message.
- Next, the MSC 4420 sends the response (in Step 20) to the SMS GMSC 4425 in the MAP-MT-FORWARD-SM Return Result message. The GMSC relays the response to the SMSC. The MSC acknowledges (in Step 21) the receipt of CP-DATA to the INC. The INC 4415 relays (in Step 22) the CP-DATA-ACK to the FAP.
- Next, the FAP 4410 forwards (in Step 23) the CP-DATA-ACK to the UE 4405 over the air interface. The MSC 4420 sends (in Step 24) Iu Release message to the INC 4415 indicating a request to release the session resources. The SCCP Connection Identifier is used to determine the corresponding session.
- The INC 4415 in turn releases (in Step 25) the GA-CSR connection to the FAP for the specific session. The FAP releases (in Step 26) corresponding radio resources towards the UE. The INC acknowledges (in Step 27) the release in an Iu Release Complete message to the MSC. The SCCP connection associated with the call between the INC and the MSC is released XI. EMERGENCY SERVICES
- Transparent support for emergency services is a key regulatory requirement. Femtocell emergency services support capabilities include support for flexible UMTS-to-Femtocell SAI mapping and INC assignment functionality. This allows the FAP to be assigned to an INC that is, in turn, connected to an MSC that can route calls to the PSAP in the Femtocell service area. It also allows the service provider to define Femtocell service areas that align with macro network service areas, to leverage the existing service area based PSAP routing approach.
- Femtocell emergency services support capabilities also include support for the retrieval and storage of FAP location information from an external database, using the enhanced service access control functions. Femtocell emergency services support capabilities further include support for the RANAP Location Report procedure, by which the INC returns the FAP location information to the MSC during emergency call processing. Some embodiments do not support emergency calling from an un-authorized UE over a given FAP (due to the Service Access Control for the specific FAP).
- One of the functions of the UMTS-Femtocell mapping process is to assign a Femtocell Service Area for calls made by the UE using the Femtocell. The FAP, during registration, provides information on macro coverage (such as macro LAI, macro 3G cell-id, etc) which can be mapped to a Femtocell Service Area Identification (SAI). This Femtocell SAI can be used to support the ability to route emergency calls to the correct PSAP; i.e., based on SAI. However, to meet the requirement to route the emergency call to the correct PSAP, there are actually two possible approaches: (1) Service Area (i.e. SAI) Based Routing, and (2) Location Based Routing.
- A. Service Area Based Routing
- With Service Area Based Routing, the PSAP routing decision is based on the Service Area Code (SAC) included within the SAI.
FIG. 45illustrates a service area based routing scenario of some embodiments. As shown, the user originates (in Step 1) an emergency call using the UE 4505 camped on the Femtocell. The UE establishes (in Step 2) a RRC connection with the FAP with the establishment cause of emergency call.
- Upon request from the upper layers, the UE sends (in Step 3) the CM Service Request (with CM Service Type set to “Emergency Call Establishment”) to the FAP 4510. The FAP performs (in Step 4) the GA-CSR Connection Establishment procedure (with establishment cause indicating an Emergency call) with the INC 4515 as described in previous sections.
- The FAP 4510 then forwards (in Step 5) the CM Service Request to the INC 4515 using a GA-CSR UL DIRECT TRANSFER message. The INC 4515 establishes a SCCP connection to the MSC 4520 and forwards (in Step 6) the CM Service Request to the MSC 4520 using the RANAP Initial UE Message. This initial message includes information about the location area (LAI) and service area (SAI) assigned to the specific FAP over which the emergency call was initiated.
- The MSC 4520, INC 4515 and UE 4505 continue (in Step 7) call establishment signaling. The MSC determines the serving PSAP based on the service area of the calling UE and routes (in Step 8) the emergency call to the appropriate PSAP. Additional signal messages are exchanged between the UE and PSAP and the emergency call is established (in Step 9) between the UE and the appropriate serving PSAP.
- B. Location Based Routing
- One of the drawbacks service area based routing is that it would require that Femtocell service area be split into multiple service areas based on PSAP routing requirements. The location based routing method removes this limitation. Location based routing is also known as “X/Y routing” or “Routing by position” and is defined in “Location Services (LCS); Functional description; Stage 2”, 3GPP TS 23.271. Some embodiments support Location based routing while some other embodiments do not support Location based routing.
- GAN Femtocell supports security mechanisms at different levels and interfaces as depicted in
FIG. 46. As shown, the security mechanisms over the Up interface 4605 protect signaling, voice and data traffic flows between the FAP 4610 and the GANC SeGW 4615 from unauthorized use, data manipulation and eavesdropping; i.e. authentication, encryption and data integrity mechanisms are supported.
- Authentication of the subscriber by the core network occurs between the MSC/VLR or SGSN 4620 and the UE 4625 and is transparent to the GANC 4640. The air interface between the UE 4625 and FAP 4610 is protected via encryption (ciphering) and integrity checks. In some embodiments the use of ciphering on the air interface is optional.
- Additional application level security mechanisms may be employed in the PS domain to secure the end-to-end communication between the FAP 4605 and the application server 4630. For example, the FAP may run the HTTP protocol over an SSL session for secure web access.
- All signaling traffic and user-plane traffic sent between FAP and GANC over the Up interface 4605 is protected by a secure tunnel (e.g., an IPSec tunnel) between the FAP 4605 and GANC-SeGW 4615, that provides mutual authentication (using SIM or USIM credentials), encryption and data integrity using the same mechanisms as specified in “3G security; Wireless Local Area Network (WLAN) interworking security”, 3GPP TS 33.234 standard, hereinafter “TS 33.234 standard”. The use of a single secure tunnel between the FAP 4610 and the GANC 4640 enables multiple UEs 4625 (only one is shown in
FIG. 46for simplicity) as well as the Femtocell itself (e.g., the FAP signaling or when the FAP supports local service using the FAP IMSI, the signaling and the user plane for the FAP utilize the same IPSec tunnel). The advantages of using a single IPSec tunnel between the FAP and the GANC include relieving the SeGW from supporting a large number of secure tunnels.
- A. Authentication
- In some embodiments, the Up interface supports the ability to authenticate the FAP with the GANC (for the purposes of establishing the secure tunnel) using UMTS credentials. Authentication between FAP and GANC shall be performed using EAP-AKA or EAP-SIM within IKEv2.
- The FAP and GANC-SeGW establish a security association for protecting signaling traffic and user-plane (voice and data) traffic. The protocol for authentication is IKEv2. Mutual authentication and key generation is provided by EAP-AKA or EAP-SIM.
- The basic elements of these procedures are the following. The FAP connection with the GANC-SeGW is initiated by starting the IKEv2 initial exchanges (IKE_SA_INIT). The EAP-AKA or EAP-SIM procedure is started as a result of these exchanges. The EAP-SIM procedure for FAP with SIM only or FAP with USIM, but not capable of UMTS AKA, is performed between FAP and AAA server (that has access to the AuC/HLR/HSS to retrieve subscriber information). The EAP-AKA procedure for FAP with USIM and the FAP is capable of UMTS AKA, is performed between FAP and AAA server. The GANC-SeGW acts as relay for the EAP-SIM/EAP-AKA messages.
- When the EAP-AKA/EAP-SIM procedure has completed successfully, the IKEv2 procedure can be continued to completion and the signaling channel between FAP and GANC-SeGW is secured. The FAP can then continue with the discovery or registration procedure. Signaling flows for EAP-AKA/EAP-SIM authentication are shown in the following subsection.
- 1. EAP-SIM Procedure for Authentication
- The EAP-SIM authentication mechanism is specified in “Extensible Authentication Protocol Method for GSM Subscriber Identity Modules (EAP-SIM)”, IETF RFC 4686. This section describes how this mechanism is used in Femtocell.
FIG. 47illustrates EAP-SIM authentication procedure in some embodiments. As shown, the FAP 4705 connects to the generic IP access network and obtains (in Step 1) the IP address of the Default or the Serving SeGW via DNS query. In response, the DNS server 4710 returns (in Step 2) the IP address of the SeGW.
- Next, the FAP 4705 initializes the IKEv2 authentication procedure by starting (in Steps 3 a-3 c) the IKE_SA_INIT exchange. It indicates the desire to use EAP by leaving out the AUTH payload from message 3, the first message of the IKE_AUTH exchange, and the initiator identity is composed compliant with the Network Access Identifier (NAI) format specified in “The Network Access Identifier”, IETF RFC 2486, hereinafter “IETF RFC 2486”, which includes the IMSI and an indication that EAP-SIM should be used.
- Next, the GANC-SeGW 4715 sends (in Step 4) an EAP Response/Identity message to the AAA server 4720, including the initiator identity included in the third IKE message. The leading digit of the NAI indicates that the FAP wishes to use EAP-SIM. The AAA server 4720 identifies the subscriber as a candidate for authentication with EAP-SIM, based on the received identity, and verifies that EAP-SIM shall be used based on subscription information. The AAA then sends (in Step 5) the EAP Request/SIM-Start packet to GANC-SeGW 4715.
- The GANC-SeGW forwards (in Step 6) the EAP Request/SIM-Start packet to FAP. The FAP chooses a fresh random number NONCE_MT. The random number is used in network authentication. The FAP sends (in Step 7) the EAP Response/SIM-Start packet, including NONCE_MT, to the GANC-SeGW.
- The GANC-SeGW forwards (in Step 8) the EAP Response/SIM-Start packet to the AAA Server. The AAA server 4720 requests (in Step 9) authentication data from the HLR 4725, based on the IMSI. The AAA server could instead use cached triplets previously retrieved from the HLR to continue the authentication process.
- Optionally, the AAA 4720 receives (in Step 10) user subscription and multiple triplets from the HSS/HLR 4725. AAA server determines the EAP method (SIM or AKA) to be used, according to the user subscription and/or the indication received from the FAP. In this sequence diagram, it is assumed that the FAP holds a SIM and EAP-SIM will be used.
- The AAA server formulates an EAP-SIM/Challenge with multiple RAND challenges, and includes a message authentication code (MAC) whose master key is computed based on the associated Kc keys, as well as the NONCE_MT. A new re-authentication identity may be chosen and protected (i.e. encrypted and integrity protected) using EAP-SIM generated keying material. The AAA Server sends (in Step 11) this RAND, MAC and re-authentication identity to the GANC-SeGW in the EAP Request/SIM-Challenge message. The GANC-SeGW forwards (in Step 12) the EAP Request/SIM-Challenge message to the FAP.
- The FAP runs (in Step 12) N times the GSM A3/A8 algorithm in the SIM, once for each received RAND. This computing gives N SRES and Kc values. The FAP calculates its copy of the network authentication MAC with the newly derived keying material and checks that it is equal with the received MAC. If the MAC is incorrect, the network authentication has failed and the FAP cancels the authentication. The FAP continues the authentication exchange only if the MAC is correct. The FAP calculates a new MAC with the new keying material covering the EAP message concatenated to the N SRES responses. If a re-authentication ID was received, then the FAP stores this ID for future authentications.
- The FAP 4705 sends (in Step 14) EAP Response/SIM-Challenge including calculated MAC to the GANC-SeGW 4715. The GANC-SeGW forwards (in Step 15) the EAP Response/SIM-Challenge message to the AAA Server 4720. The AAA Server verifies (in Step 16) that its copy of the response MAC is equal to the received MAC.
- If the comparison in step 16 is successful, then the AAA Server sends (in Step 17) 18) the FAP about the successful authentication with the EAP Success message. Now the EAP-SIM exchange has been successfully completed, the IKE signaling can be completed (in Step 19). The Secure Association between FAP and GANC-SeGW has been completed and the FAP can continue with the Femtocell discovery or registration procedure.
- 2. EAP-AKA Procedure for Authentication
- The EAP-AKA authentication mechanism is specified in “Extensible Authentication Protocol Method for 3rd Generation Authentication and Key Agreement (EAP-AKA)”, IETF RFC 4187. This section describes how this mechanism is used in Femtocell.
FIG. 48illustrates EAP-AKA authentication procedure of some embodiments. As shown, the FAP 4805 connects to the generic IP access network and obtains (in Step 1) the IP address of the Default or the Serving SeGW via DNS query. The DNS server 4810 returns (in Step 10) the IP address of the SeGW.
- The FAP 4805 initializes the IKEv2 authentication procedure by starting the IKE_SA_INIT exchange (Steps 3 a-3 c). It indicates the desire to use EAP by leaving out the AUTH payload from message 3, the first message of the IKE_AUTH exchange, and the initiator identity is composed compliant with the Network Access Identifier (NAI) format specified in the IETF RFC 2486 which includes the IMSI and an indication that EAP-AKA should be used.
- Next, the GANC-SeGW 4815 sends (in Step 4) an EAP Response/Identity message to the AAA server 4820, including the initiator identity included in the third IKE message. The leading digit of the NAI indicates that the FAP wishes to use EAP-AKA. The AAA server identifies the subscriber as a candidate for authentication with EAP-AKA, based on the received identity, and verifies that EAP-AKA shall be used based on subscription information, The AAA server requests (in Step 5) the user profile and UMTS authentication vector(s) from the HSS/HLR 4825, if these are not available in the AAA server.
- Optionally, the AAA receives (in Step 6) user subscription and UMTS authentication vector(s) from the HSS/HLR. The UMTS authentication vector consists of random part (RAND), an authentication token (AUTN), an expected result part (XRES) and sessions keys for integrity check (IK) and encryption (CK). The AAA server determines the EAP method (SIM or AKA) to be used, according to the user subscription and/or the indication received from the FAP. In this sequence diagram, it is assumed that the FAP holds a USIM and EAP-AKA will be used.
- Next, the AAA server 4820 formulates an EAP-Request/AKA Challenge with RAND, AUTN and includes a message authentication code (MAC) whose master key is computed based on the associated IK and CK. A new re-authentication identity may be chosen and protected (i.e. encrypted and integrity protected) using EAP-AKA generated keying material. The AAA Server sends (in Step 7) the RAND, AUTN, MAC and re-authentication identity to the GANC-SeGW 4815 in the EAP Request/AKA-Challenge message.
- The GANC-SeGW forwards (in Step 8) the EAP Request/AKA-Challenge message to the FAP. The FAP runs (in Step 9) UMTS algorithm on the USIM. The USIM verifies that the AUTN is correct and hereby authenticates the network. If AUTN is incorrect, the FAP rejects the authentication. If AUTN is correct, the USIM computes RES, IK and CK. The FAP calculates a new MAC with the new keying material (IK and CK) covering the EAP message. If a re-authentication ID was received, then the FAP stores this ID for future authentications.
- The FAP then sends (in Step 10) EAP Response/AKA-Challenge including calculated RES and MAC to the GANC-SeGW. The GANC-SeGW forwards (in Step 11) the EAP Response/AKA-Challenge message to the AAA Server.
- The AAA Server verifies (in Step 12) the received MAC and compares XRES to the received RES. If the checks in Step 12 are successful, then the AAA Server sends (in Step 13) 14) the FAP about the successful authentication with the EAP Success message. Now the EAP-SIM exchange has been successfully completed, the IKE signaling can be completed (in Step 15). The Security Association between FAP and GANC-SeGW has been completed and the FAP can continue with the Femtocell discovery or registration procedure.
- 3. Fast Re-Authentication
- When the authentication process is performed frequently, especially with a large number of connected Femtocell Access Points, performing fast re-authentication can reduce the network load resulting from this authentication. The fast re-authentication process allows the AAA server to authenticate a user based on keys derived from the last full authentication process.
- The FAP and GANC-SeGW can use a procedure for fast re-authentication in order to re-authenticate an FAP e.g. when setting up a new SA because the IP address of the FAP has changed. Fast re-authentication is provided by EAP-AKA, and does not make use of the UMTS algorithms. The FAP may use the re-authentication ID in the IKE_SA_INIT. The decision to make use of the fast re-authentication procedure is taken by the AAA server.
- The basic elements of these procedures are the following. The FAP initiates a new SA with a GANC-SeGW that it was previously connected to and uses the re-authentication ID (re-authentication ID received during the previous full authentication procedure) in the IKE_SA_INIT exchange. The EAP-AKA procedure is started as a result of these exchanges. The AAA server and FAP re-authenticate each other based on the keys derived on the preceding full authentication.
- B. Encryption
- All control and user plane traffic over the Up interface shall be sent through the IPSec tunnel that is established as a result of the authentication procedure. Encryption shall use the negotiated cryptographic algorithm, based on core network policy, enforced by the GANC-SeGW.
- The FAP and GANC-SeGW set up one Security Association through which all traffic is sent. A single negotiated ciphering algorithm is applied to the connection.
- 1. Establishment of a Security Association
- After the authentication procedure, the FAP shall request an IP address on the network protected by the GANC-SeGW (i.e. the public IP interface of the INC). The FAP shall set up one IPSec Security Association (SA) between FAP and GANC-SeGW.
- The FAP shall initiate the creation of the SA; i.e. it shall act as initiator in the Traffic Selector negotiation. The protocol ID field in the Traffic Selectors (TS) shall be set to zero, indicating that the protocol ID is not relevant. The IP address range in the TSi shall be set to the address assigned to the FAP (within the network protected by the GANC-SeGW). The IP address range in the TSr shall be set to 0.0.0.0-255.255.255.255. The FAP and GANC-SeGW shall use the IKEv2 mechanisms for detection of NAT, NAT traversal and keep-alive.
- All control and user plane data over the Up interface between FAP and INC shall be sent through the SA. The ciphering mode is negotiated during connection establishment. During setup of the SA, the FAP includes a list of supported encryption algorithms as part of the IKE signaling, which include the mandatory and supported optional algorithms defined in the IPSec profile, and NULL encryption. The GANC-SeGW selects one of these algorithms, and signals this to the FAP.
- When NULL encryption is applied, both control and user-plane traffic is sent unencrypted. This configuration can be selected e.g. when the connection between the generic IP access network and the GANC is under operator control. The integrity algorithm is the same as for either configuration i.e. non-ciphered traffic is still integrity protected.
- C. Profile of IKEv2
- In some embodiments, profile of IKEv2 for Femtocell system is similar to the profile defined in TS 43.318 standard.
- D. Profile of IPSec ESP
- In some embodiments, profile of IPSEC ESP for Femtocell system is similar to the profile defined in TS 43.318 standard.
- E. Security Mode Control
FIG. 49illustrates the message flow for security mode control in some embodiments. As shown, the CN (VLR/SGSN) 4920 and the UE 4905 perform (in Step 1) mutual authentication using AKA procedures. The CN authentication is initiated by the CN as a result of the CN processing an initial L3 message from the UE.
- Upon successful authentication, the CN sends (in Step 2) RANAP “Security Mode Command” message to GANC. This message includes the integrity key (IK) key, the ciphering (or encryption) key (CK), the user integrity algorithm (UIA), and the ciphering (or user encryption) algorithm (UEA) to be used for ciphering.
- In some embodiments, the GANC stores the ciphering and integrity keys and the algorithms. The GANC sends (in Step 3) a GA-CSR SECURITY MODE COMMAND with the ciphering and integrity keys and algorithms associated with the specific UE IMSI to the FAP 4910. The FAP stores the ciphering and integrity keys and algorithm (in Step 4) for the specific UE. The FAP should ensure that these keys are not accessible to 3rd party applications or any other module on the FAP. Additionally, these keys should not be stored on any persistent storage. The CK and UEA are used to protect the air interface between the FAP and the UE by encrypting the traffic between the FAP and the UE. The IK and the UIA are used to ensure the integrity of the messages exchanged between the FAP and the UE over the air interface, for example by determining that the messages are not changed. In some embodiments, the UIA and the UEA are software methods executed by a processor.
- The FAP generates a random number (FRESH) and computes the downlink (i.e., from the FAP to the UE) message authentication code (MAC) using the integrity key (IK) and integrity algorithms (MAC-I) and sends (in Step 5) the Security Mode command to the UE 4905 along with the computed message authentication code for integrity (MAC-I) and the FRESH. The FRESH variable represents a random number or nonce as defined in “3G Security; Security architecture”, 3GPP TS 33.102 standard, hereinafter “TS 33.102 standard”. The UE computes (in Step 6) the MAC-I locally (expected MAC-I or XMAC-I) and verifies (in Step 6) that the received downlink MAC-I is same. The UE computes XMAC-I on the message received by using the indicated UIA, COUNT-I generated from the stored START and the received FRESH parameter as defined in TS 33.102 standard. The downlink integrity check is started from this message onwards. For all subsequent messages sent from the FAP to the UE (the downlink messages), steps similar to Steps 5 to 6 are used to ensure the integrity of the messages.
- Upon successful verification of the MAC, the UE responds back (in step 7) with the Security Mode Complete command and also sends the MAC-I for the uplink (i.e., from the UE to the FAP) message. The FAP computes (in Step 8) XMAC-I for the uplink message and verifies (in Step 8) the received MAC-I is same as that of computed XMAC-I. The uplink integrity check is started from this message onwards. For all subsequent messages sent from the UE to the FAP (the uplink messages), steps similar to Steps 7 to 8 are used to ensure the integrity of the messages.
- MAC-I is the sender's computed MAC-I and XMAC-I is the expected MAC-I computed by the receiver. As described above, the computation is done for a given message using the algorithms and other variables which are known to the sender and receiver only. This prevents a man-in-the-middle attack, as the middle entity will not have the necessary information to compute MAC-I and hence cannot tamper the message.
- Upon successful verification of the uplink MAC, the FAP sends (in Step 9) the GA-CSR Security mode complete command to the GANC. The GANC relays (in Step 10) the Security Mode Complete command to the CN via corresponding RANAP message.
- F. Core Network Authentication
- The core network AKA based authentication provides mutual authentication between the user and the network. The AKA procedure is also used to generate the ciphering keys (encryption and integrity) which in turn provide confidentiality and integrity protection of signaling and user data. The basis of mutual authentication mechanism is the master key K (permanent secret with a length of 128 bits) that is shared between the USIM of the user and home network database. The ciphering key (Ck) and the integrity key (Ik) are derived from this master key K.
FIG. 50illustrates the AKA procedure used for mutual authentication in some embodiments. As shown, when the UE 5005 camps on the Femtocell Access Point 5010, it initiates (in Step 1) a Location Update Request (or Location Updating Request) towards the CN. The INC 5015 forwards) in Step 2) the Location Update request in a RANAP message to the VLR/SGSN 5020.
- This triggers the authentication procedure in the VLR/SGSN and it sends (in Step 3) an authentication data request MAP message to the Authentication Center (AuC) in the Home Environment (HE) 5025. The AuC includes the master keys of the UEs and based on the IMSI, the AuC will generate the authentication vectors for the specific UE. The vector list is sent back (in Step 4) to the VLR/SGSN in the authentication data response MAP message.
- The VLR/SGSN selects (in Step 5) one authentication vector from the list (only 1 vector is needed for each run of the authentication procedure). The VLR/SGSN sends (in Step 6) user authentication request (AUTREQ) message to the INC. This message also includes two parameters RAND and AUTN (from the selected authentication vector).
- The INC 5015 relays (in Step 7) the AUTREQ message to the FAP 5010 in a GA-CSR DL DIRECT TRANSFER message. The FAP forwards (in Step 8) the AUTREQ to the UE over the air interface. The USIM on the UE includes the master key K and using it with the parameters RAND and AUTN as inputs, the USIM carries out computation resembling generation of authentication vectors in the AuC. From the generated output, the USIM verifies (in Step 9) if the AUTN was generated by the right AuC.
- The USIM computation also generates (in Step 10) a RES which is sent towards the CN in an authentication response message to the CN. The FAP forwards (in Step 11) the Authentication Response to INC. The INC relays (in Step 12) the response along with the RES parameter in a RANAP message to the CN.
- The VLR/SGSN verifies (in Step 13) compares the UE response RES with the expected response XRES (which is part of authentication vector). If there is a match, authentication is successful. The CN may then initiate (in Step 14) a Security Mode procedure (as described in the Subsection “Security mode control”, above) to distribute the ciphering keys to the INC.
- G. Service Theft in Femtocell
- By definition, the FAP has a radio interface (Uu) to communicate with UEs and a network interface (Up) to the mobile network. The FAP relays messages between the UE and core network and can eavesdrop and intercept these messages. The FAP, if compromised, becomes the infamous ‘man’ of the man-in-the-middle security exposure.
- In normal operation, the macro cell network directs UEs to scan for the Femtocell UTRA Absolute Radio Frequency Channel Number (UARFCN) and scrambling code (SC) so when a UE detects FAP radio coverage, the UE can attempt to camp on the FAP. The FAP {UARFCN, SC} is expected to be configured in the macro network RNC's neighbor cell list so that RNC can provide the UE with this neighbor cell list, thus resulting in the UE performing the scans of the neighbors cells and eventual cell selection of a better neighbor for camping. The UE performs a location update, provides its identity, whether IMSI or TMSI, expects to be authenticated, and then proceeds to camp on the Femtocell for mobile service. This is exactly what is supposed to happen when the UE visits a network authorized FAP.
- When the FAP is compromised or is a rogue, then the UE could be exposing itself to theft of service. When the UE provides its identity to the FAP, the FAP can masquerade as the UE to the mobile network. Normally, UE authentication would prevent this kind of identity theft, but being in the middle of the communication between the core network and the UE, the FAP can relay authentication requests to the victim UE to defeat authentication.
- The UE believes it is being authenticated by the network and provides the correct authentication response to the FAP. The FAP sends the correct response to the core network and the core network now believes the FAP has been authenticated. In between network initiated authentication requests, the FAP can request and receive service from the mobile network disguised as the victim UE. For example, calls originated by the FAP would now be charged to the victim UE. UMTS signaling message integrity mechanisms do not help in this case because the integrity protection is provided over the air interface between the UE and the FAP.
- Since the FAP is in the possession of the end user and communicates with the GANC over the Internet, it is possible for a compromised or rogue FAP to attempt to circumvent the UMTS security architecture. A rogue FAP is the classical man-in-the-middle attacker between the UE and the CN. Without adequate network security validations and the enforcement of access policies, rogue FAPs can masquerade as a victim UE and use mobile network services using the victim UE's identity. A FAP is categorized in the following three access control modes: closed access, semi-open access, or open access.
- In a closed access case, access to complete Femtocell services over a given FAP is restricted to a closed group of subscribers. In a semi-open access case, limited access is provided to all subscribers. A subscriber who is not part of the closed group is allowed to receive incoming calls and SMS over the semi-open FAP. Additionally, the subscriber is also allowed to make emergency calls using the FAP operating in semi-open access mode. All other services, such as outgoing calls, are blocked. Finally, in an open access case, all subscribers of a given operator are allowed full service access over a FAP operating in open access mode. The following techniques are used in some embodiments to protect against UE masquerade and theft of service at a FAP operating in one of above mentioned modes.
- 1. Closed Access Points
- In a closed access FAP, UEs that are members of the FAP's private user group cannot be victimized because the FAP and the UEs in the private user group are linked by the subscription process. The GANC can enforce network-based service access controls to prevent victim UEs from being trapped by a rogue FAP. If the UE is not a member of the private user group of the rogue FAP, the GANC will deny service access to the UE. This means the rogue FAP is prevented from stealing service with the victim UE's identity.
- The GANC also strictly binds transactions performed under each UE registration context to the original authorized UE identity to prevent a rogue FAP from piggybacking messages using a victim UE identity through the authorized UE context. The strict binding requires the GANC to track the identity of each UE even as it is assigned TMSI and P-TMSI for User Identity Confidentiality. Prevention of service theft in a closed access mode is described in detail further below.
- 2. Semi-Open and Open Access Points
- The potential for a rogue FAP to masquerade as a victim UE is only available on the semi-open and open access points. The victim UEs would be the UEs that the network allows to camp on the rogue FAP but is not a member of the FAP's private user group. For those UEs, the theft of service potential is real because the rogue FAP has an incentive to charge its usage to the victim UE subscription account.
- Note, the theft-of-service scenario is only possible while a victim UE is camped on the rogue FAP. The rogue FAP can authenticate to the core network (CN) as the UE and then request services from the CN masquerading as the UE. So long that the victim UE remains camped at the rogue FAP, the FAP can continue to pass authentication requests and carry on the masquerade.
- For semi-open FAPs, by definition, prevents outgoing services to be initiated by UEs that are not a member of the FAP's private user group. Network-based enforcement of the semi-open access controls can prevent rogue FAPs from stealing service by masquerading as a victim UE. However, a rogue FAP can block incoming calls to the victim UE or eavesdrop on the conversation while the victim UE is camped on the rogue FAP. The semi-open FAP scenario is similar to the open FAP scenario described below.
- For open FAPs, the GANC by definition cannot place restrictions on the usage of mobile network services for any UE. It is also not possible to determine on a per call basis whether the call was legitimately made by the UE or whether the FAP is masquerading as a victim UE. This makes network enforcement of UE access controls ineffective for preventing UE masquerade. The prevention method must focus on ensuring only genuine and unmodified FAPs are granted open access.
- 3. Enhanced Security Solution for Open Access Points
- Open FAPs can be misused through the following two scenarios: (1) Complete replacement of a genuine FAP with rogue equipment and (2) Modification of the existing software executing on the FAP from an authorized vendor.
- a) Detection of Genuine FAP
- The replacement of a genuine FAP with rogue equipment can be prevented using a technique based on public and private keys. In this solution the FAP is required to provide a Message Authentication Code (MAC), computed from the vendor's private key, with the UMA Registration message. The GANC, using the AAA, can verify the MAC on the UMA Registration message by comparing the MAC with one computed with the FAP vendor's public key. Only genuine FAPs can provide the correct MAC in the UMA Registration message.
- Procedure details are as follows. Each FAP vendor generates a private/public key pair. The public key is stored in a FAP database in the network. When the FAP registers with the GANC, the GANC sends a Register challenge message by including a RAND number in the challenge. The FAP sends the challenge response and includes the MAC (message authentication code) generated using the vendor's private key. The MAC is generated using the standard algorithms for SHA1.
- The GANC relays the random number and the generated MAC to the AAA via the S1 interface. The AAA retrieves the public key from the FAP database and computes its expected MAC. If the locally computed MAC is the same as that received over the network, then AAA has verified the FAP is genuine. If the MAC check in the AAA fails, the registration is rejected thus preventing access to services using the GANC. Note there is one private key for all FAPs from the same vendor so every FAP has the same image. The private key should never be stored in an unencrypted fashion. This detection method must be combined with the following method to protect the private keys from being extracted from the FAP.
- b) Ensuring Unmodified FAPs
- The FAP hardware may implement a “software authentication” technique to ensure only authentic, authorized software is allowed to execute on the FAP hardware. Some embodiments perform the following software authentication technique. The “bootloader” software, which is responsible for establishing the initial state of the system, so that the proper operating system and application can be loaded, will control the download and authorization of the software. The “bootloader” software must be implicitly trusted and therefore needs to be immutable. This requirement can be met, for example, by implementing the bootloader software in ROM or OTP flash.
- The software loaded on the FAP is signed using the private key for each vendor. The bootloader software would be responsible for verification of this signature using the public key of the vendor. A failed signature check will prevent the “rogue” software from executing successfully. Note that the public key can be delivered to the bootloader software via signed certificates or it can be stored directly locally in the bootloader.
- The above technique prevents the loading of software onto the FAP hardware by anyone except the vendor. Only the vendor possesses the private key necessary to sign the software and pass the “software authentication.”
- 4. High Level Procedure
FIG. 51illustrates the high level procedure which can result in theft of service by a rogue FAP. The following description of the Femtocell service theft procedure assumes the following: (1) the Rogue FAP is a closed AP i.e. Femtocell service access is limited to a trusted list of UEs (in this example, only UE-1 associated with identity IMSI-1/TMSI-1 is allowed Femtocell service access using the Rogue FAP), (2) closed AP has implied security as part of mutual trust between FAP and the associated UEs. The close AP behavior is ensured by the network using service access control (SAC) at the time of UE registration, (3) victim UE is associated with identity IMSI-2/TMSI-2 and is NOT allowed service on this Rogue FAP, and (4) the ‘Rogue’ FAP has been compromised and is attempting to steal services using victim UE identity outside the trust list. Although FIGS. 51 to 53illustrate steps related to circuit switched resources (CSR), a person of ordinary skill in the art would be able to apply the same techniques to packet switched resources (PSR).
- As shown in
FIG. 51, the authorized UE 5110 establishes (in Step 1 a) a RRC connection with the FAP 5115 on which it camps. The UE 5110 starts (in Step 1 b) a Location Update procedure towards the CN 5130. The FAP 5115 will intercept the Location Update request and attempts to register the UE 5110 with the associated Serving GANC 5120 over the existing IPSEC tunnel. The FAP 5115 may request (in Step 1 c) and receive (in Step 1 d) the IMSI of the UE 5110 if the Location Update is done using the TMSI, since the IMSI is required for the initial registration of the UE.
- Next, the FAP 5115 attempts to register the UE 5110 on the GANC 5120 using the UE specific TCP connection by transmitting (in Step 2) the GA-RC REGISTER REQUEST. The message includes: (1) Registration Type: Indicates that the registering device is a UE, (2) Generic IP access network attachment point information: AP-ID, (3) UE Identity: UE-IMSI, and (4) FAP identity: FAP-IMSI. The GANC 5120 will, via AAA server 5125, authorize (in Steps 2 a-2 c) the UE 5110 using the information provided in the REGISTER REQUEST. The authorization logic on the AAA server 5125 would also check to see if the UE 5110 is allowed Femtocell access using the specific FAP 5115.
- When the GANC 5115 accepts the registration attempt, the GANC responds (in Step 3) with a GA-RC REGISTER ACCEPT. The FAP 5115 encapsulates (in Step 4) the Location Update NAS PDU within a GA-CSR UL DIRECT TRANSFER message that is forwarded to the GANC 5120 via the existing TCP connection.
- The GANC 5120 establishes a SCCP connection to the CN and forwards (in Step 5) the Location Update request NAS PDU to the CN using the RANAP Initial UE Message. Subsequent NAS messages between the UE and core network will be sent between GANC and CN using the RANAP Direct Transfer message. The CN 5130 authenticates (in Step 6) the UE 5110 using standard UTRAN authentication procedures. The CN 5130 also initiates (also in Step 6) the standard Security Mode Control procedure as described in TS 33.102 standard, which results in distribution of the security keys {CK, IK} for the specific UE to the FAP via the GANC.
- Next, the CN 5130 indicates (in Step 7) that it has received the location update and it will accept the location update using the Location Update Accept message to the GANC 5120. The GANC 5120 forwards this message to the FAP 5115 in the GA-CSR DL DIRECT TRANSFER. Next, the FAP relays (in Step 9) the Location Update Accept over the air interface to the UE 5120.
- At this point, a session authorized for the specific UE-1 using its credentials IMSI-1 is established (in Step 10) between the FAP 5115 and GANC 5120. Next, a victim UE 5105, in the vicinity of the rogue FAP 5115, upon discovering the FAP 5115 over the air interface, will attempt to camp on the rogue FAP 5115 based on its internal cell selection logic. This will trigger the UE 5105 to establish (in Step 11 a) an RRC connection with the Rogue FAP 5115. The UE will then start (in Step 11 b) a Location Update procedure towards the CN 5130. The FAP 5115 will intercept the Location Update request. The FAP will then request (in Step 11 c) and receive (in Step 11 d) the IMSI of the victim UE 5105 if the Location Update is done using the TMSI.
- The rogue FAP instead of attempting a registration of the victim UE 5105 with the GANC 5120, will re-use the existing authorized session of UE-1 5110 (as described in step 10) to transfer messages to the CN 5130 via GANC 5120. It is important to note that if the registration for the victim UE was attempted by the rogue FAP using the victim UE credentials (i.e. IMSI-2), the network based SAC would have rejected the registration request since the victim UE-2 5105 is not authorized to use Femtocell service over the specific rogue FAP 5115.
- The FAP 5115 encapsulates the Location Update NAS PDU within a GA-CSR UL DIRECT TRANSFER message that is forwarded (in Step 13) to the GANC 5120 via the existing TCP connection of UE-1 5110. The GANC 5120 establishes a SCCP connection to the CN 5130 and forwards (in Step 14) the Location Update request NAS PDU to the CN 5130 using the RANAP Initial UE Message. Subsequent NAS messages between the UE 5105 and core network 5130 will be sent between GANC 5120 and CN 5130 using the RANAP Direct Transfer message.
- Next, the CN 5130 authenticates (in Step 15) the victim UE-2 using standard UTRAN authentication procedures. The authentication messages are relayed transparently to the UE 5105 by the GANC 5120 and FAP 5115. The CN 5130 also initiates (in Step 15) the standard Security Mode Control procedure as described in TS 33.102 standard, which results in distribution of the security keys {CK, IK} for the victim UE to the FAP via the GANC.
- Upon completion of the authentication, the CN 5130 indicates (in Step 16) it has received the location update and it will accept the location update using the Location Update Accept message to the GANC 5120. The GANC 5120 forwards (in Step 17) this message to the FAP 5115 in the GA-CSR DL DIRECT TRANSFER. The FAP 5115 relays (in Step 17) the Location Update Accept over the air interface to the victim UE.
- The CN 5130 now thinks that the victim UE 5105 has been authenticated via the FAP 5115 and the GANC 5120 and will accept service requests from the victim UE 5105 without additional authentication for a specific time window. This time window, during which no addition authentication is performed for a given subscriber, is typically controlled by the CN 5130 based on specific implementation. The FAP 5115 takes advantage of this window and can now initiate service requests using the victim UE 5105 credentials and identity e.g. the FAP 5115 can now originate a Mobile Originated (MO) call using IMSI-2 as the subscriber identity resulting in fraudulent charge to the victim UE's subscription. It is important to note that even if the CN 5130 decides to authenticate every service request from a given subscriber (such as MO), the FAP 5115 can relay the authentication messages to the victim UE 5105 and accomplish successful authentication to the CN 5130.
- H. Mechanisms for Preventing Service Theft in Femtocell
- In this sub-section, a GANC is disclosed that protects the mobile network from the kind of man-in-the-middle theft scenario described above. The theft-of-service risk is different for different classes of UEs. For UEs that are affiliated with the FAP through a linked subscription account such as a family plan, the theft-of-service risk can be mitigated through the design of the plan pricing to remove any incentive to mislead the network. The FAP would only be stealing service from its own account.
- For UEs that are not affiliated with the FAP, the theft of service potential is real because the rogue FAP now has an incentive to charge its usage to a victim UE account. The GANC has the responsibility to prevent non-affiliated UEs from being captured by the FAP. The GANC does this by restricting each FAP to serve a defined list of affiliated UEs. The disclosed GANC AAA-based service access controls provides the decision logic to enable this UE restriction. Every UE access is individually authorized through the AAA during the UE UMA registration. The AAA only authorizes UE access after validating that the UE and the FAP are affiliated and the UE access originated from the same IP address, through the same IPSec tunnel as the FAP. The GANC enforces the AAA authorization decision by accepting or denying the UMA registration request for the UE.
- In addition, all subsequent communications from the UE are validated by the GANC to prevent rogue FAPs from attempting to insert control plane messages for the victim UE into previously authorized registration contexts. The GANC monitors the allocation of TMSI and P-TMSI to the UE so it can associate the UE with any of the UE's identities: IMSI, TMSI, and P-TMSI. This allows the GANC to enforce the UE-FAP affiliation on communication between the UE and the core network no matter whether the control plane messages are addressed with the UE IMSI, TMSI, or P-TMSI. The following two sub-sections describe the high level procedures with two different approaches which prevent attempted service theft by a rogue FAP
- 1. Service Theft Prevention—Approach 1
FIG. 52illustrates the Femtocell service theft prevention approach of some embodiments. Steps 1-7 are the same as Step 1-7 described in relation with FIG. 51above. The GANC 5220 monitors (in Step 8) allocation of new temporary identity to the UE 5210 by the CN 5230, i.e. TMSI for CS services and P-TMSI for PS services, and creates an association between the TMSI or P-TMSI and session identity for the specific UE. The GANC will utilize this information to perform security checks on session identity for subsequent NAS layers messages originating on the UE specific session.
- The GANC 5220 forwards (in Step 9) the Location Update information received from the CN 5230 to the FAP 5215 using a GA-CSR DL DIRECT TRANSFER message. The FAP 5215 relays (In Step 10) the Location Update Accept over the air interface to the UE 5210.
- At this point, a session authorized for the specific UE-1 using its credentials IMSI-1 is established (in Step 11) between the FAP 5215 and GANC 5220. Next, a victim UE 5205, in the vicinity of the rogue FAP 5215, upon discovering the FAP 5215 over the air interface, attempts to camp on the rogue FAP based on its internal cell selection logic. This will trigger the UE 5205 to establish (in Step 12 a) a RRC connection with the Rogue FAP. The UE 5205 then starts (in Step 12 b) a Location Update procedure towards the CN 5230. The FAP 5215 intercepts the Location Update request. The FAP will then request (in Step 12 c) and receives (in Step 12 d) the IMSI of the victim UE 5205 if the Location Update is done using the TMSI.
- The rogue FAP 5215 instead of attempting a registration of the victim UE 5205 with the GANC 5220, re-uses (in Step 13) the existing authorized session of UE-1 5210 (as described in Step 11 above) to transfer messages to the CN 5230 via GANC 5220. It is important to note that if the registration for the victim UE 5205 was attempted by the rogue FAP 5215 using the victim UE 5205 credentials (i.e. IMSI-2), the network based SAC would have rejected the registration request since the victim UE-2 5205 is not authorized Femtocell service over the specific rogue FAP 5215.
- Next, the FAP 5215 encapsulates the Location Update NAS PDU within a GA-CSR UL DIRECT TRANSFER message that is forwarded (in Step 14) to the GANC 5220 via the existing TCP connection of UE-1 5210. The GANC 5220 performs (in Step 15) a security check on the session identity. Since the identity carried in the Location Update messages i.e. IMSI-2 does not match any of the known identities for the session (IMSI-1 which is the identity used for registration and authorization or the TMSI learnt by the GANC 5220 as described in Step 8 above), the GANC 5220 is able to detect the attempted service theft.
- The GANC prevents the attempted service theft by deregistering the session for UE-1 5210. The GANC 5220 sends (in Step 16) a deregistration message to the FAP 5215 on the specific session (the authorized session for UE-1) on which the service theft was being attempted.
- 2. Service Theft Prevention—Approach 2
FIG. 53illustrates the Femtocell service theft prevention in some embodiments. Steps 1-15 are the same as Step 1-15 described in relation with FIG. 52above. Since the identity carried in the NAS PDU does not match any of the known identities for that session, GANC 5320 replaces the identity in the Location Update message with the original authorized identity for the specific session i.e., IMSI-2 is replace with IMSI-1 in the NAS PDU. The GANC establishes a SCCP connection to the CN 5330 and forwards (in Step 16) the modified Location Update request NAS PDU to the CN 5330 using the RANAP Initial UE message. The CN 5330 receives a service request with UE-1's identity in the request and will associate the request with UE-1 5310 subscriber data including billing, etc.
- Femtocell service access control (SAC) and accounting services are based on the S1 interface between the INC and one or more AAA servers. The S1 interface functions are defined in detail in the above mentioned U.S. application Ser. No. 11/349,025.
- The objective of Femtocell service access control is to provide operators with the tools to properly implement their Femtocell service plans based on real-time information from the subscriber and non real-time information provisioned within the operator's IT systems and service databases. Using service policies, the operator can implement a range of creative services and controls to be applied on a per individual subscriber basis, which results in the acceptance or rejection of any discrete Femtocell session registration request. Primarily, service policies are used to identify whether a subscriber's current request for access meets the conditions of the service plan to which they are subscribed.
- In some embodiments, Femtocell SAC encompasses the discovery, registration and redirection functions as well as enhanced service access control functions, such as restricting Femtocell service access based on the reported FAP MAC address or neighboring macro network UMTS cell information.
- A local SAC may be performed by the FAP for performance reasons (example: FAP may use local SAC for faster rejection of UEs which are not allowed access to either Femtocell services or not allowed access to Femtocell services via the specific FAP).
- Key elements of the service access control design approach are as follows:
- 1) There are two service access control configuration options:
- a) Basic service access control: The S1 (INC-AAA) interface is not deployed and a limited set of service access control capabilities is provided by the INC.
- i) The INC is responsible for the Femtocell discovery, registration and redirection functions.
- ii) The UMTS-to-Femtocell mapping logic and data is in the INC; i.e., this is used to support the discovery, registration and redirection functions and to assign service areas to specific FAPS.
- iii) There is no subscriber or FAP-specific service access control.
- b) Enhanced service access control: The S1 interface is deployed and the AAA provides expanded service access control features, including custom features per service provider requirements.
- i) The UMA discovery, registration and redirection functions remain on the INC.
- ii) The UMTS-to-Femtocell mapping logic and data remains in the INC.
- iii) The AAA supports interfaces to external database servers; e.g., via LDAPv3.
- iv) The details of these enhanced service access control functions are defined in the above mentioned U.S. application Ser. No. 11/349,025.
- 2) Enablement of the enhanced service access control support functions (i.e., the service access control functions of the S1 interface) is an INC configuration option; if enabled, the INC forwards attributes received in the discovery and registration requests to the AAA using RADIUS. This allows the AAA to (for example):
- a) Determine when UE registration attempts should be allowed or rejected (e.g., limiting service to a single FAP)
- b) Retrieve FAP location information from an external database and send the information to the INC.
- c) Provide a billing rate indicator to the INC that is incorporated in the UMTS-to-Femtocell SAI mapping process.
- d) Indicate that hand-in, hand-out, or both are enabled or disabled for the subscriber.
- A. UMTS-to-Femtocell Mapping
- The UMTS-to-Femtocell mapping processes include the following:
- 1) UMTS-INC Mapping (or “INC Selection”) serves the following functions:
- a) It allows an INC functioning as a “provisioning INC” to direct a mobile station to its designated “default INC”.
- b) It allows an INC functioning as a “default INC” to direct a mobile station to an appropriate “serving INC” (e.g., in case the FAP is outside its normal default INC coverage area).
- c) It allows the INC to determine if the UMTS coverage area is Femtocell-restricted and, if so, to deny service.
- 2) UMTS-Femtocell Service Area Mapping (or “Femtocell Service Area Selection”) serves the following functions:
- a) It allows an INC functioning as a “default or serving INC” to assign the Femtocell service area that shall be associated with the FAP registration (and all the UEs camped on that specific FAP). The service area can then be utilized for emergency call routing as described in the “Service area based routing” Subsection under the “EMERGENCY SERVICES” Section, above.
- B. Service Access Control (SAC) Examples
- The following example service access control are described in this section: (1) new FAP connects to GAN Femtocell network, (2) FAP connects to GAN Femtocell network (redirected connection), (3) FAP attempts to connect in a restricted UMTS coverage area, (4) authorized UE roves into an authorized FAP for Femtocell service, and (5) unauthorized UE roves into an authorized FAP for Femtocell service.
- 1. New FAP Connects to GAN Femtocell Network
FIG. 54illustrates SAC for new FAP connecting to Femtocell network in some embodiments. As shown, if the FAP 5405 has a provisioned or derived FQDN of the Provisioning SeGW, it performs (in Step 1) a DNS query (via the generic IP access network interface) to resolve the FQDN to an IP address. If the FAP has a provisioned IP address for the Provisioning SeGW, the DNS step is omitted.
- The DNS Server 5410 returns (in Step 2) a response including the IP Address of the Provisioning SeGW 5415. The FAP 5405 establishes (in Step 15) a secure tunnel to the Provisioning SeGW 5415 using IKEv2 and EAP-AKA or EAP-SIM.
- If the FAP has a provisioned or derived FQDN of the Provisioning INC, it performs (in Step 4) a DNS query (via the secure tunnel) to resolve the FQDN to an IP address. If the FAP has a provisioned IP address for the Provisioning INC, the DNS step (step 4) will be omitted. The DNS Server 5420 returns (in Step 5) a response including the IP Address of the Provisioning INC.
- Next, the FAP 5405 sets up (in Step 6) a TCP connection to a well-defined port on the Provisioning INC 5425. The FAP 5405 then queries (in Step 7) the Provisioning INC for the Default INC, using GA-RC DISCOVERY REQUEST. The message includes Cell Info and FAP Identity. For Cell Info, if the FAP detects macro network coverage, then it provides the detected UTRAN cell ID and the UTRAN LAI. If the FAP does not detect macro network coverage it provides the last LAI where the FAP successfully registered, along with an indicator stating which one it is. For FAP Identity, the message includes IMSI.
- The INC 5425 sends (in Step 8) a RADIUS Access-Request message to the AAA server 5435, including attributes derived from GA-CSR DISCOVERY REQUEST message. The AAA server 5435 queries (in Step 9) the Femtocell subscriber database 5440 for a record matching the IMSI of the FAP. The subscriber record is returned (in Step 9) to the AAA server. The AAA server verifies that FAP IMSI is authorized and FAP is allowed (based on AP-ID i.e., MAC address of the FAP).
- AAA server returns (in Step 10) selected Femtocell location information based on AP-ID and IMSI to the INC 5425 using the Access Accept message. The INC 5425 determines (in Step 11) the default security gateway and INC (e.g., INC #2 5430) using the UMTS-Femtocell mapping function (see UMTS-to-Femtocell Mapping Section, above). This is done so the FAP 5405 is directed to a “local” Default INC in the HPLMN to optimize network performance.
- The Provisioning INC 5425 returns (in Step 12) the default INC information in the GA-RC DISCOVERY ACCEPT message. The DISCOVERY ACCEPT message also indicates whether the INC and SeGW address provided shall or shall not be stored by the FAP. The FAP releases (in Step 13) the TCP connection and IPSec tunnel and proceeds to register on INC #2.
- The FAP performs (in Step 14) a private DNS query using the assigned Default INC FQDN. The private DNS server 5420 returns (in Step 15) the IP address of INC #2 5430. The FAP establishes (in Step 16) a TCP connection to INC #2 5430. The FAP sends (in Step 17) a GA-RC REGISTER REQUEST message to the INC.
- The INC sends (in Step 18) a RADIUS Access-Request message to the AAA server, including attributes derived from GA-RC REGISTER REQUEST message. The AAA server queries (in Step 19) the Femtocell subscriber database for a record matching the FAP IMSI. The subscriber record is returned (in Step 19) to the AAA server. The AAA server verifies that IMSI is authorized and FAP is allowed (based on AP-ID).
- Next, the AAA server returns (in Step 20) selected Femtocell service attributes to the INC. The INC determines (in Step 21) that it is the correct serving INC for the mobile current location using the UMTS-Femtocell mapping function. It also determines (in Step 21) the Femtocell service area to associate with the FAP using the UMTS-Femtocell mapping functions. The INC returns (in Step 22) a GA-RC REGISTER ACCEPT message to the MS
- 2. FAP Connects to GAN Femtocell Network (Redirected Connection)
FIG. 55illustrates SAC for the FAP getting redirected in Femtocell network in some embodiments. Steps 1 to 10 are the same steps as described in the “New FAP connects to GAN Femtocell network” Subsection, above. Next, the INC 5525 uses the UMTS-Femtocell mapping function to determine (in Step 11) that the FAP 5505 should be served by another INC.
- The INC 5525 sends (in Step 12) the new serving SeGW and INC FQDNs to the FAP 5505 in the GA-RC REGISTER REDIRECT message. The FAP releases (In Step 13) the TCP connection and IPSec tunnel and proceeds to register with the designated INC.
- 3. FAP Attempts to Connect in a Restricted UMTS Coverage Area
FIG. 56illustrates the SAC for FAP registering in restricted UMTS coverage area in some embodiments. As shown, Steps 1 to 10 are the same steps as described in the “New FAP connects to GAN Femtocell network” Subsection, above. Next, the INC 5625 uses the UMTS-Femtocell mapping function to determine (in Step 11) that the FAP 5605 is in an UMTS area that is Femtocell restricted (i.e., Femtocell access is not allowed in the area).
- The INC sends (in Step 12) a GA-RC REGISTER REJECT message to the FAP, including reject cause “Location not allowed”. The FAP releases (in Step 13) the TCP connection and IPSec tunnel and does not attempt to register again from the same UMTS coverage area until powered-off.
- 4. Authorized UE Roves into an Authorized FAP for Femtocell Service
- The sequence of events is same as described in UE Registration Section, above.
- 5. Unauthorized UE Roves into an Authorized FAP for Femtocell Service
- An unauthorized UE (unauthorized for Femtocell service over the specific FAP), described below.
FIG. 57illustrates the SAC for Unauthorized UE accessing authorized FAP in some embodiments.
- As shown, the UE 5705 establishes (in Step 1 a) a RRC connection with the FAP on which it camps. The UE starts (in Step 1 b) a Location Update procedure towards the CN. The FAP 5710 will intercept the Location Update request and attempts to register the UE with the associated Serving INC over the existing IPSec tunnel. Optionally, the FAP may request (in Step 1 c) the IMSI of the UE if the Location Update is done using the TMSI, since the initial registration for the UE must be done using the permanent identity i.e. the IMSI of the UE.
- The FAP sets up a separate TCP connection (for each UE) to a destination TCP port on the INC 5715. The INC destination TCP port is the same as that used for FAP registration. The FAP attempts to register the UE on the INC by transmitting (in Step 2) the GA-RC REGISTER REQUEST. The message includes (1) Registration Type which indicates that the registering device is a UE, (2) the UE Identity which is UE-IMSI, and (3) the FAP identity which is FAP-IMSI.
- Optionally, if the INC has been configured for Service Access Control (SAC) over S1 interface, the INC will (in Step 3), via AAA server 5420, authorize the UE 5405 using the information provided in the REGISTER REQUEST. The authorization logic on the AAA server also checks (in Step 4) to see if the UE is allowed Femtocell access using the specific FAP. The AAA SAC logic indicates that the registering UE is not authorized to access Femtocell service over the specific FAP.
- Next, the AAA 5720 sends (in Step 5) Access Reject (with reject cause equivalent to “UE not allowed on FAP”) to the INC 5715. The INC maps (in Step 6) the Access Reject to a GA-RC REGISTER REJECT message to the FAP indicating the reject cause.
- The FAP 5710 in turn sends (in Step 7) a Location Updating Reject to the UE 5705 with cause of “Location Area Not Allowed”. This will prevent the UE from attempting to camp on the specific FAP again. While some embodiments use “Location Area Not Allowed” as a mechanism for rejecting unauthorized UEs, other embodiments may use other appropriate UE rejection mechanisms.
FIG. 58conceptually illustrates a computer system with which some embodiments of the invention are implemented. The computer system 5800 includes a bus 5805, a processor 5810, a system memory 5815, a read-only memory 5820, a permanent storage device 5825, input devices 5830, and output devices 5835.
- The bus 5805 collectively represents all system, peripheral, and chipset buses that support communication among internal devices of the computer system 5800. For instance, the bus 5805 communicatively connects the processor 5810 with the read-only memory 5820, the system memory 5815, and the permanent storage device 5825.
- From these various memory units, the processor 5810 retrieves instructions to execute and data to process in order to execute the processes of the invention. In some embodiments the processor comprises a Field Programmable Gate Array (FPGA), an ASIC, or various other electronic components for executing instructions. The read-only-memory (ROM) 5820 stores static data and instructions that are needed by the processor 5810 and other modules of the computer system. The permanent storage device 5825, on the other hand, is a read-and-write memory device. This device is a non-volatile memory unit that stores instruction and data even when the computer system 5800 is off. Some embodiments of the invention use a mass-storage device (such as a magnetic or optical disk and its corresponding disk drive) as the permanent storage device 5825. Some embodiments use one or more removable storage devices (flash memory card or memory stick) as the permanent storage device.
- Like the permanent storage device 5825, the system memory 5815 is a read-and-write memory device. However, unlike storage device 58 5815, the permanent storage device 5825, the read-only memory 5820, or any combination of the three. For example, the various memory units include instructions for processing multimedia items in accordance with some embodiments. From these various memory units, the processor 5810 retrieves instructions to execute and data to process in order to execute the processes of some embodiments.
- The bus 5805 also connects to the input and output devices 5830 and 5835. The input devices enable the user to communicate information and select commands to the computer system. The input devices 5830 include alphanumeric keyboards and cursor-controllers. The output devices 5835 display images generated by the computer system. The output devices include printers and display devices, such as cathode ray tubes (CRT) or liquid crystal displays (LCD). Finally, as shown in
FIG. 58, bus 5805 also couples computer 5800 to a network 5865 through a network adapter (not shown). In this manner, the computer can be a part of a network of computers (such as a local area network (“LAN”), a wide area network (“WAN”), or an Intranet) or a network of networks (such as the Internet).
- It should be recognized by one of ordinary skill in the art that any or all of the components of computer system 5800 may be used in conjunction with the invention. For instance, some or all components of the computer system described with regards to
FIG. 58comprise some embodiments of the UE, FAP, GANC, and GGSN described above. Moreover, one of ordinary skill in the art will appreciate that any other system configuration may also be used in conjunction with the invention or components of the invention.
- The following is a list of definitions and abbreviations used:
- AAA Authentication, Authorization, and Accounting
- ACL Access Control List
- AES Advanced Encryption Standard
- AH Authentication Header (IPSec)
- AKA Authentication and Key Agreement
- ALI Automatic Location Identification
- AMS access Point Management System
- ANI Automatic Number Identification
- AP Access Point
- APN Access Point Name
- ATM Asynchronous Transfer Mode
- AuC Authentication Center
- CBC Cell Broadcast Center
- CBC Cipher Block Chaining
- CC Call Control
- CDR Call Detail Records
- CMDA Code Division Multiple Access
- CGI Cell Global Identification
- CgPN Calling Party Number
- CLIP Calling Line Presentation
- CK Cipher Key
- CM Connection Management
- CM-sub Connection Management sublayer
- CN Core Network
- CPE Customer Premises Equipment
- CRC Cyclic Redundancy Code
- CRDB Coordinate Routing Database
- CS Circuit Switched
- CTM Cellular Text telephone Modem, as specified in 3GPP 26.226
- DL Downlink
- DNS Domain Name System
- EAP Extensible Authentication protocol
- EAPOL EAP over LANs
- ECB Electronic Code Book (AES Mode)
- ELID Emergency Location Information Delivery
- E-OTD Enhanced Observed Time Difference
- ESN Emergency Services Number
- ESP Emergency Services Protocol or Encapsulating Security Payload (IPSec)
- ESRD Emergency Services Routing Digits
- ESRK Emergency Services Routing Key
- ETSI European Telecommunications Standards Institute
- FCAPS Fault, Configuration, Accounting, Performance, and Security management
- FAP Femtocell Access Point
- FCC US Federal Communications Commission
- FQDN Fully Qualified Domain Name
- GA-CSR Generic Access-Circuit Switched Resources
- GAN Generic Access Network
- GANC GAN Network Controller
- GA-PSR Generic Access-Packet Switched Resources
- GA-RC Generic Access-Resource Control
- GDP Generic Digits Parameter
- GERAN GSM EDGE Radio Access Network
- GGSN Gateway GPRS Support Node
- GMLC Gateway Mobile Location Center
- GMM/SM GPRS Mobility Management and Session Management
- GMSC Gateway MSC
- GPRS General Packet Radio Service
- GPS Global Positioning System
- GMM-sub GPRS Mobility Management sublayer
- GRR-sub GPRS Radio Resource sublayer in GSM
- GSM Global System for Mobile communications
- GSN GPRS Support Node
- GTP GPRS Tunnelling Protocol
- GTT GSM Global Text Telephony or SS7 Global Title Translation
- HLR Home Location Register
- HMAC Hashed Message Authentication Code
- HPLMN Home PLMN
- IAM Initial Address Message
- ICMP Internet Control Message Protocol
- IETF Internet Engineering Task Force
- IK Integrity Key
- IKEv2 Internet Key Exchange Version 2
- IMEI International Mobile station Equipment Identity
- IMSI International Mobile Subscriber Identity
- INC IP Network Controller
- IP Internet Protocol
- IPSec IP Security
- IPv4 Internet Protocol version 4
- IPv6 Internet Protocol version 6
- ISDN Integrated Services Digital Network
- ISP Internet Service Provider
- ISUP ISDN User Part
- Iu Interface UTRAN
- IV Initialization Vector
- LA Location Area
- LAC Location Area Code
- LAI Location Area Identity
- LAU Location Area Update
- LU Location Update
- LCS Location Service
- LEAP Lightweight EAP (same as EAP-Cisco)
- LLC Logical Link Control
- LLC-sub Logical Link Control sublayer
- LMSI Local Mobile Subscriber Identity
- LSB Least Significant Bit
- LSP Location Services Protocol
- M Mandatory
- M3UA MTP3 User Adaptation Layer
- MAC Media Access Control or Message Authentication Code (same as MIC)
- MAC Address Media Access Control Address
- MAC-I Message Authentication Code for Integrity
- MAP Mobile Application Part
- MDN Mobile Directory Number
- ME Mobile Equipment
- MIC Message Integrity Check (same as Message Authentication Code)
- MG or MGW Media Gateway
- MM Mobility Management
- MM-sub Mobility Management sublayer
- MPC Mobile Positioning Center
- MS Mobile Station
- MSB Most Significant Bit
- MSC Mobile Switching Center
- MSISDN Mobile Station International ISDN Number
- MSRN Mobile Station Roaming Number
- MTP1/2/3 Message Transfer Part Layer 1/2/3
- NAS Non Access Stratum
- NCAS Non Call Associated Signaling
- NDC National Destination Code
- NS Network Service
- NSAPI Network layer Service Indoor Base Station Identifier
- NSS Network SubSystem
- O Optional
- OCB Offset Code Book (AES Mode)
- OTP One Time Programmable
- pANI pseudo-ANI: Either the ESRD or ESRK
- PCS Personal Communications Services
- PCU Packet Control Unit
- PDCH Packet Data CHannel
- PDE Position Determining Entity
- PDN Packet Data Network
- PDP Packet Data Protocol, e.g., IP or X.25
- PDU Protocol Data Unit
- PEAP Protected EAP
- PKI Public Key Infrastructure
- PLMN Public Land Mobile Network
- POI Point of Interface
- PPF Paging Proceed Flag
- PPP Point-to-Point Protocol
- PSAP Public Safety Answering Point
- PSTN Public Switched Telephone Network
- PTM Point To Multipoint
- P-TMSI Packet TMSI
- PTP Point To Point
- PVC Permanent Virtual Circuit
- QoS Quality of Service
- R Required
- RA Routing Area
- RAB RANAP Assignment Request
- RAC Routing Area Code
- RADIUS Remote Authentication Dial-In User Service
- RAI Routing Area Identity
- RAN Radio Access Network
- RANAP Radio Access Network Application Part
- RFC Request for Comment (IETF Standard)
- RLC Radio Link Control
- RNC Radio Network Controller
- RR-sub Radio Resource Management sublayer
- RSN Robust Security Network
- RTCP Real Time Control Protocol
- RTP Real Time Protocol
- SAC Service Access Control
- SAC Service Area Code SC Scrambling Code
- SCCP Signaling Connection Control Part
- SDCCH Standalone Dedicated Control Channel
- SDU Service Data Unit
- SeGW GANC Security Gateway
- SGSN Serving GPRS Support Node
- SK Service Key
- SIM Subscriber Identity Module
- SM Session Management
- SMLC Serving Mobile Location Center
- SMS Short Message Service
- SM-AL Short Message Application Layer
- SM-TL Short Message Transfer Layer
- SM-RL Short Message Relay Layer
- SM-RP Short Message Relay Protocol
- SMR Short Message Relay (entity)
- SM-CP Short Message Control Protocol
- SMC Short Message Control (entity)
- SM-SC Short Message Service Centre
- SMS-GMSC Short Message Service Gateway MSC
- SMS-IWMSC Short Message Service Interworking MSC
- SNDCP SubNetwork Dependent Convergence Protocol
- SN-PDU SNDCP PDU
- S/R Selective Router
- SS Supplementary Service
- SSID Service Set Identifier (also known as “Network Name”)
- SSL Secure Socket Layer
- STA Station (802.11 client)
- TA Timing Advance
- TCAP Transaction Capabilities Application Part
- TCP Transmission Control Protocol
- TDOA Time Difference of Arrival
- TEID Terminal Endpoint Identifier
- TID Tunnel Identifier
- TKIP Temporal Key Integrity Protocol
- TLLI Temporary Logical Link Identity
- TLS Transport Layer Security
- TMSI Temporary Mobile Subscriber Identity
- TOA Time of Arrival
- TRAU Transcoder and Rate Adaptation Unit
- TTY Text telephone or teletypewriter
- UARFCN UMTS Absolute Radio Frequency Channel Number
- UDP User Datagram Protocol
- UE User Equipment
- UL Uplink
- UMA Unlicensed Mobile Access
- UMTS Universal Mobile Telecommunication System
- USIM UMTS Subscriber Identity Module/Universal Subscriber Identity Module
- USSD Unstructured Supplementary Service Data
- UTC Coordinated Universal Time
- UTRAN UMTS Terrestrial Radio Access Network
- VLR Visited Location Register
- VMSC Visited MSC
- VPLMN Visited Public Land Mobile Network
- VPN Virtual Private Network
- W-CDMA Wideband Code Division Multiple Access
- WEP Wired Equivalent Privacy
- WGS-84 World Geodetic System 1984
- WPA Wi-Fi Protected Access
- WZ1 World Zone. Moreover, while the invention has been described with reference to numerous specific details, one of ordinary skill in the art will recognize that the invention can be embodied in other specific forms without departing from the spirit of the invention.
-.
Claims (25)
1-20. (canceled)
21..
22. The method of
claim 21, wherein the set of identifications of the FAP comprises an international mobile subscriber identity (IMSI) of the FAP.
23. The method of
claim 21, wherein the set of identifications of the FAP comprises an access point identification (AP-ID) of the FAP.
24. The method of
claim 21, wherein the set of identifications of the FAP comprises a media access control (MAC) address of the FAP.
25. The method of
claim 21, wherein the set of identifications of the FAP comprises information identifying a service region of the second communication network.
26. The method of
claim 25, wherein when the FAP detects coverage of a particular cell of the second communication network, the information identifying the service region of the second communication network comprises a location area identification (LAI) and a cell identification of the particular cell of the second communication network.
27. The method of
claim 26,.
28. The method of
claim 21, wherein request is sent by the FAP to a network controller of the first communication network, wherein the network controller is for communicatively coupling the FAP with the second communication network.
29. A computer readable medium storing a computer for authorizing a Femtocell access point (FAP) of a first communication system, the FAP is for communicatively coupling a user equipment with a second communication network, the computer program comprising sets of instructions for:.
30. The computer readable medium of
claim 29, wherein the set of identifications of the FAP comprises an international mobile subscriber identity (IMSI) of the FAP.
31. The computer readable medium of
claim 29, wherein the set of identifications of the FAP comprises an access point identification (AP-ID) of the FAP.
32. The computer readable medium of
claim 29, wherein the set of identifications of the FAP comprises a media access control (MAC) address of the FAP.
33. The computer readable medium of
claim 29, wherein the set of identifications of the FAP comprises information identifying a service region of the second communication network.
34. The computer readable medium of
claim 29, wherein when the FAP detects coverage of a particular cell of the second communication network, the information identifying the service region of the second communication network comprises a location area identification (LAI) and a cell identification of the particular cell of the second communication network.
35. The computer readable medium of
claim 34,.
36. The computer readable medium of
claim 29, wherein request is sent by the FAP to a network controller of the first communication network, wherein the network controller is for communicatively coupling the FAP with the second communication network.
37.; and
b) rejecting said FAP request for registering with the first communication network when the FAP is in a service region of the second communication network where FAP access is not allowed.
38. The method of
claim 37, wherein said rejecting comprises sending a register reject message from to the FAP, the register reject message comprising a reject cause.
39. The method of
claim 38, wherein the reject cause is location not allowed.
40. A method of authorizing user equipment (UE) to use services of a first communication system comprising a Femtocell access point (FAP), the FAP is for communicatively coupling the UE with a second communication network, the method comprising:
a) receiving at a server of the first communication network a request for registering the UE with the first communication system, said request sent from the FAP to the said server; the request comprising an identification of the UE; and
b) rejecting the request when the UE is determined not to be authorized to register with the FAP.
41. The method of
claim 40, wherein the request comprises an international mobile subscriber identity (IMSI) of the UE.
42. The method of
claim 40, wherein the request comprises an international mobile subscriber identity (IMSI) of the FAP.
43. The method of
claim 40, wherein the request comprises an access point identification (AP-ID) of the FAP.
44. The method of
claim 40, wherein the request comprises a media access control (MAC) address of the FAP.
|
https://patents.google.com/patent/US20080305792A1/en
|
CC-MAIN-2021-04
|
refinedweb
| 40,533 | 50.67 |
public class PBEKeySpec extends Object implements KeySpec
The password can be viewed as some kind of raw key material, from which the encryption mechanism that uses it derives a cryptographic key.
Different PBE mechanisms may consume different bits of each password character. For example, the PBE mechanism defined in PKCS #5 looks at only the low order 8 bits of each character, whereas PKCS #12 looks at all 16 bits of each character.
You convert the password characters to a PBE key by creating an instance of the appropriate secret-key factory. For example, a secret-key factory for PKCS #5 will construct a PBE key from only the low order 8 bits of each password character, whereas a secret-key factory for PKCS #12 will take all 16 bits of each character.
Also note that this class stores passwords as char arrays instead of
String objects (which would seem more logical), because the
String class is immutable and there is no way to overwrite its
internal value when the password stored in it is no longer needed. Hence,
this class requests the password as a char array, so it can be overwritten
when done...
|
https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/PBEKeySpec.html
|
CC-MAIN-2021-25
|
refinedweb
| 195 | 52.12 |
Naming is hard
There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton
I'm a software developer for almost a decade now, and if I had to choose a single quote that was always true for me for that time it would be the one above.
Undoubtedly mapping real-world problems and implementing solutions for them must involve naming concepts in the first place and agreeing on vocabulary. It is not only a problem domain but also our experience that makes us better on calling classes, methods, variables, and all related concepts.
I was looking for a side project and came up with an idea of a web site where you put your roughly sketched name for a concept, and you will see a list of suggestions based on: – user query general language synonyms – and additionally (and more importantly) a list of synonyms based on already existing code from GitHub public repositories.
This way, you can find inspiration coming from other engineers' minds similar to yours (it does not mean they were right themselves, but at least you can get more options to choose from).
Additionally, I get inspired by those two papers: – Splitting source code identifiers using bidirectional LSTM Recurrent Neural Network – Public Git Archive: a Big Code dataset for all
Tech stack
This project would be an excellent opportunity to try something new and try to solve it with a pinch of data science and trying out some new framework/technology. I'm mainly a Ruby developer being tired of Ruby on Rails, so I've decided to give a try to Hanami. Data science part was utterly unknown to me as I've had no previous experience in that field, I had to do my research along the way.
Hanami
My goal was to have a one monolith app written in Hanami and nicely split as in-app modules (this approach was revised later on).
I liked the approach that your core logic is your app and is kept in the
lib/ directory. In contrast, any interface to that logic is an “app” (where it can be a web application, CLI interface, etc.) and is kept in
/apps directory. Such split provides an excellent separation of contexts and allows easy replacing and testing of each module.
First attempt
My main controller in Hanami web app looked like this:
module Web module Controllers module Search class Show MAX_RESULTS = 5 include Web::Action include ::AutoInject[ code: 'handlers.code', distance: 'handlers.distance', synonyms: 'handlers.synonyms', ] expose :synonyms, :res, :query params do required(:query).filled(:str?) end def call(params) if params.valid? && current_user @query = params.dig(:query) @synonyms = synonyms.find(query: @query).take(MAX_RESULTS) @synonyms.unshift(@query) responses = {} @res = @synonyms.take(MAX_RESULTS).map do |synonym| distance.filter( synonym: synonym, results: code.find( query: synonym.parameterize, user: current_user ) ) end.flatten.uniq else redirect_to routes.root_path end end end end end end
Using dependency injection makes it easy to define “processing” objects. As such, I describe an object that implements a processing function and does not mutate (or even does not have any state), so you can pass any object to it, call some function on it and return results. Given those objects can be reused between calls, we define them in a
Container file like so:
class Container extend Dry::Container::Mixin register('code.search_query_builder') do Code::SearchQueryBuilder.new end register('cache.synonyms') do Cache::Synonyms.new end ... end
The primary method for each controller in Hanami is defined in a
call method. In our case, we do a few actions there.
First, we try to find
@synonyms based on a user query. This process simply makes an API call to external service Big Huge Thesaurus by using the gem dtuite/dinosaurus. Not much to discuss there, we take results and proceed next with those.
Next thing is the main call chain in this controller:
@res = @synonyms.take(MAX_RESULTS).map do |synonym| distance.filter( synonym: synonym, results: code.find( query: synonym.parameterize, user: current_user ) ) end.flatten.uniq
Going from the inner block, we try to fetch code search results directly from GitHub using their search API endpoint.
After getting results from GitHub, we try to apply some logic by calculating Levenshtein distance to each returned token.
For each line from GitHub search results, we split them, cleanup with regexp, and decide whether to account given token in or not based on the distance calculated between
query (and its synonyms) and the token. If it is below the custom-defined threshold, then we show such a token. If not – we discard it. More on that later.
In each flow, I also try to utilize cache as much as possible, given all APIs have limitations (especially GitHub).
This is done with :
output = cache.find(query: synonym) return output if output && !output.empty?
and
cache.save(query: synonym, value: output)
cache as you may guess is an object in the
Container defined for each cache-able entity.
register('cache.synonyms') do Cache::Synonyms.new end register('cache.code') do Cache::Code.new end register('cache.distance') do Cache::Distance.new end
each of those classes inherits from the base class and defines each own cache prefix (added to differentiate cached keys in Redis):
module Cache class Distance < Base def prefix 'distance' end end end
and all the processing is kept in the base class as such:
module Cache class Base include ::AutoInject['clients.redis'] EXPIRATION_TIME = 60 * 24 * 7 # 1 week def find(query:) result = redis.get(cache_key(query)) return unless result JSON.parse(result, symbolize_names: true) end def save(query:, value:) redis.set(cache_key(query), value.to_json, ex: EXPIRATION_TIME) end def prefix fail NotImplementedError, "#{self.class}##{__method__} not implemented" end private def cache_key(query) "#{Cache::PATH_PREFIX}:#{prefix}:#{query.downcase.gsub(/\s/,'')}" end end end
Thanks to the dependency injection approach, all of those modules are easily replaceable and easy to unit test.
Ii liked that everything is kept in one app but, at the same time, organized in multiple modules. The way how Hanami structures directories/files and usage of
dry-rb gems makes my code modular and easy to work with.
The biggest issue with this approach were limits on GitHub APIs. Those run out quite fast (until we build up a decent cache, this app is not usable). Additionally, filtering results based on Levenshtein distance is not accurate enough, and I needed something better.
Data science
Bit more on Levenshtein distance
My first approach was to use something simple. I was looking for a clever way of comparing two words. Levenshtein distance seemed like a good candidate. After Wikipedia article:
... ...
I used optimized Ruby gem to calculate the value and tried to fine-tune the threshold to limit which words are worth showing as meaningful enough to a user.
require 'CGI' module Distance class Handler include ::AutoInject[ cache: 'cache.distance', ] THRESHOLD = 0.7 CLEANUP_REGEXP = /[^A-Za-z0-9\s_\:\.]/i def filter(synonym:, results:) output = cache.find(query: synonym) return output if output && !output.empty? output = results.flatten.map do |r| r.split(' ') end.flatten.map do |r| r.gsub(CLEANUP_REGEXP, '') end.map do |r| r if Levenshtein.normalized_distance(synonym, r, THRESHOLD) && !r.empty? end.compact.flatten cache.save(query: synonym, value: output) output end end end
This approach worked fine in terms of performance, but I have been missing one crucial thing – meaning. Levenshtein's distance between words does not rely on any model of the meaning of both words but rather compares them by checking how hard it is to change one word into another by calculating how many actions are required to do the job.
That was not enough, but fear not, there is another approach we can take.
Word2Vec
Text embedding was a real revelation for me. I highly recommend watching 15 minutes intro from Computerphile.
In short, word2vec maps each word in the text to a vector in multiple dimensions (how many depends on you), and based on vector distances from other words, it infers a word meaning. For someone who does not have a data science expertise, like myself, it is enough, for now, to say that this approach defines a word meaning by measuring vector distances between words in a given text window (how many words to look for and before the current term).
If you have an hour to spare, I also recommend watching this poetic, more in-depth explanation from Allison Parrish.
Or you can also read it in the form of gist as Jupyter Notebook for those who prefer reading and experimenting along.
Up to that point, I understood that searching GitHub directly via API would not scale and would take too much time on each request to be usable. Also, it is very easy to pass API limit thresholds, which required users to wait for the 60 seconds before trying again.
I knew I need a data model and a lot of code to train it.
My initial take was on the Public Git Archive, as I already knew about those from the papers I've read (the ones I've linked in the beginning). Unfortunately, datasets from the project's repo are no longer available. I was planning to use the already cleaned identifiers dataset as this is precisely what I need from those public repositories. I've tried to reach out to authors, and there is a chance they will be able to upload them and share them in the next few days.
Handling significant amounts of data
Luckily Google exposes a considerable amount of public GitHub repositories in its BigQuery analytics application.
I was able to easily extract ~1GB of data (public source code) with this self-explanatory SQL query.
WITH ruby_repos AS ( SELECT r.repo_name AS repo_name, r.watch_count AS watches FROM `airy-shadow-177520.gh.languages` l, UNNEST(LANGUAGE) JOIN `airy-shadow-177520.gh.sample_repos` r ON r.repo_name = l.repo_name WHERE name IN ('Ruby', 'Javascript', 'Java', 'Python')) SELECT content FROM `airy-shadow-177520.gh.sample_contents` c WHERE c.sample_repo_name IN ( SELECT repo_name FROM ruby_repos ORDER BY watches DESC LIMIT 3000 ) AND content IS NOT NULL
OK, I got data, I know what (roughly) I would like to do with it, now the question was: how? I already knew Jupyter Notebooks, and those are perfect for any analysis, reporting, and debugging tasks. Python is also well known nowadays from its wide variety of data science libraries and that it is a de facto language of choice among data scientists equally with R. Choice was obvious.
I've used a Python library called gensim which advertises as
the most robust, efficient and hassle-free piece of software to realize unsupervised semantic modelling from plain text.
I was able to use it easily in Jupyter Notebook and train my model. It was also trivially simple to save the trained model to a file for reuse.
Deploying model
I do have my model. Yay! After experimenting and playing with it in the notebook, the time came to deploy it somewhere and expose it to be used by my Hanami app.
Before all of that, it would also be useful to track model versions somehow. That was an easy part as I've already known about GitHub LFS (Large File Storage), which makes versioning of huge/binary files an easy peasy. I've added my model files to a new GitHub repo (separate from the Hanami app as I thought it would be easier to deploy those two separately).
The next step was to use a simple web server for model REST API. In the Python world Flask seemed like an obvious choice.
My first take was just that.
from gensim.models import Word2Vec from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/') def word2vec(): model = Word2Vec.load("model/model.wv") w = request.args['word'] return jsonify(model.most_similar(positive=[w], topn=15)) if __name__ == '__main__': app.run(debug=True)
Can you see an issue here? If not, think how loading to RAM a few hundred MB model on each request could make cloud server instance to die.
So instead of loading the same model multiple times (on each request basically), I've decided that separating the model and Flask part will be the best approach. This way, I can have a daemonized model, loaded once, and responding to queries. Whenever it dies, I also have monit watching for PID changes and reviving the model.
[email protected]:~# cat /etc/systemd/system/model_receiver.service [Unit] Description=Model Findn Receiver Daemon [Service] Type=simple ExecStart=/bin/bash -c 'cd /var/www/model.findn.name/html/ && source venv/bin/activate && ./receiver.py' WorkingDirectory=/var/www/model.findn.name/html/ Restart=always RestartSec=10 [Install] WantedBy=sysinit.target
check program receiver with path "/bin/systemctl --quiet is-active model_receiver" start program = "/bin/systemctl start model_receiver" stop program = "/bin/systemctl stop model_receiver" if status != 0 then restart
As always, with two processes, you would like to allow some kind of communication between them.
My first take was to use FIFO files, but this approach did not work out on multiple API requests made to the Flask app. I did not want to spend too much time on debugging, so I decided to use something more reliable. My choice was ØMQ for which (guess what) there is also an excellent Python library.
Equipped with all those tools I've managed to prepare, firstly Flask API app
from flask import Flask, jsonify, request import zmq app = Flask(__name__) @app.route('/') def word2vec(): w = request.args['word'] if w is None: return context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://127.0.0.1:5555') socket.send_string(w) resp = socket.recv_pyobj() try: return jsonify(resp) except Exception as e: return jsonify([]) @app.errorhandler(404) def pageNotFound(error): return "page not found" @app.errorhandler(500) def raiseError(error): return error if __name__ == '__main__': app.run(debug=True)
as well as daemonized model receiver
#!/usr/bin/env python3 import zmq import os from gensim.models import Word2Vec model = Word2Vec.load("model/model.wv") context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('tcp://127.0.0.1:5555') while True: msg = socket.recv() try: resp = model.wv.most_similar(positive=[msg.decode('utf-8')], topn=7) except Exception as e: resp = [] socket.send_pyobj(resp)
The final result can be seen here:
Summary and next steps
This side project was a lot of fun, mostly thanks to the data science part of it. I have not written any low-level algorithmic code to train the model (as I've used already existing library). Nevertheless, it was still a great experience to see how those algorithms can “learn” about the meaning of words in a human sense only by using a small subset of data. And how such a model can be deployed on a hosted server outside the Jupyter Notebook environment.
The next step probably would involve improvements to the model itself and experiment with different data sets.
Overall, it was a successful side project. Fun for sure!
|
https://ignacy.co/naming-is-hard
|
CC-MAIN-2022-05
|
refinedweb
| 2,509 | 57.77 |
The purpose of this exercise is to access the data to & from Excel to SAP HANA. This will demonstrate the bidirectional transfer of the data without using import/export options in SAP HANA Studio.
Live data can be viewed whenever we open the excel file.
STEP 1: Creating a DB table in SAP HANA:
I have created a simple table with 2 field using SAP RIVER Code. Alternately we can also use the table which is created by .HDBTABLE file
@OData
application Rivermohas98.HelloExcelApp{
export entity exceldata {
key element employ: String(10);
element skill: String(10);
}
}
STEP 2: Creating .XSODATA:
I haven’t used the OData created by SAP RIVER. The Excel file has difficulty to read the OData created by SAP RIVER. So I have alternately created an OData using .XSODATA with name rivertab.xsodata
service namespace “rivermohas98.services” {
“Rivermohas98″.”Rivermohas98::HelloExcelApp.exceldata”
as “Excel”;
}
Testing of OData:
I have inserted a record in the table using Insert SQL.
STEP 3: Retrieve SAP HANA DB from Excel:
Now I have an OData which can be accessed. I have chosen an .XSLM file, considering Macros/VBA script can be saved in .XSLM files.
Calling Odata using Power Query:
- My next step is to access the OData in this Excel File. I am sure there must be multiple ways to access it, I tried using the Excel Add-in PowerPivot.
2. A pop-up will be displayed for the OData Feed. I have entered the OData which I have created using .XSODATA
3. Query Editor will be opened. Check the feed and Click on Apply & Close
4. You will promted for User ID and Password. Alternately you can set the Credentials here.
5. The below screenshot will help to set the OData Refresh settings. Also you can see the data has been retrieved from SAP HANA DB.
STEP 4:Sending Data from Excel to SAP HANA DB:
Now lets see how to post the data. Data will be posted to SAP by Python code.
- Installation of Python and XLRD library:
I have installed Python33. The next important step is to install XLRD. XLRD is a library to read .XSLS, .XSLM files in python. I have downloaded the package “xlrd-0.9.3.tar.gz”.
Once downloaded, Unzip, go to Command line (RUN->CMD), Navigate to the folder and run “python setup.py install” in command line. Follow other sources to install python and xlrd.
2. Code in VBA:
A code has been written to trigger the Python File in Excel. Go to ALT+F11 and use the below code to trigger your Python file.
Write your code in Worksheet, this will have multiple options when to run this code. I want to trigger the Python code on Saving of the Excel file.
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Dim pyPrgm As String, pyScript As String
pyPrgm = “C:\Python33\python.exe “
pyScript = “C:\pyt\LoadExcel.py”
Call Shell(pyPrgm & pyScript, vbMaximizedFocus)
End Sub
Explanation for the Highlighted in RED
pyPrgm = “C:\Python33\python.exe ” -> This is the path where Python is installed.
pyScript = “C:\pyt\LoadExcel.py” -> This is where my python code stored to trigger OData.
3. Python Code:
Python code is in LoadExcel.py stored in the above mentioned path.
#! /usr/bin/python
# All import files may not require
import os
import requests
import json
import csv
import sys
import xlrd
# OData URL. I am using the OData Created by SAP RIVER. Give the full address of the server.
appURL = ‘………..8008/Rivermohas98/odata/Rivermohas98.HelloExcelApp‘
# Credentials
auth = ‘userid’,’password’
s = requests.Session()
- s.headers.update({‘Connection’: ‘keep-alive’})
headers = {‘X-CSRF-TOKEN’: ‘Fetch’}
r = s.get(url=appURL, headers=headers, auth=auth)
CSRFtoken = r.headers[‘x-csrf-token’]
print(“CSRFToken: ” + CSRFtoken)
headers = {‘X-CSRF-TOKEN’: CSRFtoken}
url = appURL + “/exceldata”
# Your file has to be in this location. This is the path which we have given in Excel (VBA code). Full path is required
workbook = xlrd.open_workbook(‘C:\pyt\employ.xlsm’)
# Give the worksheet name
worksheet = workbook.sheet_by_name(‘Sheet1’)
num_rows = worksheet.nrows – 1
num_cells = worksheet.ncols – 1
curr_row = 0
while curr_row < num_rows:
curr_row += 1
row = worksheet.row(curr_row)
print( row[0], row[1])
print( row[0], row[1])
data = ‘{“employ”: ” ‘ + str(row[0].value) + ‘ “, “skill”: ” ‘ + str(row[1].value) + ‘ ” }’
# print(“Check Data: ” + data)
r = s.post(url, data=data, headers=headers)
4. Test your Python Code:
You can test your Python Code from command line. Below screenshot is for reference.
STEP 5: Post the data to SAP HANA DB from Excel:
1. Now add an entry in Excel:
2. Check the result in SAP HANA:
Now we have two records.
STEP 6: Post the data to SAP HANA DB from Excel:
Now create one more record in SAP HANA table and check whether it is updating the Excel. As Similar to Step 2 and check the result in Excel.
Currently I have only used OData ‘POST’ operation. I believe further operations can be used like PUT & DELETE or triggering the Python Code for GET operation instead of using Excel OData feeds.
Thanks to Philip MUGGLESTONE for his video on Python @ SAP HANA Academy
Thanks for reading.
good to know Shahid ! thanks for the info!
|
https://blogs.sap.com/2014/07/22/sap-hana-excel-bidirectional-datasync-data-using-python-odata/
|
CC-MAIN-2019-35
|
refinedweb
| 864 | 69.58 |
Talk:Proposed features/Airspace
Contents
Source
This proposal is based on an idea from the german namespace DE:Luftraum and I modified it to start the discussion on a more international basis as aviation can never be locally. It might be neccessary to add some things to its definition, to make it more comfortable for other countries. TobiBS 10:13, 29 May 2009 (UTC)
Temporary Airspaces
Some Airspaces do not have the same definition 24/7. It might therefore be interesting to define its time of activity, but I couldn't figure out an easy concept for this, feel free to develop one and propose it. TobiBS 10:13, 29 May 2009 (UTC).
- Temporary information needs to be checked by the pilot during pre flight planning. This can be found in AIP's, NOTAMS and AIC's. Permanent airspace conditions should be refreshed in this map (if possible by copyright laws).—Preceding unsigned comment added by Quintsegers (talk • contribs) 10:20, 11 February 2010 (UTC)
- I did not mean temporary airspaces as for airshows or similar, what I meant where airspaces that are there all the time but are not active all the time (HX). I do not see any copyright concerns, as the data is published by the state, it is only neccessary to take the base data, not any reassambled data from Jeppesen or other data providers. TobiBS 11:01, 11 February 2010 (UTC
- An even more striking example is the CTR of Liège EBLG, which is class D when controlled by the military (more or less business hours) and class C at the other times, when civilian Belgocontrol takes over. For the rest I fully agree with TobiBS that these data are, by nature and by law, public - even if some national authorities limit access to them. Jan olieslagers 10:58, 21 September 2010 (BST)
Unmappable and unusable
Airspace cannot be mapped traditionally (i.e. by using yuor GPS and looking at signs). The only way to map it is to import it from posibly copyrighted sources (explain where you want to extract airspace info from if not copyrighted maps?). Also, there is no way to verify whether it is still correct or outdated. Airspace in OSM would be dangerous and possibly even illegal to use for aviation purposes. I really can't see the reason behind it. If you need to have it, put it in a separate database. Airspace is generally not realted to any features on the ground anyway, so it will be completely disconnected from the rest of our data. --Frederik Ramm 06:46, 7 June 2009 (UTC)
- A lot of things that can not be mapped with a GPS are already in the database, or does your GPS display the inhabitants of a city? What about state borders, they are sometimes only defined by law and not by traditional landmarks. At latest if it comes to reporting points which would be the next proposal after this one, they are always defined by popular landmarks, like street crossings, towers, etc.
- Regarding the sources for airspaces, they are defined in the AIP, not only on the maps, but also in textual description. I think you can't claim a copyright for coordinates that define a rectangle or something like that if they are in textual form. I don't think it is possibly illegal, but it is illegal to use other maps than official ones for real aviation, but there is still a wide use for OSM aviation maps, because if you want to show your route to friends or if you are doing flight planning for simulated aviation or similar, you have to draw the maps on your own, or you have to use non free maps, therefore there is use for it and it is clear and obvious that no one should use these maps for the purpose of flight planning or actual flying, look at fl95.de for example, there is not only a map, but a complete flight planner and they are also stating that it is not legal to use the site as a basic flight planning.
- As I understand, there is a consens of leaving the data in one database, the reason is simple, if the copyright of any database changes you are maybe unable to combine the data on one day, if the data is in the same database it will always be easier to keep track of it.
- Closing I would like to remind that it is not forbidden to tag thins that are not Map Features and as people will create and tag it, I would like to recoomend to argue about the how, not the if. These data hurts nobody and can also be interesting for none aviation related persons who would like to know if there house of interest is located in a military low flying area or similar. TobiBS 09:23, 7 June 2009 (UTC)
Changed class=* to airspace=*
I read that class=* is an obsolete parameter and that the concept follows another standard, therefore I changed it to airspace=*
Good idea
I am currently building an aircraft and am a current airline pilot with over 30 years experience. One issue we have in the United Kingdom is infringement of controlled airspace by aircraft not equipped with either transponders or GPS, who rely on traditional map reading skills. These infringements cause massive problems for ATC controllers. What I would propose is having the airspace available on a standard Garmin car GPS so that users would be warned of approaching controlled airspace cheaply. This is something that OSM would be ideal for.
- I was looking for some kind of airspace data in the past. So I totally agree with the owner and especially with the guy from GB. But I am missing a tag which stores the frequency you have to call to receive permission to cross an airspace.
- Airspace data can be downloaded for free in the openair format. I have to check the license but I guess, you can use it for free. In order to convert the data I have written a small engine to convert it. Kaymen 18:31, 4 September 2009 (UTC)
- I would propose some more attribute like controlzone = (yes|no) and temporary = (yes|no). The last one is for airspaces, which are not active H24 (HX). Frequency would be another nice attribute.
- I finished writing the converter and will upload all airspaces in the north of germany in the next weeks. This morning I received the answer from the DAEC, which makes the german airspaces available for the public (openair format).
- Die Segelflugkommission des Deutschen Aero Club stellt die Daten, die sie käuflich von der DFS erwirbt, den Luftsportlern zur Verfügung. Einerseits sind sie die Grundlage für die Wettkampfgebiete der Segelflugmeisterschaften aber auch ein hervorragendes Tool sich ständig mit den aktuellen Luftraumdaten der Bundesrepublik Deutschland auf allen möglichen Plattformen zu versorgen. Ein Copyright wird mit Absicht nicht eingetragen, da die möglichst weite Verteilung eines der Ziele ist. (Günter Betram from DAEC).
- Kaymen 11:48, 7 September 2009 (UTC)
- Great to see that others like the idea, too. Regarding the ideas of controlzone and temporary: I intended to do this type of classification in the type=* field, but as it was only a proposal, we have to find the best solution. Regarding the frequency their is a problem, because it is not always the same and can be also dependent from time.
- If you have done the conversion and added the data, please inform me, so that I can render a bigger part of northern Germany for the OpenAviation Map. TobiBS 16:06, 9 September 2009 (UTC)
Why camelCase?
Why are the lowerLimit, lowerLimitType, upperLimit and upperLimitType written as camelcase and not in the more widely used form with underscores and colon, eg. lower_limit, lower_limit:type, upper_limit, upper_limit:type? Daeron 09:59, 24 September 2009 (UTC)
Unit of measurement is needed on height limits
I propose two more attributes:
- upper_unit=ft/m/fl/etc..
- lower_unit=ft/m/fl/etc..
This property does not make sense when we're talking about flight levels (or maybe it then would be fl?). I'm not proposing this because i know of any airspace that's defined in meters, it's more about being compitable with the eventual future or other systems. Lysgaard 10:17, 5 January 2011 (UTC)
- Another way to do it would be to have the unit as a suffix in the lower_limit and upper_limit tags. would then be like lower_limit=4000ft.
Conversion of OpenAir files
Today some airspace information are provided on some web sites () using the OpenAir format ... A good idea would be to try to map (and to develop an automatic tool) to convert OpenAir into direct OSM XML data....
OSM database or separate database
Just a word so that everyone is aware of what has been told elswhere : Airspaces shall not be mapped in OSM main database.
(Message above is not my opinion, just factual information) -- Djam 18:41, 31 October 2011 (UTC)
Civilian / Military airspaces
Is A/B/C/D/E/F/G/restricted/prohibited/dangerous classification sufficient to cover military zones ? -- Djam 18:46, 31 October 2011 (UTC)
|
https://wiki.openstreetmap.org/wiki/Talk:Proposed_features/Airspace
|
CC-MAIN-2018-17
|
refinedweb
| 1,536 | 65.96 |
I'm working on Hotel management application [desktop] and I noticed, the date changing time hotels system is not 00:00 am , it's between 1AM and 6AM so reservations and room status etc. should be stay until audit time.When the user make audit the new day will start.
That's why I need to create a method that stop date change at midnight and return new date when audit button clicked. Briefly I have to create central system for date.
As a result; when I use this date in all classes every methods will work synchronously[blockade, reservations, check in, check out etc.] but I couldn't find good way to do this.
I'm thinking around some code like this :
package com.coder.hms.utils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class CustomDateFactory {
private Date date;
private Calendar calendar;
private SimpleDateFormat sdf;
public CustomDateFactory() {
//for formatting date as desired
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
public void setValidDateUntilAudit(int counter) {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
//get hour and minute from calendar
calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int min = calendar.get(Calendar.MINUTE);
int sec = calendar.get(Calendar.SECOND);
//check if the field value equals -1
if (counter == -1) {
//and the time at 00:00
if (hour == 0 && min == 0 && sec == 2) {
//bring the date one day back
calendar.add(Calendar.DATE, counter);
date = calendar.getTime();
}
} else {
date = new Date();
}
}
};
timer.schedule(task, 0, 100);
}
public Date getDate() {
final String today = sdf.format(date);
final LocalDate ld = LocalDate.parse(today);
date = java.sql.Date.valueOf(ld);
return date;
}
}
public class DateFactoryTest {
private LocalDate currentDate;
private LocalDateTime localDateTime;
public DateFactoryTest() {
currentDate = LocalDate.now();
localDateTime = LocalDateTime.now();
}
private void setTheDate(boolean isAuditted) {
if (localDateTime.getHour() <= 6 && isAuditted == false) {
currentDate.minusDays(1);
} else if (localDateTime.getHour() > 6 && isAuditted == true) {
ImageIcon icon = new ImageIcon(getClass().getResource("/com/coder/hms/icons/dialogPane_question.png"));
int choosedVal = JOptionPane.showOptionDialog(null, "You're doing early audit, are you sure about this?",
"Approving question", 0, JOptionPane.YES_NO_OPTION, icon, null, null);
if (choosedVal == JOptionPane.YES_OPTION) {
isAuditted = false;
}
}
}
private LocalDate getDate() {
return currentDate;
}
}
Avoid the troublesome old date-time classes such as
java.util.Date. Now supplanted by the java.time classes. Among those obsolete classes is
java.sql.Date – you may have to use it if your JDBC driver is not yet updated for JDBC 4.2 and later, but if so, minimize its use and do not use these objects in your business logic.
As other people commented, do not hack the meaning of a date. If a “Hotel Day” really runs from 6 AM to 6 AM, then create a class to represent that. Define a member for the official date, of type
LocalDate. Define also members for the start and stop, of type
LocalDateTime, where the stop is
plusDays( 1 ).
Define a pair of getter methods each taking a
ZoneId argument, and returning a
ZonedDateTime, each for the true exact moment when the hotel-day starts and stops. A
LocalDateTime is not an actual moment, and has no meaning until you specify a time zone. Anomalies such as Daylight Saving Time (DST) mean the 6 AM start or stop time might really be 5 AM or 7 AM or 6:15 AM on a particular date.
public startAtZone( ZoneId z ) { ZonedDateTime zdt = this.startLocalDateTime.atZone( z ) ; return zdt ; }
Calculate the span of time as a
Duration. Call the
to… methods to get a total number of seconds, milliseconds, or nanoseconds.
Duration d = Duration.between( ZonedDateTime.now( z ) , myHotelDay.stopAtZone( z ) ) ;
Note that the best approach to defining spans of time is generally the Half-Open approach where the beginning is inclusive and the ending is exclusive. This means your hotel-day starting at 6 AM runs up to, but does not include, the following 6 AM. That means
6 AM to 6 AM, so no bothering to determine 05:59:59.999 or 05:59:59.999999 or 05:59:59.999999999. Search with
>= && < logic, and do not use SQL
BETWEEN.
By the way,
Timer is legacy now. Read about the Executors framework, and search Stack Overflow.
By the way, the format you used,
yyyy-MM-dd, is defined by the ISO 8601 standard. The java.time classes use those standard formats by default when parsing/generating strings.
|
https://codedump.io/share/lYSdOkdbLqxm/1/how-to-stop-date-changing-at-0000-o39clock
|
CC-MAIN-2019-35
|
refinedweb
| 745 | 52.26 |
2007 was another slow year for XML. However, several important specifications did reach 1.0, and XML continued to gain traction in publishing, both Web and traditional. Most important, the slow leak in the Web services ship caused by its collision with the REST iceberg turned into a gusher, and the whole vessel began to sink beneath the waves. The tip of this Titanic-sinking iceberg was POX, plain old XML documents sent over standard HTTP without any schemas or specs to get in anyone's way. (Some people saw the iceberg approaching years ago, but as Roy Fielding said, "the industry still insisted on proving that for themselves.")
REST isn't the only technology that hides 90% of its power below the surface. The full power of XML has yet to be explored. The Atom Publishing Protocol (APP) and XQuery both reached 1.0 this year, and the impact of both is just beginning to be felt.
Despite having survived numerous challenges from pretenders to the throne over the last 10 years (YAML, SML, S-expressions, and other also-rans), XML saw its most serious challenge yet in 2007 with the increasing popularity of JSON. JSON usage hasn't yet peaked and seems likely to continue to increase in the next year despite JSON's limited applicability, security problems, and poorly designed application programming interfaces (APIs).
XQuery's been a "next year" technology for half a decade now, but in January the promise was finally realized with the official publication of XQuery 1.0. Several pure XML databases have already implemented it, including Mark Logic, eXist, Sedna, and Berkeley DB XML. You can also find it in hybrid databases including IBM® DB2® 9 and Oracle 10g. XQuery is also available in some stand-alone products including Michael Kay's Saxon and DataDirect XQuery.
But the job isn't finished. XQuery is only a quarter of the solution. In CRUD terms, XQuery is Read without Create, Update, or Delete. These necessary features have to be filled in with proprietary extensions. This means you can't easily move an application or database from one implementation to the next. More importantly, you can't teach developers a standard syntax, and you can't easily hire an experienced Mark Logic programmer to work on a DB2 9 application. (Programs rarely shift between platforms, but developers often do.) XQuery needs an update (and create and delete) facility. The World Wide Web Consortium (W3C) issued a last-call draft of XQuery Update Facility 1.0 in August, and vendors are starting to implement it. If the XML community is lucky, 2008 will finally see this last critical piece exit last call and move on to final release.
The XQuery working group also published the first batch of XQuery 1.1 requirements this year. Some of the most significant possible new features include exception handling, extension functions, function pointers, and/or lambda expressions. With any luck, these will take only another five or six years to finish. However, it's better to get started now before XQuery adoption really takes off and any spec changes become multidecade endeavors as was the case for SQL, Fortran, and C.
Although XQuery is a fairly complete programming language—it can completely replace PHP, static HTML, and essentially any other Web framework—you'll probably need to integrate it with programs written in traditional languages for the foreseeable future. Thus it's good that the XQuery API for Java (XQJ) advanced to proposed final draft in the Java Community Process this year. Think of this as JDBC for XQuery. XQJ is already supported by Saxon 9 and Data Direct XQuery 3.0, and more vendors are likely to follow once the finished spec is released next year.
In this shortest and coldest month of the year, everyone stayed home and not a lot happened. There were new releases of Saxon, TagSoup, and WebCGM. (What's WebCGM, you ask? Exactly.)
We did get the last-call working draft of XForms 1.1 this month, which added some critical new features including support for PUT and DELETE submissions. But the 10 remaining months in the year weren't quite long enough to push XForms forward to final recommendation. Candidate recommendation in November was as far as XForms 1.1 got. Maybe next year.
Most significant XForms vendors released updated versions of their products at various points throughout the year, including FormsPlayer, Chiba, Orbeon, and the Mozilla XForms extension. Unfortunately, the holy grail of XForms support built right into a major browser remained elusive.
The W3C was formed more than a decade ago as a direct response to the failure of the Internet Engineering Task Force (IETF) HTML 2.0 effort. Given that history, it's a little shocking to realize that by 2006 the W3C had effectively abandoned HTML. Through the millennium to date, they were so focused on XML and the Semantic Web that they pretty much forgot about the one technology they were formed to support. Thus, in 2004 some Web designers and browser vendors got together as the Web Hypertext Application Technology Working Group (WhatWG), picked up the ball the W3C had dropped, and started to run away with it.
It took a couple of years, but in March the W3C finally noticed they were about to be scored on. They rechartered their own HTML working group and started playing catch-up. The two teams mostly agreed to share the ball going forward, but the WhatWG is still playing quarterback and driving the ball down the field.
Despite the brouhaha, not much running HTML 5 code was produced in 2007. Specification development focused on Web video, SQL APIs, and parsing arcana. Whether any of this will ever be implemented in Web browsers that normal people use remains an open question. Personally, I question the wisdom of spending months developing an in-browser SQL API precisely at the time native XML databases are warming up off field (and I promise that's my last football metaphor in this article, or you can take away my referee's whistle).
Despite early hype that XML would bring semantics to the Web and enable browsers to
understand what they were displaying, XML was really always about syntax, not semantics. The
entire XML 1.0 specification has only two marginally semantic attributes:
xml:space and
xml:lang (and I'm not sure about
xml:space). Meaning, for the most part, comes from the application that
processes the XML document, not the document itself. That's largely been true of
subsequent specs in the XML family, including namespaces, the XML Infoset, XSLT, and XPath.
But in April, the W3C expanded on the
xml:lang attribute in a
big way by releasing the Internationalization Tag Set (ITS) 1.0. This recommendation defines
standard attributes for identifying directionality, translatability, ruby text,
and other common
aspects of document localization and internationalization that can be shared across many
different vocabularies. For example, in the DocBook article shown in Listing 1, the
its:translate attribute indicates that the author element shouldn't be translated, and
the
its:dir attribute says that the whole document uses left-to-right
text.
Listing 1. A DocBook article with extra ITS markup
This spec didn't get a lot of attention, but it's useful for anyone who publishes in a multilingual environment (and these days, that's nearly everyone).
In April, The W3C Internationalization Activity also posted the finished version of Internationalization Best Practices: Specifying Language in XHTML & HTML Content. This advice is summarized in 16 "best practices" that I extract here:
- Best Practice 1: Always declare the default language for text in the page using attributes on the html tag, unless the document contains content aimed at speakers of more than one language.
- Best Practice 2: Where a document contains content aimed at speakers of more than one language, decide whether you want to declare one language in the html tag, or leave the languages undefined until later.
- Best Practice 3: Where a document contains content aimed at speakers of more than one language, try to divide the document linguistically at the highest possible level, and declare the appropriate language for each of those divisions.
- Best Practice 4: Use the lang and/or xml:lang attributes around text to indicate any changes in language.
- Best Practice 5: For HTML use the lang attribute only, for XHTML 1.0 served as text/html use the lang and xml:lang attributes, and for XHTML served as XML use the xml:lang attribute only.
- Best Practice 6: Use language attributes rather than HTTP or meta elements to declare the default language for text processing.
- Best Practice 7: Do not declare the default language of a document in the body element, use the html element.
- Best Practice 8: If the text in attribute values and element content is in different languages, consider using a nested approach.
- Best Practice 9: Consider using a Content-Language declaration in the HTTP header or a meta tag to declare metadata about the languages of the intended audience of a document.
- Best Practice 10: Where a document contains content aimed at speakers of more than one language, use Content-Language with a comma-separated list of language tags.
- Best Practice 11: Follow the guidelines in the IETF's BCP 47 for language attribute values.
- Best Practice 12: Use the shortest possible language tag values.
- Best Practice 13: Where possible, use the codes zh-Hans and zh-Hant to refer to Simplified and Traditional Chinese, respectively.
- Best Practice 14: When pointing to a resource in another language, consider the pros and cons of indicating the language of the target document.
- Best Practice 15: If you want to indicate that the target document of an a element is in another language, consider the pros and cons of using hreflang with CSS.
- Best Practice 16: Do not use flag icons to indicate languages.
MathML was one of the first XML applications, but sadly it has seen limited practical uptake. Nonetheless, the W3C Math Working Group hasn't given up, and in late April they released the first draft of MathML 3. (Yes, I know this is supposed to be the May section, but not much XML news happened in May.)
The most important feature in version 3 is support for elementary school math notation. After all, first graders outnumber mathematics PhDs about 100,000 to 1. MathML 3 also adds support for bidirectional layout and improves linebreaking and positioning for improved typesetting. Finally, the spec has been rewritten with clarity in mind. One can only hope the third time is the charm. After all, math is what the Web was invented for.
In June, the OpenOffice Project released version 2.2. of OpenOffice, a cross-platform office suite that saves all its files as zipped XML in the international standard OpenDoc format. This was mostly a bug-fix release, and it wouldn't normally merit mention in a year-in-review article. But the real news was that for the first time, the OpenOffice Project also released a native Mac OS X version along with the versions for Linux® and Microsoft® Windows®.
Unlike previous semi-releases on the Mac, 2.2 was based on the Mac's native Aqua user interface toolkit rather than X-Windows. The Mac release was only alpha quality, but it was still a major step forward in making OpenOffice a real competitor to Microsoft Office. If OpenOffice can attract a significant number of MacBook-wielding programmers, it might finally be able to cure some of the user-interface glitches that have plagued it since 1.0.
June also saw the biggest news on the browser front all year when Apple posted the first of several betas of Safari 3.0 for Windows. No longer content with its 6% (and growing) market share, Apple seems to be commencing a full-scale challenge to Microsoft on its home front. First iTunes and now Safari? Can iLife and iWork be far behind? Only 2008 will tell. In the meantime, Safari supports XML, XSLT, Cascading Style Sheets (CSS), XHTML, Atom, and RSS. Safari's CSS support is better than any other browser on Windows. While distracted by Google-inspired paranoia, Microsoft might not notice Apple sneaking up on it from behind.
In July, the W3C published the first public working draft of Efficient XML Interchange (EXI) Format 1.0. The spec claims that:
."
I'm not sure what's worse: the incredible opaqueness of the format or the fact that EXI really truly isn't a representation of the XML infoset. Opaqueness I expected, but the latter surprised me. EXI introduces data types such as Binary, Boolean, Decimal, Float, Integer, Unsigned Integer, and Date-Time. XML doesn't have data types, and that's a feature, not a bug. XML doesn't presume to tell any reader how it must interpret any particular string of text it finds in a document. EXI does.
Fortunately, by the end of the year, EXI started to see some serious push-back from other parts of the W3C, including the influential Technical Architecture Group. The W3C process makes it hard to derail a spec, no matter how unwise it is, so EXI will probably be released in 2008 regardless. It wouldn't be the first turkey egg the W3C has laid (schemas, anyone?), and it certainly won't be the last; but maybe with enough advance warning about the problems inherent in binary serializations, this won't cause as much damage as it otherwise might. Let's hope the world treats this more like XML 1.1 than XML Schemas.
In August, XML geeks dust off their French phrase books and head to Montreal for the annual Extreme Markup Languages conference. This is by far the geekiest of the three major XML shows each year. There are no classes about how to write stylesheets or schemas. Instead, topics include subjects like "A Web 2.0 ANSI SQL Transparent Native XML Nonlinear Hierarchical LCA Query Processor" and "Exploring intertextual semantics: A reflection on attributes and optionality."
This conference has always been a little shaky financially, usually with more speakers than paying attendees. The sponsor often doesn't make up its mind whether to hold the conference again until the end of the show; and everyone waits around with bated breath to see if it will make it one more year. Sadly, this year that didn't happen. 2007 turned out to be the last go-round for Extreme (although it outlasted many competitors).
But from the ashes of the old, a new conference shall arise. Mulberry Technologies, which has been running Extreme in everything but name for as long as I've attended, has announced Balisage: The Markup Conference, to take place in Montreal 12-15 August 2008.
."
If the Canadian loonie continues its run against the US dollar, 2008 might not be a cost-effective year for Americans to go, but Europeans and Canadians should have a good time.
The biggest story of the year broke wide open in September with the discovery that, in support of the Office Open XML format, Microsoft promoted a voter registration campaign within the various national member bodies at the International Standards Organization (ISO). The news first surfaced in Sweden, where 23 mostly minor Microsoft-affiliated companies joined the Swedish Standards Institute at the last minute, and 22 of them voted in favor of approving OOXML. Other national standards bodies also found themselves inundated with more new membership applications than they'd seen in years, mostly from Microsoft partners. Countries that hadn't previously participated in JTC 1/SC 34 (the specific ISO subcommittee where most XML work happens) suddenly joined.
Although Office Open XML got a simple majority of the votes (51-18-18), it needed at least a two-thirds majority of "P-members" and no more than 25% negative votes. It failed on both counts, so the spec went back to Ecma International for resolution of comments. Perhaps Microsoft can improve the spec enough to get the extra votes it needs when the spec comes up for reconsideration in February, but the outcome is uncertain. As I write this, Microsoft appears reluctant to allow the ISO to control future evolution of OOXML, so some previously Yes votes might change to No votes.
The effort to influence the OOXML ballot caused collateral damage to several other, unrelated specifications, including Document Schema Definition Languages (DSDL). Many of the new members who voted in favor of OOXML had no interest in other working-group tasks. Once their initial vote was cast, they disappeared and prevented the group from reaching a quorum on unrelated and much less controversial issues.
October saw the release of the Atom Publishing Protocol. APP began its life as a simple format for uploading blog entries to replace custom APIs like the MetaWeblog and WordPress APIs. But along the way, it turned into something much, much more.
APP is nothing less than a RESTful, scalable, extensible, secure system for publishing content to HTTP servers. On one hand, it's a pure protocol, completely independent of any particular server or client. On the other hand, because it's nothing more than HTTP, it's easy to implement in existing clients and servers.
The Web was originally intended to be a read-write medium. But for the first 15 years, most energy went into the reading half of that equation. Browsers got all the attention, while authoring tools withered on the vine. Page editors were generally poor and forced to tunnel through FTP to file systems. Only now, with APP, is the field opening up to editors that are as rich, powerful, and easy to use as the browsers.
Some good server software, such as the eXist native XML database, has already started to take advantage of APP, and several clients are working on it. More will do so over the coming year. Publishing on the Web will finally become as straightforward as browsing it.
In November, Mark Logic unveiled MarkMail, an XQuery-based site for interacting with e-mail archives. According to Jason Hunter:
"Each email is stored internally as an XML document and accessed using XQuery. All searches, faceted navigation, analytic calculations, and HTML page renderings are performed on a single MarkLogic Server machine."
MarkMail is currently indexing 500 or so Apache mailing lists, jdom-interest, and xml-dev, among others.
Naturally, the first thing people did with all this power was ego-surf. It turns out that within this collection, Michael Kay of Saxon fame is the top human poster of all time (a few Apache robots sending out commit messages beat him); but on xml-dev, top poster honors go to Len Bullard with more than 4,000 posts. The fact that most of Len's posts are several-page articles makes this even more impressive.
I came in at number 10 on xml-dev, with 1,014 posts. I would have been number 9, except that a couple of years ago, when I changed mail clients, my screen name changed from "Elliotte Rusty Harold" to "Elliotte Harold," and the database thinks those are two different people. There are still a few bugs in the system. :-)
December started with the IDEAlliance's annual XML 2007 conference, the largest XML show of the year. This year's event took place in Boston. Attendance was down, with just a few more than 300 attendees and 15 exhibitors.
Most of the show was about what are now relatively well-known technologies, at least to the elite group of XML developers who still attend. Like last year, XQuery stood out as the star of the show, although XForms made a respectable showing. XProc, RDFa, OpenDoc, Office Open XML, Atom, APP, and JSON were also subjects of some interest and hallway chatter. Web services and anything SOAP-related were conspicuous by their absence. I don't think I ever heard those terms mentioned except when they were followed by "but now we're moving to REST."
The one really new thing at the show came from an unexpected source: Intel. Although better known for hardware, Intel also develops software that takes maximum advantage of the company's processors. Intel came to the show to show off and release the Intel XML Software Suite, a collection of native X86 libraries for Linux and Windows that provide really fast XSLT processing, XPath evaluation, XML Schema Validation, and Document Object Model (DOM) and Simple API for XML (SAX) parsing. A Java Native Interface (JNI) based wrapper for the Java™ platform is also included.
Intel claims the library is twice as fast as XSLTC and Xalan for XPath and XSLT, and six times faster than Xerces-C++ for raw parsing of large (100 megabyte+) documents. The parser achieves these gains by using symbol table data structures that occupy less memory and by multithreading the processing across two or more cores. This works for documents in the 300 MB to 32 GB region. For smaller documents, the overhead of the technique makes traditional parsers faster.
I haven't had a chance to test those claims myself; but if they're true, that's very interesting. Xerces isn't the fastest parser out there, but a six-times speed-up is better than anyone else has done. Surprisingly, Intel has done this with the standard APIs, SAX and DOM. Personally, I had little doubt that XML parsing performance could be improved, but I expected that doing so would require new APIs designed for high performance. Intel doesn't seem to have needed that.
December usually closes with a bang as W3C working groups rush to finish their work and push out specs before the Christmas holidays. The week before Christmas is traditionally the single busiest time of year at the W3C. Keep an eye on. You might yet see a few surprises to come. :-)
2007 was a productive year for XML. The most sound and fury focused around the standardization of office document formats, a fight that even spilled over into the popular press. (Who ever thought you'd be reading about ISO standards for XML formats in the Wall Street Journal?)
But if I had to pick the most important story of the year, I'd be hard pressed to choose between the continuing slow growth of XQuery, APP, and XForms. All have the potential to radically alter the software infrastructure that underlies the Web. XForms is a radically new client-development platform, XQuery is a radically new server-development platform, and APP connects them together. Of the three, XQuery is ready for serious production use today, and APP is gearing up. Look for big things from both of them in 2008. XForms is running behind and may be a little late to the party, but I hope it gets there before the doors close. Either way, the future for XML on the Web looks brighter than ever.
Learn
- NoOOXML.org: Read about the voting on OOXML as tracked by NoOOXML.org.
- Office Open XML: Peruse additional info about OOXML in this Wikipedia entry.
- RFC 5023: The Atom Publishing Protocol: Read about this HTTP-based, application-level protocol for publishing and editing Web resources as Atom-formatted representations.
- MarkMail: Try a free service for searching mailing list archives. It indexes several hundred technical mailing lists, with more to come.
- Proceedings from Extreme Markup Languages: Read the papers and conference materials from 2001-2007, available in an assortment of formats.
- Extreme Markup Languages 2007: Read the various blogs that covered it (even though I didn't make it this year).
- Balisage: Continue the Montreal markup tradition in August. Submit your papers now.
-.
- New to XML page: Check out the XML zone's updated resource central for XML..
|
http://www.ibm.com/developerworks/xml/library/x-xml2007rvw.html
|
crawl-002
|
refinedweb
| 3,980 | 61.97 |
1.10 API for Raw Compilation
1.10.1 Bytecode Compilation
The compiler takes a list of Racket, and .
By default, all files with the extension ".rkt", ".ss", or ".scm" in a collection are compiled, as are all such files within subdirectories; the set of such suffixes is extensible globally as described in get-module-suffixes, and compile-collection-zos recognizes suffixes from the 'libs group. However, any file or directory whose path starts with skip-path or an element of skip-paths is skipped. (“Starts with” means that the simplified path p’s byte-string form after (simplify-path p #f)starts with the byte-string form of (simplify-path skip-path #f).)
The collection compiler reads the collection’s "info.rkt" file (see "info.rkt" is lists, each of which starts with a path for documentation source. See Controlling raco setup with "info.rkt" Files for more information. The sources (and the files that they require) are compiled in the same way as other module files, unless skip-docs? is a true value.
compile-include-files : A list of filenames (without directory paths) to be compiled, in addition to files that are compiled based on the file’s extension, being in scribblings, or being required by other compiled files.
module-suffixes and doc-module-suffixes : Used indirectly via get-module-suffixes.
Changed in version 6.3 of package base: Added support for compile-include-files.
1.10.2 Recognizing Module Suffixes
Added in version 6.3 of package base.
The mode and namespace arguments are propagated to find-relevant-directories to determine which collection directories might configure the set of suffixes. Consequently, suffix registrations are found reliably only if raco setup (or package installations or updates that trigger raco setup) is run.
The group argument determines whether the result includes all registered suffixes, only those that are registered as general library suffixes, or only those that are registered as documentation suffixes. The set of general-library suffixes always includes ".rkt", ".ss", and ".scm". The set of documentation suffixes always includes ".scrbl".
The following fields in an "info.rkt" file extend the set of suffixes:
module-suffixes : A list of byte strings that correspond to general-library module suffixes (without the . that must appear before the suffix). Non-lists or non-byte-string elements of the list are ignored.
doc-module-suffixes : A list of byte strings as for module-suffixes, but for documentation modules.
1.
1.10.4 Options for the Compiler
More options are defined by the dynext/compile and dynext/link libraries, which control the actual C compiler and linker that are used for compilation via C.
1.10.5 The Compiler as a Unit
1.10.5.1 Signatures
1.10.5.2 Main Compiler Unit
The unit imports compiler:option^, dynext:compile^, dynext:link^, and dynext:file^. It exports compiler^.
|
https://docs.racket-lang.org/raco/API_for_Raw_Compilation.html
|
CC-MAIN-2018-13
|
refinedweb
| 476 | 50.73 |
Created on 2017-08-08 13:43 by tschiller, last changed 2021-10-20 22:50 by iritkatriel. This issue is now closed.
The lib2to3 library doesn't detect/apply any fixes if the source files aren't included with the distribution. See get_all_fix_names at
This affects Azure's official Python site extensions [1], which only include bytecode pyc's for the fixes [2].
This results in bad installs when using setuptools to install packages that leverage the use_2to3 flag during the install [3]
[1]
[2]
[3]
What are you reporting as the bug here? 2to3 obviously can't work without the source, so based just on what you have written here this sounds like an Azure bug.
I'm reporting that lib2to3 doesn't work without having source .py files for the fixes that are packaged with the lib2to3 library. Perhaps the get_all_fix_names method in lib2to3/refactor.py should check for either .py or .pyc files?
The source files are included with the package that I'm installing (anyjson 0.3.3 in this case).
Ah, I see. We don't really support .pyc-only distribution, though we try not to break it.
Do you want to propose a fix?
It also breaks .zip file distribution, which I'm fairly sure we do explicitly support by virtue of having "python36.zip" in sys.path by default. And the ".pyc-only in a zip file" distribution is *totally* busted :) (and also officially released for Windows...)
I'm dragging in an importlib expert to the discussion, probably against his will, since this is really a problem of "how do I programmatically discover what I can import without using os.listdir()". Hopefully Brett can answer that question and we can come up with a patch.
Simplest way is to do and see if a spec can be found for the module in question. That will do the search for the module but it won't load it. This does dictate that you know the name of the module upfront, though. If you want more of a "list all modules since I don't know what I want" then you're out of luck until I develop the API (maybe 3.7?).
I'm sorry about entering the discussion without knowing any connection between the original problem and Brett's question, but isn't the latter answered by pkgutil.iter_modules (and pkgutil.walk_packages if needed)?
You're technically right, Verdan, but pkgutils is kind of a hack as it isn't always using standard APIs to achieve its goals, so I personally never recommend using the module unless absolutely necessary and you know exactly how brittle it can be.
Perhaps the more important question is whether 2to3 really needs to dynamically generate a list of fixers or if that should have been stopped due to YAGNI. There are only a few modules in the stdlib, and it doesn't seem to support proper namespace packages, so unless there are plans to suddenly add many more we could just make it a hard coded list.
|
https://bugs.python.org/issue31143
|
CC-MAIN-2021-49
|
refinedweb
| 511 | 65.42 |
The select package
While tinkering on a project, I frequently found myself having to make FFI calls to select(2). This package provides an interface to that system call. It also used to expose an STM interface for running select(2) with alternative STM actions, but that functionality was split into the stm-orelse-io package from version 0.3.
Changes in version 0.3:
Split all STM-related functionality into a separate package, stm-orelse-io, independent of select.
TODO:
Provide a type for fd_set that can be passed to and from C so that we can have a version of System.Posix.IO.select that reports which file descriptors are ready, instead of how many. Its type will be something like [Fd] -> [Fd] -> [Fd] -> Timeout -> IO ([Fd], [Fd], [Fd]).
NOTE: I feel I'm occupying prime namespace realestate with a package name like select. I'll happily let myself be chased away if anybody else wants to use this package name. Let me know.
Properties
Modules
- System
Downloads
- select-0.3.tar.gz [browse] (Cabal source package)
- Package description (included in the package)
Maintainer's Corner
For package maintainers and hackage trustees
|
http://hackage.haskell.org/package/select-0.3
|
CC-MAIN-2017-17
|
refinedweb
| 194 | 57.77 |
Maya API doesn’t compile with dot net framework 4.0, as it defines MStatus as MS, which is a namespace in .NET 4.0
Hence create a new project, select Visual C++, at the top select .Net Framework3.5 and make an Empty Project.
Then per super quick test you can add the following files:
stdafx.h
#include
#include <maya/MString.h>
#include <maya/MArgList.h>
#include <maya/MFnPlugin.h>
#include <maya/MPxCommand.h>
#include <maya/MIOStream.h>
main.h
#include "stdafx.h" class hello : public MPxCommand { public: hello(){ } virtual ~hello(){ } static void* creator(){ return new hello; } bool isUndoable() const{ return false; } MStatus doIt( const MArgList& args ); };
main.cpp
#include "stdafx.h" #include "main.h" MStatus hello::doIt( const MArgList& args ) { displayInfo("Hello "+args.asString(0)+"\n"); return MS::kSuccess; } MStatus initializePlugin( MObject obj ) { MFnPlugin plugin( obj, "Autodesk", "1.0", "Any" ); plugin.registerCommand( "hello", hello::creator ); cout << "initializePlugin()\n"; return MS::kSuccess; } MStatus uninitializePlugin( MObject obj ) { MFnPlugin plugin( obj ); plugin.deregisterCommand( "hello" ); cout << "uninitializePlugin()\n"; return MS::kSuccess; }
I use precompiled headers for all external stuff and all finished parts (so I can have multiple nodes and commands in one plugin and work on them one by one), you don't have to and in that case can dump the contents of stdafx.h into main.h and leave it out.
Now let's go to the project settings: Select the project you just created in the solution explorer and hit ALT + F7
Note that you select the Project and not the Solution, or the wrong options will appear (being you miss about every category that I'm going to mention next).
In the options set Configuration (at the top) to All Configurations. If you are developing for Maya 64 bit click the Configuration Manager... button, then in Active solution platform select
Now we're building for x64, so we can continue. Platform could be set to either Active or, preferably, all (in case you wish to change to x86 you already have the majority of the settings in place).
Then on the left go to Configuration Properties, expand it and hit General. There in General set Target Extension to .mll and set Configuration Type to Dynamic Library (.dll). This is the maya plugin format. The rest can remain as is.
So we have at least one .cpp (main.cpp) file, otherwise we do not get the C/C++ options. So do create these test files please. Then expand C/C++ and go to General under that category.
Additional Include Directories should be something along the lines of:
C:\Program Files\Autodesk\Maya2013\include;%(AdditionalIncludeDirectories)
You can click the text field, then the arrow appearing on the right, hit
Now under C/C++ go to Preprocessor and in Preprocessor Definitions paste:
WIN32;NDEBUG;_WINDOWS;NT_PLUGIN;REQUIRE_IOSTREAM;%\(PreprocessorDefinitions)
For Debug mode you may wish to explicitly define DEBUG instead of NDEBUG. Do not get confused by the WIN32, this also goes for 64-bit systems.
Then, also in C/C++, head to Precompiled Headers. If you want those that is, set it to Create (/Yc), if you use my test files the Header File should be stdafx.h and the Output File can remain default.
Now expand the Linker category, here in General somewhere halfway down you must set the Additional Library Directories. Same as the include, except it is named lib rather than include:
C:\Program Files\Autodesk\Maya2013\lib;%(AdditionalLibraryDirectories)
In Linker -> Input go to Additional Dependencies, you can edit this manually and separte each entry by enters or semicolons, or just paste this again:
Foundation.lib;
OpenMaya.lib;
OpenMayaUI.lib;
OpenMayaAnim.lib;
OpenMayaFX.lib;
OpenMayaRender.lib;
Image.lib;
opengl32.lib;
%(AdditionalDependencies)
This opens up the full maya functionality, most of the time the UI, FX and Render libs are not necessary.
When developing a plugin that is not using the simple plugin macro you need to define your own initialize and uninitialize to register all the commands and nodes. The docs will tell you that the simplecommand can only make plugins with one single command, which is so limited that I wonder why you would do something that simple in C++ rather than Python. So in Linker -> Command Line under additional options enter:
/export:initializePlugin /export:uninitializePlugin
This allows the functions to be exposed from the DLL and to be called by maya when loading the plugin. Which is necessary for the test files I gave above.
Now build and get angry if it doesn't work. Also post your errors so I can add the solutions in the relevant places above.
|
http://trevorius.com/scrapbook/maya/maya-api-in-visual-studio-2010/
|
CC-MAIN-2018-47
|
refinedweb
| 765 | 57.16 |
Agenda
<Noah> scribenick: noah
<scribe> scribe: Noah Mendelsohn
date: 7 March 2007
DC: I'm tempted to look at one particular issue: XHTML role and RDFa are both things people are trying to add without actually having to be in the loop with the main HTML work. Beneficiaries are people who want to create/use accessible AJAX applications, without having to get in the queue to get lots of features added to HTML. Are those good focal points for the discussion of extensibility?
<DanC_lap> ("which group?" is a non-trivial question)
TVR: The Web Accessibility group has taken an interesting tack. The role mechanism was initially proposed by me in the XHTML groups, and they are defining particular roles. There is now a question of how to do this in HTML, particularly given that the values of the attributes are QNames. What's being done could be viewed as a hack, or could be viewed as the way we should have done the transition. Make class="xxx;role", and there's a standard Javascript library that rewrites the DOM.
NM: So, the content is different if you're not Javascript enabled?
DC: Yes, but at least they've shown
the need is serious.
... So, maybe we just say to the HTML WG: this is important, go standardize it.
TVR: The fact that value is a QName
will definitely cause concern.
... I can do anything I want using <div> and <span>
RL: I think I read in the vision document that extensibility was not considered appropriate for the HTML working group goals.
<Zakim> Rhys, you wanted to say that DIAL is the way to look at that for authoring and to
<DanC_lap> (re role use cases, this deom is interesting . see also ...)
<Zakim> DanC_lap, you wanted to suggest that the cost of the quotes is dominated by the norms in your community
DC: Cost of putting quotes is not
about the space taken, typically, but social issues, what people in
your community accept, etc.
... Interesting you read extensibility as a non-goal for the HTML WG. I don't think I was trying to say that.
<timbl_> Noah: What I read the vision document to say is that two working groups will share a model.
<scribe> scribenick: rhys
NM: I read the vision document to say that there were two working groups that share a model.
<timbl_> DC: I expect them to share XML.
DanC: I don't expect the groups to share a model.
HT: who is responsible for XHTML 1.1 maintenance?
DanC: its a shared responsibility.
NM: (quotes the section of the vision document about the serialisations)
DanC: The two serialisations are in the HTML working group.
<scribe> scribenick: noah
NM: The vision document says:
"Instead,."
NM: I read that as saying that for any given abstract document, at least in the 80% case, then DOM would be the same.
<Zakim> Noah, you wanted to ask about goals of for HTML
DC: No, it didn't mean to say that.
HT: I'm unclear in the vision document, when it says HTML without qualification, it means all of the several variants, vs. specifically one (scribe infers the tag soup version)
DC: We'll know in a few months.
<DanC_lap> (I hope)
(TimBL edits to say "Instead, the charter calls for two equivalent serializations to be developed by the HTML WG, "
Scribe's note: the final text of the vision document was still being revised while the TAG meeting was in progress. Tim noted above that he made an edit to help eliminate the ambiguity that had just been discussed.
RL: Before lunch we were talking about mobile, especially device independence markup. DIAL is one approach to solving that problem, not having to do redirects, having one representation, etc.
DC: What do we have on DIAL?
RL: There's a WD.
DC: Does it tell a story?
RL: There's a primer.
See
RL: It's XHTML2 + XForms + Some other modules
<timbl_> XHTML2 + XFORMS + soem other modules
<ht_mit> DIAL stands for Device Independent Authoring Language
RL: These stories are based on actual
commercial usage, from vendors, network operators, content
providers, etc.
... Dirk wishes to create a web site viewable on, say, any web device including mobile.
DC: Which kind of org. does he work for?
RL: Say, network operators, content
partners (e.g. Disney/eBay), other sites. Maybe it helps you get
ringtones for your device.
... Dirk writes some DIAL as his markup. It's constructed to avoid device dependency?
DC: He uses emacs?
RL: Probably DIAL-ware tools.
DC: Available?
RL: Yes, e.g. from Volantis (chuckle). [Volantis is Rhys' employer.]
DC: Direct manipulation?
RL: Typically mixed, xml editor with
some help around the edges.
... If the markup is only the device independent stuff, then the device-specific stuff has to go somewhere, and has to be worth the incremental trouble.
... Example: companies may not trust transcoding of their logo images.
... So, there are ways of linking to the device dependent stuff. This is generic resources.
... The reference is device independent, but the infrastructure serves the right thing.
DC: Mostly deployed server-side?
RL: Yes, mostly.
... Opera mobile is an interesting example. It can do some level of rearrangement and transcoding on the device for a standard HTML page, but it can tend to be less successful insofar as the HTML they're starting with has already lost some information about the intent.
... Eventually, more will happen on the client, but there's a risk you send the device images, etc. it won't need.
... I see XHTML2 as being important for doing those things server-side.
... Forms is the main thing.
TVR: XHTML2 has some things like navigation lists, and the section stuff.
DC: How does section stuff work?
TVR: lets you open and close a tree.
RL: What's really crucial is the XML for extensibility, and BTW we'd like to do that using CDF.
<Zakim> timbl_, you wanted to ask about "Instead, the charter calls for two equivalent serializations to be developed for HTML"
<Zakim> ht_mit, you wanted to share some information about John Cowan's tagsoup project
HT: Reminding that I have 5-10 minutes of intro on tag soup and how it works.
<Zakim> Noah, you wanted to comment on server-side only XHTML2
<scribe> scribenick: rhys
NM: Rhys said that we care about this stuff on the server. The discussion changes when you move to the server. Insofar as we have these compositions only at the server, we've lost
<scribe> scribenick: noah
TVR: I disagree that this is similar
to JSP or ASP pages, because those will never run on the
client.
... Running it only on the server is a bootstrapping mechanism.
... I was several months ago against tag soup because it kills that story.
... The notion that it can move from server to client is what matters.
TBL: Lots of content is moved on the wire as part of the server-side business of assembling content.
NM: I agree. The risk is that, if tag soup is the only thing that can go beyond the servers, then you will only get composition and extensibility at the server, which indeed would be unfortunate.
RL: BTW, I've offered to talk in future on Uniquitous Web Applications Work.
TVR: Before lunch, we talked about writing a document about transition issues.
Raman shows a list of proposed topics:
<Raman> * TagSoup Issues
<Raman> This document will explore the issues that rise at the
<Raman> intersection of the TAG Soup and XML Web.
<Raman> As TagSoup evolves to enable incremental transition to XML, we
<Raman> identify individual differences in traditional XML 1.0
<Raman> serialization and TAgSoup, and for each such instance, enumerate
<Raman> the pros and cons (carrot vs stick)
<Raman> driving that issue, how it affects various issues of deployment,
<Raman> and who might benefit from us writing down such a document. In
<Raman> addition, it would be useful for the TAG to arrive at a pithy
<Raman> conclusion for each point analogous to the assertion
<Raman> - If you're interested in extensibility, use XML serialization.
<Raman> * Topic List
<Raman> 1. Quotes around attributes.
<Raman> 1. Example use cases.
<Raman> 2. Situations that justify deviation.
<Raman> 3. Possible drawbacks with use of this deviation.
<Raman> 4. Suggested best practice.
<Raman> 2. Some tags are special =img= doesn't need close tag.
<Raman> 3. XML or HTML serialization from /show source/
<Raman> 4. Cut and paste between HTML and XML
<Raman> 5. Points on the HTML TAGSoup <-> XML continuum.
<Raman> 6. Integration of SVG, MathML etc into Web pages
<Raman> 7. Integration of HTML into RSS, ATOM.
<Raman> 8. Connection and impact on one-web.
1. Quotes around attributes.
TBL: This is a bug
TVR: What I'd imagine is a matrix that says, e.g. if you don't put quotes around attributes, you won't be able to mix it with SVG, except that in this case you can clean things up. I'll refactor the list as you suggest.
HT: Missing end tags fall into 2-3 categories: known to be empty, in old SGML dtd were optional, were known not optional.
TBL: Unknown tags, possibly with namespaces.
<DanC_lap> the high-level things like "Integration of HTML into RSS, ATOM" are more appealing to me than "Quotes around attributes."
HT: Hierarchically: unknown start
tag.
... Under that, unknown namespace qualified start tag.
TVR: And lest we forget, free floating end tags not corresponding to a start.
HT: This is a a good template, at least as a general model, but let's not fill it in in detail for now.
<DanC_lap> (I realize why I have angst around TAG discussion of missing quotes and end tags... all these great examples and nobody's capturing them for the test suite.)
TVR: For the first bullet I gave subcategories. Can you think of subcats. for others?
HT: Yes, I'd like to see something
that says at least hypothetically: "best possible argument in favor
-- why do people do this?"
... e.g., I'd guess that most missing ";" at end of entity references are just typos, but others are done with conviction.
SW: Question, am I right that this tag soup thing was not an intentional design, except as a consequence of the "be liberal in what you accept philosphy"?
HT: Not quite, the SGML DTD said "you may omit the following end tags..."
SW: In these charters, there's a common DOM, an XML serialization, and a tag soup serialization.
<timbl_> You could also omit quotes, no?
TVR: It's all well and good if you can clean up soupy input, but why would you reserialize as soup?
SW: Are we doing some of what the WG will do?
TVR: We are learning on our feet. What I want us to focus on is: how will anything we do in the soup world affect the intersection? I want to see ample communication with the TAG.
DC: The groups will do similar things, but with different focus and logistics.
NM: Some workgroups have been very effective in taking more time than is sometimes convenient to be very crisp about articulating use cases, getting everyone to agree on what was important about those use cases, and make sure the mechanisms supported the use cases. That, ideally, would be a good way to get people to make conscious decisions about where extensibility is of value and where not.
TVR: The functions and operators stuff was very well done that way, even though XForms didn't use it in the end.
TBL: One of the very important questions is whether valid XML with namespaces is a subset of the tag soup serialization.
DC: With namespaces?
TBL: Hmm, maybe using the default namespace.
TVR: Does it mean that a browser that consumes soup can necessarily consume valid XHTML with MathML?
TBL: Yes, especially if HTML is default namespace, and the math stuff may not render right.
TVR: There's debate about that.
TBL: Today what's happening is that they'll ignore the namespaces and the math markup, but the math content will render, perhaps messily.
DC: The question is not ignoring unknown tags, it's what can you get at from Javascript. Sure you can stick in namespace decls, but can you get at them from Javascript.
TVR: Yes, what's in the DOM.
NM: I was confused. You have now explained that in addition to the work being done XHTML2, the HTML WG will take responsibility for two serializtions, one XML-based and one soupy?
Several: yes.
NM: Thank you, I was confused. That's very helpful. I thought we had one serialization from HTML, one from XHTML. The clarification is: two from HTML itself, one soupy and one XML.
TBL: I think you'd probably need to use the XML serialization for namespace-qualified stuff.
DC: I'm not convinced folks in the HTML WG are fully bought into supporting namespaces at all.
HT: I think the existing drafts suggest it's possible.
<ht_mit>
<ht_mit> HTML5 current draft
<ht_mit> Web Applications 1.0
<ht_mit> Working Draft — 6 March 2007
Working draft of HTML 5 (Web Applications 1.0):
<ht_mit>
From that: "Implementations that support XHTML5 must support some version of XML, as well as its corresponding namespaces specification, because XHTML5 uses an XML serialisation with namespaces. [XML] [XMLNAMES]"
We are discussing John Cowan's "TagSoup: A SAX parser in Java for nasty, ugly HTML" ( )
TVR: Recovers from lots of "errors" in the markup.
(The following is from the documentation on John Cowan's TagSoup):
"The HTML Scanner
• DOCTYPE declarations are ignored completely
• Consequently, external DTDs are not read
• Comments and processing instructions (ending in >, not ?>) are passed through to the application
• Entity references are expanded or turned into text"
"Element Rectification
• Rectification takes the incoming stream of starttags, end-tags, and character data and makes it well-structured
• TagSoup is essentially an HTML scanner plus a schema-driven element rectifier
• TagSoup uses its own schema language compiled into Schema objects"
"Parent Element Types
• Parent element types represent the most conservative possible parent of an element
• The schema gives a parent element type for each element type:
–The parent of BODY is HTML
–The parent of LI is UL
–The parent of #PCDATA is BODY"
HT: I think there's a meta annotation explicitly in the schema to declare the most conservative possible parent, at least in some cases where it can't be inferred.
DC: It's a bit like LEXX and YACC, in that there is a scanner table and a parser table you can fool with.
HT: But the fixups are built into the Java code, though key'd off the schema. It so happened that the very first document I looked at happened to be one that neither John's Tag Soup nor Dave Ragett's tidy could successfully handle. It was <center><tr> ... </center>. Both tools made the "mistake" of closing the table.
Scribe's note: in earlier informal discussions, it was observed that browsers ignore the <center>
HT: Possible fix is look ahead.
TVR: Maybe just throw away the <center> tag.
HT: Yes, you could probably do that with John's model. I'm thinking of something like a shift/reduce parser, but instead you get shift/ship-as-sax-event
<DanC_lap> (I wonder if ht is going to connect this to extensibility or something else beyond straight HTML parser design.)
HT: I'm experimenting with a system that uses John's tokenizer, and my own upper level. Wondering whether it can reconstruct the HTML 5 English language spec. Since that is sometimes described as a way of capturing the error recovery of today's browsers.
TVR: Sounds appealing. Trouble is likely to be where HTML 5 does backtracking...almost does an "unshift".
HT: I asked on the Tag Soup list whether John has a regression test suite. Elliotte suggested John has things, but got them from the Web, and it's likely there would be copyright problems in sharing it.
DC: Was waiting for you to relate this to extensibility. Our job is not to do a better job on HTML 5 than the WG is going to do.
HT: The TAG has a least power finding.
TVR: It's been suggested we should write a validator.
DC: Do you acknowledge that this could be seen as being rude, in that it's not our business as a workgroup to do this?
HT: Well, they have gone far down the road.
<scribe> scribenick: rhys
NM: I think there is a line to be walked and that we need to acknowledge Dan's concern about ownership. It's reasonable for people to be hesitant about the role of the TAG in this particular case, and others actually. The TAG should be careful and either contribute as individuals or learn from what is happening in particular working groups. It is appropriate for us to discuss all of this because it helps us learn the what the issues are.
<ht_mit>
<scribe> scribenick: Noah
HT: In the statement of tagSoupIntegration-54 it says "Treat it "as if" it had been processed by [some formalization of] 'tidy -asxhtml';". I feel I'm exploring that. I think the reasoning is closely related to least power, but trying to make the story as declarative as possible.
<Zakim> DanC_lap, you wanted to ask if ht's explorations suggest anything about the @role situation or other extensibility cases
DC: Any new insights into what to do about role attribute?
HT: Don't think so, the Tag Soup program predates that.
DC: Suppose I want to use something like role without waiting to go through HTML WG. Want to get at it from Javascript.
HT: Posit that it's not in the HTML spec. I don't know what he does with unknown attributes. Seems to me that you should be able to control that in the formalization of the mapping.
DC: Good thing to study. Also think about simpler stuff like SVG elements.
HT: I think those would be passed through. The philosophy of Tag Soup is to pass through when possible. I suspect he passes through.
NW: My experience a bit difference. I had trouble with a bunch of RDDL. It munged the namespace declarations.
HT: There's something about that, and a switch.
DC: Sam Ruby, Ian Hixie and others
are building a parsing library and 200 tests.
... Something like 2% of web documents use <image> spelled that way.
<DanC_lap>
<DanC_lap> or 0.2%
SW: We have 15 mins to go. We have a set of points Raman has set down, now need a strategy moving forward.
NM: What's the success criteria for the list Raman is working on?
<DanC_lap> esp
TVR: I would like it to be the place holder document for tag soup issue 54.
NM: And is it the list of answers to some question? Things to worry about?
DC: Potential table of contents for a document.
NM: Works for me.
TVR: And a framework to govern our work.
<DanC_lap> TVR asked for DanC to work on it with him. DanC agreed.
TVR: Happy to do an initial draft, as long as people view it as fodder for discussion, not something to shred.
<scribe> ACTION: T.V. Raman to draft initial discussion material on tag soup for discussion on 26 March, draft on the 19th or so.
TVR: Public or private?
NM: Public. Just make sure it's clear that we're trying to come up to speed, not tread on other peoples' toes.
SW: Next telcon will be on the 12th of March.
DC: regrets for the 12th.
<DanC_lap> I'm at risk for 12 March; travelling to SxSWi
SW: won't have time for agenda work until just after arriving.
DC: What about discussing XML chunk whatever.
NW: Was going to ask to just close
it.
... xmlChunk-44 was an attempt to tackle deep equals for XML. I now think we can't do better than XML Functions and Operators.
TBL: No communication from us.
NW: We always write a note when closing the issue.
DC: Garbage collect or endorse the draft.
NW: collect it.
SW: Objections?
Silence.
<scribe> ACTION: Norm to mark as abandoned the finding on deep equals and announce xmlChunk-44 is being closed without further action, with reason
RESOLUTION: close issue xmlChunk-44
<DanC_lap> sounds like 12 March call is cancelled
<DanC_lap> RESOLVED: to meet next 19 March
RESOLUTION: the next TAG teleconference will be on 19 March 2007.
SW: Adjourned
|
http://www.w3.org/2001/tag/2007/03/07-afternoon-minutes
|
CC-MAIN-2015-32
|
refinedweb
| 3,435 | 73.78 |
Talk:XML Schema
Discuss the XML Schema page here
Contents
Pros and Cons
Discussion / pro
- The difference between "Point of Interest", "Waypoint" and "Node" can be expressed through properties. I don't see the need of different data structures. Beside, Point of interests can be parts of the street landscape, as in bus stops, train stations, parking lots etc.
- Same is for streets, bus routes, wander routes etc.
- The scheme of defining areas is common in computer graphic. If there is a better way common in GIS, we should use the better one ;)
- The scheme makes it possible for the server to start the xml-data with the most important data and continue with lesser important data. The client could display only as much data as he wants and then closes the connection and skip the unimportant stuff (as example because the user already clicked on a scroll button).
- I expect the most raised eyebrowns at the fact, that I suggest a seperate list of properties instead of including a tag <properties> in every other object tag. This has several reasons:
- Properties to other properties will look much cleaner this way.
- Someone who isn't interested in properties can stop transfering data when he reached the properties - tag. Or a parser could start displaying the data, even when he has not finished receiving the whole dataset. Integrating the properties within the data would make it necessary to
transfer all properties to one object together with it.
- Structure is very simple to parse. The tag's depth is static, the tag names are static. And the whole structure is very strict defined (optional tags makes SAX-parser much harder to write).
contra
- Seperating and cluttering the data of one logical object over several places makes it harder for humans to read the document
- After validating with a parser, you still can't be sure, whether the document is valid. As example it could contain references to id's, not submitted yet. (Question: Can the id-linkage be expressed in XML-Schema?)
Conclusion
- To me, it would be best to support the above XML schema for application reading or writing the key/values. A second GPX interface is not necessary since proxies can be established that translates this to GPX easily.
-- User:Imi - 19:40, 29 November 2005
- Using "Track" as the name for a collection of segments isn't a good idea. It's confusing because it's too similar to GPX trk notation. Andy's suggestion of "way" would be better, if not "street".
- I would like to see more respect to the fact that we have collections of nodes and collections of segments - why use XML if you're just going to send flat lists? <nodes> and <segments> would be sensible, with <nodes> coming first so that when a segment refers to an ID it's already been received.
- Why not just have <street uids="12,13,14,15" /> to represent streets, and have them inherit all the properties of the segments they contain?
- Can the id-linkage be expressed in XML-Schema? : Yes, the XML Schema key and keyref statements can be used to ensure that the UIDs are unique and the references are valid. I don't think it ensures that the ID's are in the correct order, but you won't have to worry about this if the document is valid! --Matt 16:46, 19 Dec 2005 (GMT))
Inconsistent
In REST you use this to create a segment with properties
<osm version='0.2'> <segment tags='name=harrypotter; ; ; ; ; ' from='194797' to='226261' /> </osm>
But if you want to use this schema you would have to do this:
<segment from="85" to="12345" /> <property uid="85" object="19" key="pub" value="cheap beer" />
Why are they different, is this because of SteveC's preference to the semicolon way? This should be consistent with the real world..
-- User:Emj 08:45, 30 November 2005
- I always thought Steve's "semicolon way" to be a quick hack implementation until someone fix it up and implement this one. There was a discussion of the disadvantages of the semi-colon stuff somewhere in the mailing list. --Imi 22:02, 20 Dec 2005 (GMT)
XML Schema Description
I made the XML Schema follow the documentation on the article part of this page, apart from a few deviations:
- I couldn't figure out how to have an element called "nodes" under both the "osm" main element and the "area" element (ditto for the tracks). Instead, I called them "nodeRef" and "trackRef" when under the "area" and "track" elements. This simplifies things a bit, but may not be aesthetically pleasing.
- There is a bit of additional XML stuff hanging off the "osm" element to do with namespaces. I have to confess, I don't understand XML namespaces at all, so I copied this from another Schema. If someone knows a better way to do it, please step forward!
Additionally, there are a number of points on this page which are worth considering (and probably implementable in XML Schema).
- Why not have:
<track uid="123">1 2 3 4 5</track>
rather than:
<track uid="123"> <segmentRef uid="1" /> <segmentRef uid="2" /> <segmentRef uid="3" /> <segmentRef uid="4" /> <segmentRef uid="5" /> </track>
since Schema is perfectly capable of validating a list of whitespace-separated UIDs. (Note: I don't know whether the XPath/key(ref) stuff can handle it, though...)
- Ditto above for areas.
- It may be possible to restrict the references in track and area to point to only UIDs used for segments and nodes, but this is beyond my limited Schema skills!
User:Matt - 18:00, 19 December 2005
Difference between property's "uid" and "object" ?
I see no difference between the attribute "uid" and the attribute "object" of the property tag. Anyone against removing "object" from properties and just use uid? --Imi 22:01, 20 Dec 2005 (GMT)
osmap.org
Hello I just found this website and am very impressed. I've been working on a Map XML based data format for a little over a year, with an end goal similar to OpenStreetMap (I think). Although I still think osmap was a good idea, it hasn't gone anywhere, nobody even knows about it. I'm curious if you would find any parts of osmap useful in the development of yours. Maybe you can get ideas from it while creating your own XML format. Or help develop it and use it as your transfer/sharing format. Or if you think its stupid, maybe I could just point my domain to yours. Check it out at least. I look forward to helping out or sharing ideas and knowledge. I'm really open to your ideas and opinions, and hope you are too and don't consider this spam!
- I read it, at it look not promising to me. Beside the many errors and inconsistencies in the textual definition, it is "just another annotation" scheme for map data. In OSM, annotation stuff is currently seperated from the physical description of the map (which I think is good.) --Imi 14:33, 15 Feb 2006 (GMT)
Way or track
I have checked the referred schema file and in that it is stated that there are no way elements they are called track. I however believe this page is correct. Karlskoging1 22:01, 1 February 2007 (UTC)
Schema Feedback
Hello, I've just been looking at the docs and schema and have some bits of feedback.
- You should plan for versioning in the XSD. Consider having a namespace with a date under it, just as everyone else does. Maybe
also add a version attribute in the root node so that you can up the version without changing namespace.
- There's nothing in the docs that says whether lat/long are in decimal or alternate representations (remember, its all just strings...this should be explicit). Nor do you say which datum. WGS-84?
- There's no timestamp attribute on node; if there was you'd have to decide between time_t, seconds since 1/1/70, or a full xsd:dateTime format, which appears to be what the example is striving for. But the example is invalid as dateTime is ISO8601 format, and should be something like 2007-03-04T18:15:30Z .
- It's often handy to add an extension point for metadata, say a <metadata> element of type: xsd:any and namespace##other. That tells XSD to only allow stuff in other namespaces (like dublin core or XHTML).
If you must use XSD for your syntax (the good alternate is RelaxNG), consider adding many more sample docs. Ant 1.7 has a special task, <schemavalidate> that is designed to bulk validate a set of docs against some XSD files. So you can have your build process automatically check that the XSD is aligned with your test docs. SteveL 21:06, 15 March 2007 (UTC)
|
http://wiki.openstreetmap.org/wiki/Talk:XML_Schema
|
CC-MAIN-2017-04
|
refinedweb
| 1,488 | 70.53 |
Details
- Type:
Improvement
- Status: Resolved
- Priority:
Trivial
- Resolution: Won't Fix
- Affects Version/s: 0.10
-
- Component/s: HTTP Interface
- Labels:None
- Skill Level:Committers Level (Medium to Hard)
Description":[
]}
to be valid there needs to be a root element (and then an array with commata) like in the non-continuous feed:
{"results":[
{"seq":38,"id":"f473fe61a8a53778d91c38b23ed6e20f","changes":[
]},
{.
Activity
Exactly. Each line is valid JSON, but the response itself is not valid JSON.
Now to read the response line by line, a method is needed which reads (from the never ending feed) until a newline comes and then parses the JSON object. Now to do this, the reading method needs to block (as it does not know whether the next character is a new line or not). Now if you take JSON as a structured format, it is much more easy and suitable (because there is no additional information about newlines, etc. needed) if such a feed is read in a SAX-like manner, which throws events whenever there are new elements within the feed:
Starting seq
Starting id
Starting changes
Starting rev
Closing rev
...
but such a parser needs the document (or better the stream) to be valid JSON, which the current ouptut of the cont. feed is not.
The feed format used to be as you wish it, and still is for non-continuous mode. Consider the uses of continuous mode, though, and this makes sense. Continuous mode is for continuous replication and for external indexers (e.g, couchdb-lucene but also many others). If the response is a single JSON object, then those users would have to wait for the end of the response before they can parse the result, and there is no end to a continuous feed in general.
If there exists a SAX-style json parser, then that might be another approach, but I'm not aware of one.
This programming model seems so trivial that even if one did exist, I can't imagine it would be easier;
while (read(line) != EOF){ change=parse(line); apply(change); }
Also, since the continuous format is deliberately not "valid JSON" in the manner described, this is not a bug but a feature request..
I use _changes?heartbeat=5000&feed=continuous, so I get a response at least every 5 seconds, even if no documents change.
See handleResponse() method for a working code example.
2 solutions :
1) Use select on the socket which return the answer which is what I do for consumer, and just stop listening on this socket when you don't need it anymore
2) or wait for each line and make a a new request each time an answer is coming which is basically longpolling.
Again, though, the typical use of _changes is to keep some other system up to date with all changes (another database for replication, a full-text index for couchdb-lucene, etc).
Regarding the
"If there exists a SAX-style json parser, then that might be another approach, but I'm not aware of one."
just that it does not exist "in the wild" it does not neccessarily mean there isn't one - we have a JSON Push Parser which can be compared to a SAX-like parser - it does not get a reader, but uses a writer - and once data is written on that writer, the parser will do it's work (and emit the above named events).
This Push Parser has now an extension to handle continous writes of distinct JSON objects ({}{}{}...) like the _changes feed delivers in continuous mode, but it might be different with a different parser out there, which expects the feed to return valid JSON data.
That there is no end does not mean, that there might not be a parser which can not work with the data.
Start Document
Starting seq
Starting id
Starting changes
Starting rev
Closing rev
...
... <-- lots of changes
...
long time later
End Document <-- timeout of _changes feed happens here
By the way, XMPP works the same - it basically has an infinitely long stream of XML elements flowing - but still starts with a root node and ends with a closing one to be valid XML.
You might call it a feature request, but I think either the output should be valid JSON or not. If you tell me the output is not valid JSON, okay, but I couldn't read this from the docs, as all other _changes interfaces return valid JSON.
Using &heartbeat=1000 was also my first approach, but it just is not as performant to send a newline every 1000ms just to keep a while loop running.
Obviously you can't have a valid json response on a continuous feed if you don't read line by line. Again what you want is using longpolling which send a valid response: wait until there is a change, close connection.
For long timeout you can use heartbeat=true, when send an empty line regurlaly (default timeout). You can also use timeout option instead of heartbeat.
Thats exactly what I am talking about: the response is not valid JSON.
It is:
{}
{}
{}
...
(not valid JSON)
where it should be
{root:[
{},
{},
{},
...
]} <-- timeout happens here
(valid JSON)
And I don't want to use longpolling, as this means I need to reconnect after every change.
What I want to use is ?feed=continuous (so I can track multiple changes with one HTTP request) with &timeout=X (and NOT heartbeat=Y, which would just waste bandwidth) AND a valid JSON response which is parseable.
So if you think parsing line by line is okay, thats fine, but for a SAX-based parser a newline outside an element is just white space - let me change this into a feature request for an additional REST parameter on the _changes interface - let's say
&encapsulated=true|false
which is false by default and if true wraps the response into a
{"results":[
...
],"last_seq":0}}
and delimits the different changes elements by comma.
if you listen the changes why not making a valid json while you listening ie : save line, add comma, continue .
I prefer to have a valid json line by line rather than having to remove ending coma each time i want to use this line.
I am not reading in lines, I am reading whatever gets returned into the buffer and then writing it to the Push Parser, and yes, indeed, my first fix for this was writing a {"results":[ on the Parser and the transforming every \n into a comma. But it just does not seem right - CouchDB should return (or at least should be able to return) a valid JSON document itself.
Anyways I am noticing you are not with me here and it seems odd that I need to argue about adding a flag to make a return valid which is currently coming back invalid.
We have written enough, so I am sure someone having the same issues will find this conversation and may reopen this defect. Then he or she can try convincng you again.
> By the way, XMPP works the same - it basically has an infinitely long stream of XML elements
> flowing - but still starts with a root node and ends with a closing one to be valid XML.
Stream parsing is much more common in the XML world; unfortunately JSON stream parsers are not (yet?) widespread.
> You might call it a feature request, but I think either the output should be valid JSON or not.
> If you tell me the output is not valid JSON, okay, but I couldn't read this from the docs, as all
> other _changes interfaces return valid JSON.
It's not valid JSON, and I would agree it's a bug if you're referring to the Content-Type header which is returned:
$ curl -v -H "Accept: application/json"
...
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Server: CouchDB/0.11.0a813819 (Erlang OTP/R12B)
< Date: Mon, 21 Dec 2009 13:35:52 GMT
< Content-Type: application/json
< Cache-Control: must-revalidate
<
I would also agree that it's inconsistent with the way a view is returned. Views are complete JSON docs, but have newlines in magic places to make it possible to parse them line-at-a-time.
$ curl -H "Accept: application/json"
{"total_rows":5,"offset":0,"rows":[
{"id":"6d85c1ca41bd9eb4435b2fcac3670b84","key":"6d85c1ca41bd9eb4435b2fcac3670b84","value":{"rev":"1-d4388236888cf366f37777e888221968"}},
{"id":"927c96f86e2fdebbcae3520ac2054fbd","key":"927c96f86e2fdebbcae3520ac2054fbd","value":{"rev":"1-d4388236888cf366f37777e888221968"}},
{"id":"bar","key":"bar","value":{"rev":"6-7c014f6deb5cd9935625a8f411f8db08"}},
{"id":"c134ca85221694a28f9ad8953b3087a7","key":"c134ca85221694a28f9ad8953b3087a7","value":{"rev":"1-d4388236888cf366f37777e888221968"}},
{"id":"foo","key":"foo","value":{"rev":"21-b94c260d79b638231eb14b3de8458c2f"}}
]}
It would have been possible for feed=continuous to work this way too.
In that case I'd have thought the comma should appear at the start of each line (apart from the first, obviously), otherwise you need a dummy record at the end to close the stream cleanly. And if you want the heartbeat feature you'll still need a dummy record.
> if you want the heartbeat feature you'll still need a dummy record.
A simple newline would still be fine as a heartbeat for 'gets' readers of course. What I meant was, if you are using a stream parser you probably won't get an event for just reading a newline, so heartbeat would have to send some real content to be useful in that case.
I don't need the heartbeat feature, as I use a non-blocking method to read the stream - what I want is simply an option to make CouchDB return valid JSON on the _changes continuous feed
I agree with the commata by the way - they definitely need to be at the beginning of the next element.
continuous mode used to return valid JSON, and clients were expected to clip out valid lines (using the newline hints) if they wanted to parse each change as it happened. It was deliberately changed to this behavior to allow clients to more easily handle _changes, since all consumers of _changes at that time needed to do the same logic.
Changing it back will make it "correct" but harder to use (every consumer will have to add hackish logic to parse part of the response). Since the request format is predicated on "Sax-style json parsers" which apparently don't exist, it feels like purism for its own sake, practicality taking a step down.
Perhaps it suffices to change the returned content-type to multipart/related where each part is a valid JSON response?
That said, I would hope it suffices to document the returned format for continuous mode with the expectation that it will be the preferred format for developers that write external indexers (which is the reason it was changed to the current format in the first place).?
What you describe is by the way the old behavior of _changes continuous feed. I agree that we fail on validation in timeout scenario (though it's easy to solve it on client side). The one problem with old behaviour I see with it is the extra time you have when you really want continuous changes ie :
1) test if lines start with {'results
2) test if line is {}
3) remove the ","
4) finally deserialize.
Actually you just have to listen changes, get the line, handle it which is a way easier, faster. And you still can create a valid json parser at the end. We need to choose what is the best here, validation or fast handling.
I know I am the "outsider" here, but I disagree - having a clean and valid interface is as much important as speed. +1 Vote for the flag (as this is both speedy and valid used with a SAX style parser).
I just propose a choice. Will see what others will say ...
I still fail to see how a sax style parser and json could work together but that's another story. Anyway your response will never be valid if it timeout your parser will still need to complete the response. Maybe indeed sending a multipart response is more valid here.
As for the SAX style parser:{ x: "abc", y: "xyz" }
would be:
startDocument
startElement x
value abc
endElement
startElement y
value xyz
endElement
endDocument
If the client is closing the connection it will most likely close it, when all data needed is read --> valid state
When the timeout occurs, the server (CouchDB) will send the closing ],"last_seq":XYZ}, just like it does now --> valid state
I see though timeout could occur on client side -> no valid response also valid state != valid json in case you close the connection.
Anyway I understand your position. Not sure what need to be done yet though
I've met the Yeti. His name is Yajl. He's quite friendly, but no one ever really mentions the SAX thing much. Cause no one ever really produces partial JSON documents. Cause there really aren't that many SAX parsers. Cause as it turns out, SAX is a huge friggin pain in the butt. Granted this 'push parser' sounds more like a pull-dom parser. Either way, this discussion on commas is pretty weird for being about commas.
The validity of that response with that content-type is debatable. AFAIK theres nothing in the specification that says you can't repeat values in a JSON stream. And there are parsers that allow for parsing multiple values. The XMPP 'infinite document' is just a clever hack around a format that explicitly denies repeated documents.
If someone wants commas in that stream, then they should feel free to write a patch. But comma's have nothing to do with non-blocking i/o or other such things.
Cheerio!
Haha, I didn't even know Yajl existed
Glad you met the Yeti!
With the partial JSON documents: you are right, it's a rare case, but in general I would call such an endless changes feed a partial JSON document.
You are right about the (non-)blocking - I just wanted to make sure that you understand why I am not eager to search for newlines in the feed - for me it's not a standard response with single JSON documents per line, but one giant stream of JSON. I don't care whether there are any white spaces between elements - may it be newlines or something else.
When we made the change away from commas I was a little concerned about validity. Now that you are bringing it up, I find myself thinking that a query option to provide valid JSON would be great.
I think the general sentiment is that it would't hurt to give an option. The next step is for someone to write a patch for this. If the patch is clean I'd have no objections to including it.
Wow, lots of comments on this one.
I originally implemented this as a single JSON stream, it was switched to newline separated json objects for ease parsing by clients. I don't have an opinion one way or the other, but the thing starts to bothers me is the culture offering more options so that everyone can have it exactly as they want it.
The stems from the increasing "texture" of the API, and what must get documented and tested, and the burden of what must get implemented for those who want to make compatible CouchDB implementations. I tend to favor simpler APIs to the point of occasionally pushing some of the complexity to the client to ensure the server itself isn't completely overloaded with complexity and options.
The more options, the more possible errors, yes - but making the client fixing the validity of the response still seems a little weird.
A client which parses line-by-line can still strip the JSON header (which is always the first line and the same length btw.) and disregard any leading commas easily, because such a client interpretes each changes entry anyways - whereas a different parser working on the overall stream or a client which just wants all changes in the last X seconds and waits for the timeout has more problems making the response valid afterwards.
But I agree it simplifies the process for some if it is readable line-by-line, so this might just be one of the cases where an option just is necessary (don't understand me wrong, I would also be fine if valid JSON output is the only default).
For me, the non-valid-JSON (e.g. object-per-line without exceptions) is fine (and probably more useful than the alternative), EXCEPT that the Content-Type: application/json seems wrong for that case. I think "Content-Type: application/json" should only be provided on content that may easily (trivially) be parsed by a conforming JSON parser, which is definitely not true for the current feed=continuous feed.
If someone else wants to close this as "Won't Fix", be my guest as that seems to be the consensus.
I'm taking the uncontroversial stance of setting "Fix Version" as 2.0 so we can revisit this (if we want) and hopefully it doesn't remain open indefinitely.
First couchdb committer to reach retirement can take on this and the million niggling deviations from The Canonical Truth Of HTTP. Or knitting, at the retiree's option.
I'm not sure to follow, each line is a valid json. Purpose of continuous feed is to get changes line by line, so where is the problem?
|
https://issues.apache.org/jira/browse/COUCHDB-604?focusedCommentId=12793202&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2015-18
|
refinedweb
| 2,910 | 66.98 |
MrDave's (David Yack) WebLog Server2005-05-06T05:14:00ZTeach yourself WPF in 5 days... has a great post on learning WPF in five days. This isn’t a go to Dallas for trianing, this is a how to use the resources online to learn WPF. Check it out <a href="">here</a>.<img src="" width="1" height="1">MrDave ASP.NET 2.0 Conversion Gotchas<p><font face="Times New Roman" size="3"><span style="FONT-SIZE: 12pt">One of my last few <a title="" href="">posts</a> talked about a gotcha that occurs when converting web projects that had files that were no longer in the project file but still in the project folder.<?xml:namespace<o:p></o:p></span></font></p> <p><font face="Times New Roman" size="3"><span style="FONT-SIZE: 12pt">After exchanging e-mails with <a title="" href="">Scott</a> </span></font><font face="Arial" color="navy" size="2"><span style="FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial">ConversionReport.txt file.</span></font><o:p></o:p></p> <p><font face="Times New Roman" size="3"><span style="FONT-SIZE: 12pt".<o:p></o:p></span></font></p> <p><font face="Times New Roman" size="3"><span style="FONT-SIZE: 12pt">The continuous improvement that has been seen in the migration wizard over the last year, and the fact that attention is still there to make it better is great! <o:p></o:p></span></font></p><img src="" width="1" height="1">MrDave Blast - Fort Collins Colorado - October 3rd<p>I will be up in Fort Collins, Colorado on October 3rd speaking at <a href="">Widbey Blast </a>which is sure to be a full day of good stuff all for free! Last I heard it was filling up so if you want to go I would hury up and get registered!</p> <p <a href="">Don Kiely</a>, <a href="">Keith Brown</a>, <a href="">Kathleen Dollard</a>, Doug Gregory and Tim Colton. </p> <p>You can find out more info and register for the event here <a href="">Widbey Blast Web Site</a></p> <p>Looks like a busy week coming up, 2 days of giving a training event in Denver, MVP Summit in Redmond and back to Fort Collins for this event. Come to think of it this last month has kind of been like that! </p><img src="" width="1" height="1">MrDave Live updated to include Microsoft Visual Studio 2005 Team Suite, RC<p>Looks like today the Go Live was updated to include Team Suite, RC. </p> <p>You can find the full Go Live details at<a href="" target="_blank"></a> or the amendment <br />for current Go Live users at <a href=""></a> which is dated as of today!</p> <p> </p> <p> </p><img src="" width="1" height="1">MrDave Template Parameters<p>One of the cool features of Visual Studio is the ability to do project and item templates. Prior to these it used to be a real pain to package up your best practices. </p> <p>Scott G recently posted on using them with ASP.NET you can find that <a href="">here</a></p> <p>Buried in one of his comments is the <a href="">link to this MSDN page </a>that has a wealth of information on the parameters that are exposed for use on the template pages.</p> <p>Using the template capability is a great way to promote consistency across your team.</p><img src="" width="1" height="1">MrDave Howard and Free Copy of Code Smith<p>Do you need any other excuse to visit Colorado Springs?</p> <p>Read the full details <a href="">here</a> </p><img src="" width="1" height="1">MrDave to ASP.NET 2.0 from Beta2-->RTM<div class="Section1"> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'> The following is from <a href="">Brian Goldfarb’s post</a> about changes between beta 2 – Keep the info coming knowing these types of things can really help the early adopters move on to RTM quickly!</span></font></p> <blockquote style='margin-top:5.0pt;margin-bottom:5.0pt'> <div> <p><i><font size="3" face="Times New Roman"><span style='font-size:12.0pt; font-style:italic'>It is time to start preparing for the RTM of ASP.NET 2.0 and in order to do that I've had the team prepare a great paper that outlines the major changes that we've made since Beta 2. Find it here: <a href=""></a></span></font></i></p> <p><i><font size="3" face="Times New Roman"><span style='font-size:12.0pt; font-style:italic'>Next week, we will be posting detailed API x API changes since Beta2 which should help give even more insight. I hope you find this useful</span></font></i>! </p> <p class="MsoNormal"><font size="3" face="Times New Roman"><span style='font-size: 12.0pt'><img border="0" width="1" height="1" id="_x0000_i1025" src="" /></span></font></p></div></blockquote></div><img src="" width="1" height="1">MrDave like Virtual Earth is live!<div class="Section1"> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>If you didn’t get a chance to play with Virtual Earth when it was up last night for testing – it appears to be back alive now.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>Everyone from <a href="">Scoble</a> to <a href="">Chandu</a> who is on the Virtual Earth team has been talking about it.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>If you are looking at how to create your own Virtual Earth application that leverages the power of the VE engine you might find Dr. Neil Rodyn’s site interesting <a href="">ViaVirtualEarth </a> he has a couple of good articles on how to get you started. </span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>I happened to catch the late night testing last night and got to experiment with it and prototyped a Commercial Real Estate application. With any luck you might get a peak of it in the future.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>Check out the Virtual Earth <a href="">blog</a> which has already jumped right to the punch line of Why would I use VE – Isn’t it just like Google Maps</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>The new locate me function is pretty cool – I haven’t tried the one that requires software but the IP Locate gets you close to the region your in.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'><a href="">Here’s</a> my IP Locate – Where are you?</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'> </span></font></p></div><img src="" width="1" height="1">MrDave language should book samples use?<div class="Section1"> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'> I figured this would be a great way to start off the week with a little debate and energized discussion!</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>If you’re writing technology books about .NET you really can’t avoid the question of what language to do you use for the code samples?</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>Read more and share your opinion <a href="">here now!</a></span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'> </span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'> </span></font></p></div><img src="" width="1" height="1">MrDave Code for user group website<div class="Section1"> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>I’m looking for good ideas on how to share source code for a user group web site. We want to get more members involved in learning via the process of building it but the thought of just having a free for all with managing the code scares me!</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>What I’m looking for is ideally something that will integrate with Visual Studio 2005. It would be nice if we could not have to exclude users that could only have Visual Web Developer.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>Ideally it would not require check in/out from a separate application other than Visual Studio.</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>Anyone doing this now – any one have ideas?</span></font></p> <p><font size="3" face="Times New Roman"><span style='font-size:12.0pt'>We have considered gotdotnet workspaces but everyone I talk to says they have too many problems – Anybody want to convince me otherwise? </span></font></p></div><img src="" width="1" height="1">MrDave
|
http://weblogs.asp.net/mrdave/atom.aspx
|
CC-MAIN-2014-15
|
refinedweb
| 1,606 | 64.3 |
Retrieving data and pagingFor the server side there’s no code changes we need to do – once you update the NuGet package for the Azure Storage extension the Azure Mobile Services .NET Backend, you should get the continuation links when the request would have more items than the ones returned. If you don’t have a service setup yet, you can check out the bonus material later in this post. Now that the service setup is out of the way, we can start with the client code. As I mentioned before, the full support is only available in the managed SDK for now, so let’s take a look at it. For this scenario, I’ll use a simple controller which returns list of people (a very limited contact list), with my class in the client defined as follows:
public class Person { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("age")] public int Age { get; set; } }By default, a read operation in a table controller will return up to 50 items. If we have more in our table storage, then the client will need to request more, by casting the result of the
ToListAsyncor
ToEnumerableAsyncmethods to the
IQueryResultEnumerable<T>interface. The code below shows how to go through all elements in the table.
public async Task<double> CalculateAverageAge() { var client = new MobileServiceClient(AppUrl, AppKey); var table = client.GetTable<Person>(); var sum = 0.0; var count = 0; var items = await table.Take(10).ToEnumerableAsync(); while (items != null && items.Count() != 0) { count += items.Count(); sum += Enumerable.Sum(items, i => i.Age); var queryResult = items as IQueryResultEnumerable<Person>; if (queryResult != null && queryResult.NextLink != null) { items = await table.ReadAsync<Person>(queryResult.NextLink); } else { items = null; } } return sum / count; }If we’re using JSON tables (i.e., not using a type such as
Person, and using the
JTokenfamily instead), we can request the response to be wrapped in an object by passing
trueto the
wrapResultparameter of the
ReadAsyncmethod. If that’s the case, then the result is wrapped in an object with the following properties: results, which will contain the array with the actual results from the service; and nextLink, which will be present if the HTTP response had a Link header with the continuation token that should be passed to the
ReadAsyncmethod to retrieve the next set of entries from the table.
public async Task<double> CalculateAverageAge2() { var client = new MobileServiceClient(AppUrl, AppKey); var table = client.GetTable("person"); var sum = 0.0; var count = 0; var response = await table.ReadAsync("$top=10", null, wrapResult: true); while (response != null) { var items = (JArray)response["results"]; var nextLink = (string)response["nextLink"]; count += items.Count(); sum += Enumerable.Sum(items, i => (int)i["age"]); if (nextLink != null) { response = await table.ReadAsync(nextLink, null, true); } else { response = null; } } return sum / count; }With the continuation links, the client can now traverse all the items from a table in Azure Storage by passing them to the read methods in the table objects.
Bonus material: setting up a service using Azure Storage tablesIn case you haven’t yet set up a service with a table storage backed controller, here are the steps which you can follow to do so.
Setting up a storage accountIf you haven’t done so yet, you’ll need to set up an Azure Storage account to use table storage. Before we can start saving and retrieving data in tables, we need a storage account in Azure for that. You can follow the instructions at the “How To Create a Storage Account” tutorial to create the account. Once the account is setup, you’ll need to get the account name and access key to tell the mobile service how to talk to the storage account. To get the key, you can go to the quickstart or dashboard tab in the traditional portal and select the “Manage Access Keys” option:
Setting up the serviceTo use the Azure Storage to store data from your mobile service, you need to add the Azure Storage Extension for the Azure Mobile Services .NET Backend. Right-click your service project, select “Manage NuGet Packages…” and search for “mobileservices.backend”. Select the package mentioned above (and shown below) and click “Install”.
Personas shown below. Notice that instead of using the
EntityDatabase class (typically used in projects based on Entity Framework / SQL), I’m using the
StorageDatabase class, which defines properties used by Azure Table Storage such as partition / row key, among others.
public class Person : StorageData { public string Name { get; set; } public int Age { get; set; } }Next, let’s add the connection string for the storage account to the service. We can either set it in the web.config file (easy to do, good for development, can be used when debugging locally, but not as secure) or in the connection strings section of the “configure” tab in the portal (more secure as people with access to the source code won’t be able to see it, but only works when the service is deployed to Azure). For simplicity sake, I’ll make the change in my Web.config:
<connectionStrings> <add name="MS_TableConnectionString" connectionString="<the actual value>" providerName="System.Data.SqlClient" /> <add name="My_StorageConnectionString" connectionString="DefaultEndpointsProtocol=https;AccountName=<the account>;AccountKey=<the key>;"/> </connectionStrings>Finally, we can create the controller class which will expose the data from the table in the storage account as table in the mobile service. The implementation is almost identical to the one which is generated in the download link from the portal quickstart page, or in the Visual Studio template for an Entity Framework-backed data, with the following exceptions:
- The domain manager is of type
StorageDomainManager<T>, which maps between the mobile service table and the backing data store (Azure storage)
- Since tables in Azure storage don’t support fully querying capabilities as do tables in a SQL database, returning an
IQueryable<T>is not supported. But the base type
TableController<T>has one method which can be used with storage tables:
QueryAsync(for querying multiple items) and
LookupAsync(for querying single items)
public class PersonController : TableController<Person> { protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); var tableName = controllerContext.ControllerDescriptor.ControllerName.ToLowerInvariant(); var connStringName = "My_StorageConnectionString"; DomainManager = new StorageDomainManager<Person>(connStringName, tableName, Request, Services); } // GET tables/Person public Task<IEnumerable<Person>> GetAllPerson(ODataQueryOptions queryOptions) { return base.QueryAsync(queryOptions); } // GET tables/Person/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task<SingleResult<Person>> GetPerson(string id) { return base.LookupAsync(id); } // PATCH tables/Person/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task<Person> PatchPerson(string id, Delta<Person> patch) { return UpdateAsync(id, patch); } // POST tables/Person/48D68C86-6EA6-4C25-AA33-223FC9A27959 public async Task<IHttpActionResult> PostPerson(Person item) { Person current = await InsertAsync(item); return CreatedAtRoute("Tables", new { id = current.Id }, current); } // DELETE tables/Person/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task DeletePerson(string id) { return DeleteAsync(id); } }One thing that must be noted is that the lookup / delete / update methods take an id of type string – as is part of the contract with the client SDKs. But the id of items stored in tables is made up of two parts: partition and row keys. To merge these two worlds, we define a mapping that the id is of the form <partition key>,<row key> (where the keys can be wrapped in single quotes if necessary). For example, if we run the service with the code shown above, we can insert an item with a request like the following:
POST /tables/person HTTP/1.1 X-ZUMO-APPLICATION: <the app key> Content-Type: application/json; charset=utf-8 Host: mobile-service-name.azure-mobile.net Content-Length: 75 { "id": "partition,row1082", "name": "dibika lyzufu", "age": 64 }
|
https://azure.microsoft.com/pl-pl/blog/better-support-for-paging-with-table-storage-in-azure-mobile-services-net-backend/
|
CC-MAIN-2019-04
|
refinedweb
| 1,276 | 51.58 |
Have a question about Spyder or need some quick help with the IDE? Ask here!
Hi. I use the latest Spyder Standalone installation on Windows. Yesterday, on the day of installation, everything was fine. Today, after some Windows updates, Spyder does not launch anymore. Already tried to reinstall with two options, for everyone on my computer and just for me, but I get the same error when launching, which is:
C:\Program Files\Spyder>Python\python.exe Spyder.launch.pyw
Traceback (most recent call last):
File "Spyder.launch.pyw", line 34, in <module>
from spyder.app.start import main
File "pkgs\spyder\app\start.py", line 21, in <module>
import zmq
File "pkgs\zmq__init.py", line 125, in <module>
from zmq import backend
File "pkgs\zmq\backend\init.py", line 32, in <module>
raise original_error from None
File "pkgs\zmq\backend\init.py", line 27, in <module>
_ns = select_backend(first)
File "pkgs\zmq\backend\select.py", line 32, in select_backend
mod = import_module(name)
File "D:\obj\windows-release\37amd64_Release\msi_python\zip_amd64\init.py", line 127, in >import_module
File "pkgs\zmq\backend\cython\init__.py", line 6, in <module>
from . import (
ImportError: DLL load failed: The specified module could not be found.
The strangest thing that comes to my mind is the line:
File "D:\obj\windows-release\37amd64_Release\msi_python\zip_amd64__init__.py", line 127, in
Why is it trying to load something from D: drive?
Any Idea about what I could try?
C:\Users\Russell>chcp 1252
Active code page: 1252
C:\Users\Russell>call C:\anaconda\Scripts\activate C:\anaconda
(base) C:\Users\Russell>spyder 1>nul 2>nul
if closed spyder will close also
|
https://gitter.im/spyder-ide/public?at=60a1684cb10fc85b569d2e53
|
CC-MAIN-2021-39
|
refinedweb
| 275 | 60.82 |
This site uses strictly necessary cookies. More Information
I'm using the google cardboard SDK and i have a script attached to the child "Head" in the GvrMain prefab. There's also a Character controller connected and the vrCamera variable has been set to the "Head" object to this so that i can move the user based on the code which will follow.
Here is a link to what my scene looks like and what the head object looks like in unity and it's configuration.
The issue i'm having is that i want to move the character when the user tilts their head at an angle, all this works fine but the issue is that when the simpleMove function is called nothing is happening... I've logged to see if any of the variables upto the point are empty but none of them seem to be; just this function doesn't seem to be getting called. Code below.
public class VRLookWalk : MonoBehaviour {
public Transform vrCamera;
public float toggleAngle = 30.0f;
public float speed = 3.0f;
public bool moveForward;
private CharacterController myCC;
// Use this for initialization
void Start () {
myCC = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
if (vrCamera.eulerAngles.x >= toggleAngle && vrCamera.eulerAngles.x < 90.0f)
{
moveForward = true;
} else {
moveForward = false;
}
if (moveForward)
{
Vector3 forward = vrCamera.TransformDirection (Vector3.forward);
myCC.SimpleMove (forward * speed);
}
}
}
Answer by OpenXcell-Studio
·
Oct 17, 2016 at 06:57 AM
folow the step:
1)delete all thing except terrain and direction light
2)drag GvrMainViewer.prefab
3)create new camera name it maincamera
4)add character controll and vr look walk on maincamera
5)than drag maincamera in to vr camera
play now
Still no difference :( the simple$$anonymous$$ove function isn't firing for some reason
you have to drag just GvrVieqwer$$anonymous$$ain.prefab
not Gvr$$anonymous$$ain and not need of head in his child
and in vr camera assign maincamera after complete above step
and assign character controller on maincamera and vr look walk script is also on main camera and than in public vr camera drag the main camera
Here is a screenshot of the prefabs in the folder i just realised that i have to use the legacy folder "Gvr$$anonymous$$ain" since when i want to use the GvrViewer$$anonymous$$ain or GvrController$$anonymous$$ain it just seems to be an empty object like the first two links i just posted.
GvrController Gvr$$anonymous$$ain LegacyGvr$$anonymous$$ain
accept the answer if it solved your problem, vr mode is on than only your main camera move with your head movement
Answer by walidabazo
·
Sep 22, 2017 at 11:19 AM
Show this.
Unity 5.5 to Unity 2017 - Google VR
0
Answers
Problem UI masking in google vr 2020, unity 2020
0
Answers
EnterpriseSocial Q&A
|
https://answers.unity.com/questions/1257533/moving-the-user-with-google-cardboard-sdk.html
|
CC-MAIN-2021-43
|
refinedweb
| 471 | 52.94 |
sleep()
Suspend a thread for a given length of time
Synopsis:
#include <unistd.h> unsigned int sleep( unsigned int seconds );
Arguments:
- seconds
- The number of realtime seconds that you want to suspend the thread for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The sleep() function suspends the calling thread until the number of realtime seconds specified by the seconds argument have elapsed, or the thread receives a signal whose action is either to terminate the process or to call a signal handler. The suspension time may be greater than the requested amount, due to the nature of time measurement (see the Tick, Tock: Understanding the Neutrino Microkernel's Concept of Time chapter of the QNX Neutrino Programmer's Guide), or due to the scheduling of other, higher priority threads by the system.
Returns:
0 if the full time specified was completed; otherwise, the number of seconds unslept if interrupted by a signal.
Examples:
/* * The following program sleeps for the * number of seconds specified in argv[1]. */ #include <stdlib.h> #include <unistd.h> int main( int argc, char **argv ) { unsigned seconds; seconds = (unsigned) strtol( argv[1], NULL, 0 ); sleep( seconds ); return EXIT_SUCCESS; }
|
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/s/sleep.html
|
CC-MAIN-2019-47
|
refinedweb
| 205 | 51.38 |
Actively participating in
the development of a static code analyzer such as NDepend
is a good way to learn about tricky Common Type System (CTS)
details. Every feature have to be tested properly to cop with things like
managed and unsafe unmanaged pointer types (ref out and *), open/close generic
types, generic parameter types, methods with special name (.ctor() .cctor()
get_ set_ add_ remove_…), all sorts of arrays combination,
virtual/new/override methods, explicit interface implemented methods, nested
types, anonymous namespace… And of course, all this tricky points can be more
or less combinated.
During our tests we found 2
bugs related to anonymous namespace. One in VSTS Coverage and one in the Visual
Studio Code Model. Hopefully, the other CTS peculiarity seems to be bug free as far
as our tests are concerned.
When the lightning strikes
2 times the same place, I suppose that this is not by chance: namespace are not
first class citizen in the CTS. In other words, there are no metadata tables related
to namespace in the metadata of an assembly. At IL level, namespace are just types
names’ prefixes. This lack of support for namespace certainly leads team responsible
for these features to forget about testing these cases.
The Team Coverage Anonymous Namespace Bug
This bug occurs when there
is a nested type in a type declared in an anonymous namespace. For example
testing this piece of code…
class ClassInAnonymousNamespace {
internal class NestedClass {
internal static int MethodTested(int a, int b) {
return a + b;
}
}
}
…leads
to the following Team Coverage XML. We can see that instead of having the class
ClassInAnonymousNamespace.NestedClass
declared inside the anonymous namespace, we have a class named .NestedClass declared in the ClassInAnonymousNamespace namespace.
The Visual Studio Code Model Anonymous
Namespace Bug
This bug occurs with VB.NET, when you
have a type declared in an anonymous namespace. For the VB.NET compiler, the anonymous
namespace doesn’t exist. Indeed, the VB.NET compiler makes it so that every type
declared in an assembly are prefixed by the name of the assembly. I don’t know
the reason for such choice, but I hope there is a solid one because it is
really not elegant. Update 24 July 2008: This is a customizable VB.NET project setting: Application > Root Namespace.
Now consider the VisualStudio code model. As shown below, a VB.NET type
declared in an anonymous namespace doesn’t reference a namespace object. To see
the assembly name namespace, one needs
to analyze the delta between the FullName
and the Name of the type.
|
http://codebetter.com/patricksmacchia/2008/07/24/the-anonymous-namespace-bug/
|
CC-MAIN-2016-50
|
refinedweb
| 426 | 56.45 |
MATH ADVENTURES WITH PYTHON
AN ILLUSTRATED GUIDE TO EXPLORING MATH WITH CODE
BY PETER FARRELL
San Francisco
Playlists
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out
MATH ADVENTURES WITH PYTHON. Copyright © 2019 by Peter Farrell.
All rights reserved. No part of this work may be reproduced or transmitted in any form
or by any means, electronic or mechanical, including photocopying, recording, or by
any information storage or retrieval system, without the prior written permission of the
ISBN10: 1593278675
ISBN13: 9781593278670
Publisher: William Pollock
Production Editor: Meg Sneeringer
Cover Illustration: Josh Ellingson
Developmental Editor: Annie Choi
Technical Reviewer: Patrick Gaunt
Copyeditor: Barton D. Reed
Compositors: David Van Ness and Meg Sneeringer
Proofreader: James Fraleigh
The following images are reproduced with permission:
Figure 102 by Acadac mixed from originals made by Avsa
(
100km.png#/media/File:Britainfractalcoastlinecombined.jpg; CCBYSA3.0);
Figure 1119 by Fabienne Serriere,.
For information on distribution, translations, or bulk sales, please contact No Starch
Press, Inc. directly:
Playlists
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; [email protected] in; fringement of the
trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While
every precaution has been taken in the preparation of this work, neither the authors nor
No Starch Press, Inc. shall have any liability to any person or entity with respect to any
loss or damage caused or alleged to be caused directly or indirectly by the information
contained in it.
INTRODUCTION
Which approach shown in Figure 1 would you prefer? On the left, you see an example of
a traditional approach to teaching math, involving definitions, propositions, and proofs.
This method requires a lot of reading and odd symbols. You’d never guess this had
anything to do with geometric figures. In fact, this text explains how to find the
centroid, or the center, of a triangle. But traditional approaches like this don’t tell us
why we should be interested in finding the center of a triangle in the first place.
Figure 1: Two approaches to teaching about the centroid
Next to this text, you see a picture of a dynamic sketch with a hundred or so rotating
triangles. It’s a challenging programming project, and if you want it to rotate the right
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out
way (and look cool), you have to find the centroid of the triangle. In many situations,
making cool graphics is nearly impossible without knowing the math behind geometry,
for example. As you’ll see in this book, knowing a little of the math behind triangles,
like the centroid, will make it easy to create our artworks. A student who knows math
and can create cool designs is more likely to delve into a little geometry and put up with
a few square roots or a trig function or two. A student who doesn’t see any outcome,
and is only doing homework from a textbook, probably doesn’t have much motivation
to learn geometry.
In my eight years of experience as a math teacher and three years of experience as a
computer science teacher, I’ve met many more math learners who prefer the visual
approach to the academic one. In the process of creating something interesting, you
come to understand that math is not just following steps to solve an equation. You see
that exploring math with programming allows for many ways to solve interesting
problems, with many unforeseen mistakes and opportunities for
improvements along the way.
This is the difference between school math and real math.
THE PROBLEM WITH SCHOOL MATH
What do I mean by “school math” exactly? In the US in the 1860s, school math was
preparation for a job as a clerk, adding columns of numbers by hand. Today, jobs are
different, and the preparation for these jobs needs to change, too.
People learn best by doing. This hasn’t been a daily practice in schools, though, which
tend to favor passive learning. “Doing” in English and history classes might mean
students write papers or give presentations, and science students perform experiments,
but what do math students do? It used to be that all you could actively “do” in math
class was solve equations, factor polynomials, and graph functions. But now that
computers can do most of those calculations for us, these practices are no longer
sufficient.
Simply learning how to automate solving, factoring, and graphing is not the final goal.
Once a student has learned to automate a process, they can go further and deeper into a
topic than was ever possible before.
Figure 2 shows a typical math problem you’d find in a textbook, asking students to
define a function, “f(x),” and evaluate it for a ton of values.
Figure 2: A traditional approach to teaching functions
This same format goes on for 18 more questions! This kind of exercise is a trivial
problem for a programming language like Python. We could simply define the function
f(x) and then plug in the values by iterating over a list, like this:
import math
def f(x):
return math.sqrt(x + 3) x + 1
#list of values to plug in
for x in [0,1,math.sqrt(2),math.sqrt(2)1]:
print("f({:.3f}) = {:.3f}".format(x,f(x)))
The last line just makes the output pretty while rounding all the solutions to three
decimal places, as shown here:
f(0.000) = 2.732
f(1.000) = 2.000
f(1.414) = 1.687
f(0.414) = 2.434
In programming languages like Python, JavaScript, Java, and so on, functions are a
vitally important tool for transforming numbers and other objects—even other
functions! Using Python, you can give a descriptive name to a function, so it’s easier to
understand what’s going on. For example, you can name a function that calculates the
area of a rectangle by calling it calculateArea(), like this:
def calculateArea(width,height):
A math textbook published in the 21st century, decades after Benoit Mandelbrot first
generated his famous fractal on a computer when working for IBM, shows a picture of
the Mandelbrot set and gushes over the discovery. The textbook describes the
Mandelbrot set, which is shown in Figure 3, as “a fascinating mathematical object
derived from the complex numbers. Its beautiful boundary illustrates chaotic behavior.”
Figure 3: The Mandelbrot set
The textbook then takes the reader through a painstaking “exploration” to show how to
transform a point in the complex plane. But the student is only shown how to do this on
a calculator, which means only two points can be transformed (iterated seven times) in
a reasonable amount of time. Two points.
In this book, you’ll learn how to do this in Python, and you’ll make the program
transform hundreds of thousands of points automatically and even create the
Mandelbrot set you see above!
ABOUT THIS BOOK
This book is about using programming tools to make math fun and relevant, while still
being challenging. You’ll make graphs to show all the possible outputs of a function.
You’ll make dynamic, interactive works of art. You’ll even make an ecosystem with
sheep that move around, eat grass, and multiply, and you’ll create virtual organisms
that try to find the shortest route through a bunch of cities while you watch!
You’ll do this using Python and Processing in order to supercharge what you can do in
math class. This book is not about skipping the math; it’s about using the newest,
coolest tools out there to get creative and learn real computer skills while discovering
the connections between math, art, science, and technology. Processing will provide the
graphics, shapes, motion, and colors, while Python does the calculating and follows
your instructions behind the scenes.
For each of the projects in this book, you’ll build the code up from scratch, starting
from a blank file, and checking your progress at every step. Through making mistakes
and debugging your own programs, you’ll get a much deeper understanding of what
each block of code does.
WHO SHOULD USE THIS BOOK
This book is for anyone who’s learning math or who wants to use the most modern tools
available to approach math topics like trigonometry and algebra. If you’re learning
Python, you can use this book to apply your growing programming skills to nontrivial
projects like cellular automata, genetic algorithms, and computational art.
Teachers can use the projects in this book to challenge their students or to make math
more approachable and relevant. What better way to teach matrices than to save a
bunch of points to a matrix and use them to draw a 3D figure? When you know Python,
you can do this and much more.
WHAT’S IN THIS BOOK?
This book begins with three chapters that cover basic Python concepts you’ll build on to
explore more complicated math. The next nine chapters explore math concepts and
problems that you can visualize and solve using Python and Processing. You can try the
exercises peppered throughout the book to apply what you learned and challenge
yourself.
Chapter 1: Drawing Polygons with Turtles teaches basic programming concepts like
loops, variables, and functions using Python’s built-in turtle module.
Chapter 2: Making Tedious Arithmetic Fun with Lists and Loops goes deeper into
programming concepts like lists and Booleans.
Chapter 3: Guessing and Checking with Conditionals applies your growing Python
skills to problems like factoring numbers and making an interactive number-guessing
game.
Chapter 4: Transforming and Storing Numbers with Algebra ramps up from solving
simple equations to solving cubic equations numerically and by graphing.
Chapter 5: Transforming Shapes with Geometry shows you how to create shapes and
then multiply, rotate, and spread them all over the screen.
Chapter 6: Creating Oscillations with Trigonometry goes beyond right triangles and
lets you create oscillating shapes and waves.
Chapter 7: Complex Numbers teaches you how to use complex numbers to move points
around the screen, creating designs like the Mandelbrot set.
Chapter 8: Using Matrices for Computer Graphics and Systems of Equations takes
you into the third dimension, where you’ll translate and rotate 3D shapes and solve huge
systems of equations with one program.
Chapter 9: Building Objects with Classes covers how to create one object, or as many as
your computer can handle, with roaming sheep and delicious grass locked in a battle for
survival.
Chapter 10: Creating Fractals Using Recursion shows how recursion can be used as a
whole new way to measure distances and create wildly unexpected designs.
Chapter 11: Cellular Automata teaches you how to generate and program cellular
automata to behave according to rules you make.
Chapter 12: Solving Problems Using Genetic Algorithms shows you how to harness
the theory of natural selection to solve problems we couldn’t solve in a million years
otherwise!
DOWNLOADING AND INSTALLING PYTHON
The easiest way to get started is to use the Python 3 software distribution, which is
available for free at. Python has become one of the most
popular programming languages in the world. It’s used to create websites like Google,
YouTube, and Instagram, and researchers at universities all over the world use it to
crunch numbers in various fields, from astronomy to zoology. The latest version
released to date is Python 3.7. Go to and choose
the latest version of Python 3, as shown in Figure 4.
Figure 4: The official website of the Python Software Foundation
Figure 5: Click the downloaded file to start the install
You can choose the version for your operating system. The site detected that I was using
Windows. Click the file when the download is complete, as shown in Figure 5.
Follow the directions, and always choose the default options. It might take a few
minutes to install. After that, search your system for “IDLE.” That’s the Python IDE, or
integrated development environment, which is what you’ll need to write Python code.
Why “IDLE”? The Python programming language was named after the Monty Python
comedy troupe, and one of the members is Eric Idle.
STARTING IDLE
Find IDLE on your system and open it.
Figure 6: Opening IDLE on Windows
A screen called a “shell” will appear. You can use this for the interactive coding
environment, but you’ll want to save your code. Click File▸New File or press ALTN,
and a file will appear (see Figure 7).
Figure 7: Python’s interactive shell (left) and a new module (file) window, ready
for code!
This is where you’ll write your Python code. We will also use Processing, so let’s go over
how to download and install Processing next.
INSTALLING PROCESSING
There’s a lot you can do with Python, and we’ll use IDLE a lot. But when we want to do
some heavyduty graphics, we’re going to use Processing. Processing is a professional
level graphics library used by coders and artists to make dynamic, interactive artwork
and graphics.
Go to and choose your operating system, as shown
in Figure 8.
Figure 8: The Processing website
Figure 9: Where to find other Processing modes, like the Python mode we’ll be
using
Download the installer for your operating system by clicking it and following the
instructions. Doubleclick the icon to start Processing. This defaults to Java mode. Click
Java to open the dropdown menu, as shown in Figure 9, and then click Add Mode.
Select Python Mode▸Install. It should take a minute or two, but after this you’ll be
able to code in Python with Processing.
Now that you’ve set up Python and Processing, you’re ready to start exploring math!
PART I
HITCHIN’ UP YOUR PYTHON WAGON
aylists
story
opics
utorials
ffers & Deals
ghlights
ettings
Support
Sign Out
1
DRAWING POLYGONS WITH THE TURTLE MODULE
Centuries ago a Westerner heard a Hindu say the Earth rested on the back of a turtle.
When asked what the turtle was standing on, the Hindu explained, “It’s turtles all the
way down.”
Before you can start using math to build all the cool things you see in this book, you’ll
need to learn how to give instructions to your computer using a programming language
called Python. In this chapter you’ll get familiar with some basic programming concepts
like loops, variables, and functions by using Python’s builtin turtle tool to draw
different shapes. As you’ll see, the turtle module is a fun way to learn about Python’s
basic features and get a taste of what you’ll be able to create with programming.
PYTHON’S TURTLE MODULE
The Python turtle tool is based on the original “turtle” agent from the Logo
programming language, which was invented in the 1960s to make computer
programming more accessible to everyone. Logo’s graphical environment made
interacting with the computer visual and engaging. (Check out Seymour Papert’s
brilliant book Mindstorms for more great ideas for learning math using Logo’s virtual
turtles.) The creators of the Python programming language liked the Logo turtles so
much that they wrote a module called turtle in Python to copy the Logo turtle
functionality.
Playlists
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out
Python’s turtle module lets you control a small image shaped like a turtle, just like a
video game character. You need to give precise instructions to direct the turtle around
the screen. Because the turtle leaves a trail wherever it goes, we can use it to write a
program that draws different shapes.
Let’s begin by importing the turtle module!
IMPORTING THE TURTLE MODULE
Open a new Python file in IDLE and save it as myturtle.py in the Python folder. You
should see a blank page. To use turtles in Python, you have to import the functions
from the turtle module first.
A function is a set of reusable code for performing a specific action in a program. There
are many builtin functions you can use in Python, but you can also write your own
functions (you’ll learn how to write your own functions later in this chapter).
A module in Python is a file that contains predefined functions and statements that you
can use in another program. For example, the turtle module contains a lot of useful
code that was automatically downloaded when you installed Python.
Although functions can be imported from a module in many ways, we’ll use a simple
one here. In the myturtle.py file you just created, enter the following at the top:
from turtle import *
The from command indicates that we’re importing something from outside our file. We
then give the name of the module we want to import from, which is turtle in this case.
We use the import keyword to get the useful code we want from the turtle module. We
use the asterisk (*) here as a wildcard command that means “import everything from
that module.” Make sure to put a space between import and the asterisk.
Save the file and make sure it’s in the Python folder; otherwise, the program will throw
an error.
WARNING
Do not save the file as turtle.py. This filename already exists and will cause a conflict
with the import from the turtle module! Anything else will work: myturtle.py,
turtle2.py, mondayturtle.py, and so on.
MOVING YOUR TURTLE
MOVING YOUR TURTLE
Now that you’ve imported the turtle module, you’re ready to enter instructions to move
the turtle. We’ll use the forward() function (abbreviated as fd) to move the turtle forward
a certain number of steps while leaving a trail behind it. Note that forward() is one of the
functions we just imported from the turtle module. Enter the following to make the
turtle go forward:
forward(100)
Here, we use the forward() function with the number 100 inside parentheses to indicate
how many steps the turtle should move. In this case, 100 is the argument we pass to
the forward() function. All functions take one or more arguments. Feel free to pass other
numbers to this function. When you press F5 to run the program, a new window should
open with an arrow in the center, as shown in Figure 11.
Figure 11: Running your first line of code!
As you can see, the turtle started in the middle of the screen and walked forward 100
steps (it’s actually 100 pixels). Notice that the default shape is an arrow, not a turtle,
and the default direction the arrow is facing is to the right. To change the arrow into a
turtle, update your code so that it looks like this:
myturtle.py
from turtle import *
forward(100)
shape('turtle')
As you can probably tell, shape() is another function defined in the turtle module. It lets
you change the shape of the default arrow into other shapes, like a circle, a square, or
an arrow. Here, the shape() function takes the string value 'turtle' as its argument, not a
number. (You’ll learn more about strings and different data types in the next chapter.)
Save and run the myturtle.py file again. You should see something like Figure 12.
Figure 12: Changing the arrow into a turtle!
Now your arrow should look like a tiny turtle!
CHANGING DIRECTIONS
The turtle can go only in the direction it’s facing. To change the turtle’s direction, you
must first make the turtle turn a specified number of degrees using the right() or left()
function and then go forward. Update your myturtle.py program by adding the last two
lines of code shown next:
myturtle.py
from turtle import *
forward(100)
shape('turtle')
right(45)
forward(150)
Here, we’ll use the right() function (or rt() for short) to make the turtle turn right 45
degrees before moving forward by 150 steps. When you run this code, the output should
look like Figure 13.
Figure 13: Changing turtle’s direction
As you can see, the turtle started in the middle of the screen, went forward 100 steps,
turned right 45 degrees, and then went forward another 150 steps. Notice that Python
runs each line of code in order, from top to bottom.
EXERCISE 11: SQUARE DANCE
Return to the myturtle.py program. Your first challenge is to modify the code
in the program using only the forward and right functions so that the turtle
draws a square.
REPEATING CODE WITH LOOPS
Every programming language has a way to automatically repeat commands a given
number of times. This is useful because it saves you from having to type out the same
code over and over and cluttering your program. It also helps you avoid typos that can
prevent your program from running properly.
USING THE FOR LOOP
In Python we use the for loop to repeat code. We also use the range keyword to specify
the number of times we go through the loop. Open a new program file in IDLE, save it
as for_loop.py, and then enter the following:
for_loop.py
for i in range(2):
print('hello')
Here, the range() function creates i, or an iterator, for each for loop. The iterator is a
value that increases each time it’s used. The number 2 in parentheses is the argument
we pass to the function to control its behavior. This is similar to the way we passed
different values to the forward() and right() functions in previous sections.
In this case, range(2) creates a sequence of two numbers, 0 and 1. For each of these two
numbers, the for command performs the action specified after the colon, which is to
print the word hello.
Be sure to indent all the lines of the code you want to repeat by pressing TAB (one tab is
four spaces). Indentation tells Python which lines are inside the loop so for knows
exactly what code to repeat. And don’t forget the colon at the end; it tells the computer
what’s coming up after it is in the loop. When you run the program, you should see the
following printed in the shell:
hello
hello
As you can see, the program prints hello twice because range(2) creates a sequence
containing two numbers, 0 and 1. This means that the for command loops over the two
items in the sequence, printing “hello” each time. Let’s update the number in the
parentheses, like this:
for_loop.py
for i in range(10):
print('hello')
When you run this program, you should get hello ten times, like this:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Let’s try another example since you’ll be writing a lot of for loops in this book:
for_loop.py
for i in range(10):
print(i)
Because counting begins at 0 rather than 1 in Python, for i in range(10) gives us the
numbers 0 through 9. This sample code is saying “for each value in the range 0 to 9,
display the current number.” The for loop then repeats the code until it runs out of
numbers in the range. When you run this code, you should get something like this:
0
1
2
3
4
5
6
7
8
9
In the future you’ll have to remember that i starts at 0 and ends before the last number
in a loop using range, but for now, if you want something repeated four times, you can
use this:
for i in range(4):
It’s as simple as that! Let’s see how we can put this to use.
USING A FOR LOOP TO DRAW A SQUARE
USING A FOR LOOP TO DRAW A SQUARE
In Exercise 11 your challenge was to make a square using only the forward() and right()
functions. To do this, you had to repeat forward(100) and right(90) four times. But this
required entering the same code multiple times, which is timeconsuming and can lead
to mistakes.
Let’s use a for loop to avoid repeating the same code. Here’s the myturtle.py program,
which uses a for loop instead of repeating the forward() and right() functions four times:
myturtle.py
from turtle import *
shape('turtle')
for i in range(4):
forward(100)
right(90)
Note that shape('turtle') should come right after you import the turtle module and
before you start drawing. The two lines of code inside this for loop tell the turtle to go
forward 100 steps and then turn 90 degrees to the right. (You might have to face the
same way as the turtle to know which way “right” is!) Because a square has four sides,
we use range(4) to repeat these two lines of code four times. Run the program, and you
should see something like Figure 14.
Figure 14: A square made with a for loop
You should see that the turtle moves forward and turns to the right a total of four times,
finally returning to its original position. You successfully drew a square using a for loop!
CREATING SHORTCUTS WITH FUNCTIONS
Now that we’ve written code to draw a square, we can save all that code to a magic
keyword that we can call any time we want to use that square code again. Every
programming language has a way to do this, and in Python it’s called a function, which
is the most important feature of computer programming. Functions make code
compact and easier to maintain, and dividing a problem up into functions often allows
you to see the best way of solving it. Earlier you used some builtin functions that come
with the turtle module. In this section you learn how to define your own function.
To define a function you start by giving it a name. This name can be anything you want,
as long as it’s not already a Python keyword, like list, range, and so on. When you’re
naming functions, it’s better to be descriptive so you can remember what they’re for
when you use them again. Let’s call our function square() because we’ll be using it to
make a square:
myturtle.py
def square():
for i in range(4):
forward(100)
right(90)
The def command tells Python we’re defining a function, and the word we list afterward
will become the function name; here, it’s square(). Don’t forget the parentheses after
square! They’re a sign in Python that you’re dealing with a function. Later we’ll put
values inside them, but even without any values inside, the parentheses need to be
included to let Python know you are defining a function. Also, don’t forget the colon at
the end of the function definition. Note that we indent all the code inside the function
to let Python know which code goes inside it.
If you run this program now, nothing will happen. You’ve defined a function, but you
didn’t tell the program to run it yet. To do this, you need to call the function at the end
of the myturtle.py file after the function definition. Enter the code shown in Listing 11.
myturtle.py
from turtle import *
shape('turtle')
def square():
for i in range(4):
forward(100)
right(90)
square()
Listing 11: The square() function is called at the end of the file.
When you call square() at the end like this, the program should run properly. Now you
can use the square() function at any point later in the program to quickly draw another
square.
You can also use this function in a loop to build something more complicated. For
example, to draw a square, turn right a little, make another square, turn right a little,
and repeat those steps multiple times, putting the function inside a loop makes sense.
The next exercise shows an interestinglooking shape that’s made of squares! It might
take your turtle a while to create this shape, so you can speed it up by adding the speed()
function to myturtle.py after shape('turtle'). Using speed(0) makes the turtle move the
fastest, whereas speed(1) is the slowest. Try different speeds, like speed(5) and speed(10), if
you want.
EXERCISE 12: A CIRCLE OF SQUARES
Write and run a function that draws 60 squares, turning right 5 degrees after
each square. Use a loop! Your result should end up looking like this:
USING VARIABLES TO DRAW SHAPES
So far all our squares are the same size. To make squares of different sizes, we’ll need to
vary the distance the turtle walks forward for each side. Instead of changing the
definition for the square() function every time we want a different size, we can use a
variable, which in Python is a word that represents a value you can change. This is
similar to the way x in algebra can represent a value that can change in an equation.
In math class, variables are single letters, but in programming you can give a variable
any name you want! Like with functions, I suggest naming variables something
descriptive to make reading and understanding your code easier.
USING VARIABLES IN FUNCTIONS
When you define a function, you can use variables as the function’s parameters inside
the parentheses. For example, you can change your square() function definition in the
myturtle.py program to the following to create squares of any size rather than a fixed
size:
myturtle.py
def square(sidelength):
for i in range(4):
forward(sidelength)
right(90)
Here, we use sidelength to define the square() function. Now when you call this function,
you have to place a value, which we call an argument, inside the parentheses, and
whatever number is inside the parentheses will be used in place of sidelength. For
example, calling square(50) and square(80) would look like Figure 15.
Figure 15: A square of size 50 and a square of size 80
When you use a variable to define a function, you can simply call the square() function
by entering different numbers without having to update the function definition each
time.
VARIABLE ERRORS
At the moment, if we forget to put a value in the parentheses for the function, we’ll get
this error:
Traceback (most recent call last):
File "C:/Something/Something/my_turtle.py", line 12, in <module>
square()
TypeError: square() missing 1 required positional argument: 'sidelength'
This error tells us that we’re missing a value for sidelength, so Python doesn’t know how
big to make the square. To avoid this, we can give a default value for the length in the
first line of the function definition, like this:
def square(sidelength=100):
Here, we place a default value of 100 in sidelength. Now if we put a value in the
parentheses after square, it’ll make a square of that length, but if we leave the
parentheses empty, it’ll default to a square of sidelength 100 and won’t give us an error.
The updated code should produce the drawing shown in Figure 16:
square(50)
square(30)
square()
Figure 16: A default square of size 100, a square of size 50, and a square of size
30
Setting a default value like this makes it easier to use our function without having to
worry about getting errors if we do something wrong. In programming this is called
making the program more robust.
EXERCISE 13: TRI AND TRI AGAIN
Write a triangle() function that will draw a triangle of a given “side length.”
EQUILATERAL TRIANGLES
A polygon is a manysided figure. An equilateral triangle is a special type of polygon
that has three equal sides. Figure 17 shows what it looks like.
Figure 17: The angles in an equilateral triangle, including one external angle
An equilateral triangle has three equal internal angles of 60 degrees. Here’s a rule you
might remember from geometry class: all three angles of an equilateral triangle add up
to 180 degrees. In fact, this is true for all triangles, not just equilateral triangles.
WRITING THE TRIANGLE() FUNCTION
Let’s use what you’ve learned so far to write a function that makes the turtle walk in a
triangular path. Because each angle in an equilateral triangle is 60 degrees, you can
update the right() movement in your square() function to 60, like this:
myturtle.py
def triangle(sidelength=100):
for i in range(3):
forward(sidelength)
right(60)
triangle()
But when you save and run this program, you won’t get a triangle. Instead, you'll see
something like Figure 18.
Figure 18: A first attempt at drawing a triangle
That looks like we’re starting to draw a hexagon (a sixsided polygon), not a triangle.
We get a hexagon instead of a triangle because we entered 60 degrees, which is the
internal angle of an equilateral triangle. We need to enter the external angle to the
right() function instead, because the turtle turns the external angle, not the internal
angle. This wasn’t a problem with the square because it just so happens the internal
angle of a square and the external angle are the same: 90 degrees.
To find the external angle for a triangle, simply subtract the internal angle from 180.
This means the external angle of an equilateral triangle is 120 degrees. Update 60 in the
code to 120, and you should get a triangle.
EXERCISE 14: POLYGON FUNCTIONS
Write a function called polygon that takes an integer as an argument and
makes the turtle draw a polygon with that integer’s number of sides.
MAKING VARIABLES VARY
There’s more we can do with variables: we can automatically increase the variable by a
certain amount so that each time we run the function, the square is bigger than the last.
For example, using a length variable, we can make a square, then increase the length
variable a little before making the next square by incrementing the variable like this:
length = length + 5
As a math guy, this line of code didn’t make sense to me when I first saw it! How can
“length equal length + 5”? It’s not possible! But code isn’t an equation, and an equal
sign (=) in this case doesn’t mean “this side equals that side.” The equal sign in
programming means we’re assigning a value.
Take the following example. Open the Python shell and enter the following code:
>>> radius = 10
This means we’re creating a variable called radius (if there isn’t one already) and
assigning it the value 10. You can always assign a different value to it later, like this:
radius = 20
Press ENTER and your code will be executed. This means the value 20 will be assigned
to the radius variable. To check whether a variable is equal to something, use double
equal signs (==). For example, to check whether the value of the radius variable is 20, you
can enter this into the shell:
>>> radius == 20
Press ENTER and it should print the following:
True
Now the value of the radius variable is 20. It’s often useful to increment variables rather
than assign them number values manually. You can use a variable called count to count
how many times something happens in a program. It should start at 0 and go up by one
after every occurrence. To make a variable go up by one in value, you add 1 to its value
and then assign the new value to the variable, like this:
count = count + 1
You can also write this as follows to make the code more compact:
count += 1
This means “add 1 to my count variable.” You can use addition, subtraction,
multiplication, and division in this notation. Let’s see it in action by running this code
in the Python shell. We’ll assign x the value 12 and y the value 3, and then make x go up
by y:
>>> x = 12
>>> y = 3
>>> x += y
>>> x
15
>>> y
3
Notice y didn’t change. We can increment x using addition, subtraction, multiplication,
and division with similar notation:
>>> x += 2
>>> x
17
Now we’ll set x to one less than its current value:
>>> x -= 1
>>> x
16
We know that x is 16. Now let’s set x to two times its current value:
>>> x *= 2
>>> x
32
Finally, we can set x to a quarter of its value by dividing it by 4:
>>> x /= 4
>>> x
8.0
Now you know how to increment a variable using arithmetic operators followed by an
equal sign. In sum, x += 3 will make x go up by 3, whereas x -= 1 will make it go down by
1, and so on.
You can use the following line of code to make the length increment by 5 every loop,
which will come in handy in the next exercises:
length += 5
With this notation, every time the length variable is used, 5 is added to the value and
saved into the variable.
EXERCISE 15: TURTLE SP IRAL
Make a function to draw 60 squares, turning 5 degrees after each square
and making each successive square bigger. Start at a length of 5 and
increment 5 units every square. It should look like this:
SUMMARY
In this chapter you learned how to use Python’s turtle module and its builtin functions
like forward() and right() to draw different shapes. You also saw that the turtle can
perform many more functions than those we covered here. There are dozens more that
I encourage you to experiment with before moving on to the next chapter. If you do a
web search for “python turtle,” the first result will probably be the turtle module
documentation on the official Python website () website. You’ll find
all the turtle methods on that page, some of which is shown in Figure 19.
Figure 19: You can find many more turtle functions and methods on the Python
website!
You learned how to define your own functions, thus saving valuable code that can be
reused at any time. You also learned how to run code multiple times using for loops
without having to rewrite the code. Knowing how to save time and avoid mistakes using
functions and loops will be useful when you build more complicated math tools later
on.
In the next chapter we’ll build on the basic arithmetic operators you used to increment
variables. You’ll learn more about the basic operators and data types in Python and how
to use them to build simple computation tools. We’ll also explore how to store items in
lists and use indices to access list items.
EXERCISE 16: A STAR IS BORN
First, write a “star” function that will draw a fivepointed star, like this:
Next, write a function called starSpiral() that will draw a spiral of stars, like
this:
2
MAKING TEDIOUS ARITHMETIC FUN WITH LISTS AND
LOOPS
“You mean I have to go again tomorrow?” —Aidan Farrell after the first day of school
Most people think of doing arithmetic when they think of math: adding, subtracting,
multiplying, and dividing. Although doing arithmetic is pretty easy using calculators
and computers, it can still involve a lot of repetitive tasks. For example, to add 20
different numbers using a calculator, you have to enter the + operator 19 times!
In this chapter you learn how to automate some of the tedious parts of arithmetic using
Python. First, you learn about math operators and the different data types you can use
in Python. Then you learn how to store and calculate values using variables. You also
learn to use lists and loops to repeat code. Finally, you combine these programming
concepts to write functions that automatically perform complicated calculations for
you. You’ll see that Python can be a much more powerful calculator than any calculator
you can buy—and best of all, it’s free!
BASIC OPERATORS
Doing arithmetic in the interactive Python shell is easy: you just enter the expression
and press ENTER when you want to do the calculation. Table 21 shows some of the
most common mathematical operators.
istory
opics
utorials
Offers & Deals
ighlights
ettings
upport
Sign Out
mounir
Typewriter
Table 21: Common Mathematical Operators in Python
Operator Syntax
Addition +
Subtraction –
Multiplication *
Division /
Exponent **
Open your Python shell and try out some basic arithmetic with the example in Listing
21.
>>> 23 + 56 #Addition
79
>>> 45 * 89 #Multiplication is with an asterisk
4005
>>> 46 / 13 #Division is with a forward slash
3.5384615384615383
>>> 2 ** 4 #2 to the 4th power
16
Listing 21: Trying out some basic math operators
The answer should appear as the output. You can use spaces to make the code more
readable (6 + 5) or not (6+5), but it won’t make any difference to Python when you’re
doing arithmetic.
Keep in mind that division in Python 2 is a little tricky. For example, Python 2 will take
46/13 and think you’re interested only in integers, thus giving you a whole number (3)
for the answer instead of returning a decimal value, like in Listing 21. Because you
downloaded Python 3, you shouldn’t have that problem. But the graphics package we’ll
see later uses Python 2, so we’ll have to make sure we ask for decimals when we divide.
OPERATING ON VARIABLES
You can also use operators on variables. In Chapter 1 you learned to use variables when
defining a function. Like variables in algebra, variables in programming allow long,
complicated calculations to be broken into several stages by storing results that can be
used again later. Listing 22 shows how you can use variables to store numbers and
operate on them, no matter what their value is.
>>> x = 5
>>> x = x + 2
>>> length = 12
>>> x + length
19
Listing 22: Storing results in variables
Here, we assign the value 5 to the x variable, then increment it by 2, so x becomes 7. We
then assign the value 12 to the variable length. When we add x and length, we’re adding 7
+ 12, so the result is 19.
USING OPERATORS TO WRITE THE AVERAGE() FUNCTION
Let’s practice using operators to find the mean of a series of numbers. As you may know
from math class, to find the mean you add all the numbers together and divide them by
how many numbers there are in the series. For example, if your numbers are 10 and 20,
you add 10 and 20 and divide the sum by 2, as shown here:
(10 + 20) / 2 = 15
If your numbers are 9, 15, and 23, you add them together and divide the sum by 3:
(9 + 15 + 23) / 3 = 47 / 3 = 15.67
This can be tedious to do by hand but simple to do with code. Let’s start a Python file
called arithmetic.py and write a function to find the average of two numbers. You
should be able to run the function and give it two numbers as arguments, without any
operators, and have it print the average, like this:
>>> average(10,20)
15.0
Let’s give it a try.
MIND THE ORDER OF OPERATIONS!
Our average() function transforms two numbers, a and b, into half their sum and then
returns that value using the return keyword. Here’s the code for our function:
arithmetic.py
def average(a,b):
return a + b / 2
We define a function called average(), which requires two numbers, a and b, as inputs.
We write that the function should return the sum of the two numbers divided by 2.
However, when we test the function in the shell, we get the wrong output:
>>> average(10,20)
20.0
That’s because we didn’t take the order of operations into account when writing our
function. As you probably remember from math class, multiplication and division take
precedence over addition and subtraction, so in this case division is performed first.
This function is dividing b by 2 and then adding a. So how do we fix this?
USING PARENTHESES WITH OPERATORS
We need to use parentheses to tell Python to add the two numbers first, before dividing:
arithmetic.py
def average(a,b):
return (a + b) / 2
Now the function should add a and b before dividing by 2. Here’s what happens when
we run the function in the shell:
>>> average(10,20)
15.0
If you perform this same calculation by hand, you can see the output is correct! Try the
average() function using different numbers.
DATA TYPES IN PYTHON
Before we continue doing arithmetic on numbers, let’s explore some basic Python data
types. Different data types have different capabilities, and you can’t always perform the
same operations on all of them, so it’s important to know how each data type works.
INTEGERS AND FLOATS
Two Python data types you commonly perform operations on are integers and floats.
Integers are whole numbers. Floats are numbers containing decimals. You can change
integers to floats, and vice versa, by using the float() and int() functions, respectively,
like so:
>>> x = 3
>>> x
3
>>> y = float(x)
>>> y
3.0
>>> z = int(y)
>>> z
3
In this example we use x = 3 to assign the value 3 to the variable x. We then convert x
into a float using float(x) and assign the result (3.0) to the variable y. Finally, we convert
y into an integer and assign the result (3) to the variable z. This shows how you can
easily switch between floats and ints.
STRINGS
Strings are ordered alphanumeric characters, which can be a series of letters, like
words, or numbers. You define a string by enclosing the characters in single ('') or
double quotes (""), like so:
>>>>> a + a
'hellohello'
>>> 4*a
'hellohellohellohello'
Here, we store the string "hello" in variable a. When we add variable a to itself, we get a
new string, 'hellohello', which is a combination of two hellos. Keep in mind that you
can’t add strings and number data types (integers and floats) together, though. If you
try adding the integer 2 and the string "hello", you’ll get this error message:
>>> b = 2
>>> b
2
>>>>> b + d
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
b + d
TypeError: unsupported operand type(s) for +: 'int' and 'str'
However, if a number is a string (or enclosed in quotes), you can add it to another
string, like this:
>>>>>>> b + c
'1234'
>>> 'hello' + ' 123'
'hello 123'
In this example both '123' and '4' are strings made up of numbers, not number data
types. So when you add the two together you get a longer string ('1234') that is a
combination of the two strings. You can do the same with the strings 'hello' and ' 123',
even though one is made of letters and the other is made of numbers. Joining strings to
create a new string is called concatenation.
You can also multiply a string by an integer to repeat the string, like this:
>>>>> 3 * name
'MarciaMarciaMarcia'
But you can’t subtract, multiply, or divide a string by another string. Enter the following
in the shell to see what happens:
>>>>>>> noun * verb
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
noun * verb
TypeError: can't multiply sequence by nonint of type 'str'
As you can see, when you try to multiply 'dog' and 'bark', you get an error telling you
that you can’t multiply two string data types.
BOOLEANS
Booleans are true/false values, which means they can be only one or the other and
nothing in between. Boolean values have to be capitalized in Python and are often used
to compare the values of two things. To compare values you can use the greaterthan (>)
and lessthan (<) symbols, like so:
>>> 3 > 2
True
Because 3 is greater than 2, this expression returns True. But checking whether two
values are equal requires two equal signs (==), because one equal sign simply assigns a
value to a variable. Here’s an example of how this works:
>>> b = 5
>>> b == 5
True
>>> b == 6
False
First we assign the value 5 to variable b using one equal sign. Then we use two equal
signs to check whether b is equal to 5, which returns True.
CHECKING DATA TYPES
You can always check which data type you’re dealing with by using the type() function
with a variable. Python conveniently tells you what data type the value in the variable
is. For example, let’s assign a Boolean value to a variable, like this:
>>> a = True
>>> type(a)
<class 'bool'>
When you pass variable a into the type() function, Python tells you that the value in a is a
Boolean.
Try checking the data type of an integer:
>>> b = 2
>>> type(b)
<class 'int'>
The following checks whether 0.5 is a float:
>>> c = 0.5
>>> type(c)
<class 'float'>
This example confirms that alphanumeric symbols inside quotes are a string:
>>>>> type(name)
<class 'str'>
Now that you know the different data types in Python and how to check the data type of
a value you’re working with, let’s start automating simple arithmetic tasks.
USING LISTS TO STORE VALUES
So far we’ve used variables to hold a single value. A list is a type of variable that can
hold multiple values, which is useful for automating repetitive tasks. To declare a list in
Python, you simply create a name for the list, use the = command like you do with
variables, and then enclose the items you want to place in the list in square brackets, [],
separating each item using a comma, like this:
>>> a = [1,2,3]
>>> a
[1, 2, 3]
Often it’s useful to create an empty list so you can add values, such as numbers,
coordinates, and objects, to it later. To do this, just create the list as you would normally
but without any values, as shown here:
>>> b = []
>>> b
[]
This creates an empty list called b, which you can fill with different values. Let’s see how
to add things to a list.
ADDING ITEMS TO A LIST
To add an item to a list, use the append() function, as shown here:
>>> b.append(4)
>>> b
[4]
First, type the name of the list (b) you want to add to, followed by a period, and then use
append() to name the item you want to add inside parentheses. You can see the list now
contains just the number 4.
You can also add items to lists that aren’t empty, like this:
>>> b.append(5)
>>> b
[4, 5]
>>> b.append(True)
>>> b
[4, 5, True]
Items appended to an existing list appear at the end of the list. As you can see, your list
doesn’t have to be just numbers. Here, we append the Boolean value True to a list
containing the numbers 4 and 5.
A single list can hold more than one data type, too. For example, you can add text as
strings, as shown here:
>>> b.append("hello")
>>> b
[4, 5, True, 'hello']
To add a string, you need to include either double or single quotes around the text.
Otherwise, Python looks for a variable named hello, which may or may not exist, thus
causing an error or unexpected behavior. Now you have four items in list b: two
numbers, a Boolean value, and a string.
OPERATING ON LISTS
Like on strings, you can use addition and multiplication operators on lists, but you can’t
simply add a number and a list. Instead, you have to append it using concatenation.
For example, you can add two lists together using the + operator, like this:
>>> c = [7,True]
>>> d = [8,'Python']
>>> c + d #adding two lists
[7, True, 8, 'Python']
We can also multiply a list by a number, like this:
>>> 2 * d #multiplying a list by a number
[8, 'Python', 8, 'Python']
As you can see, multiplying the number 2 by list d doubles the number of items in the
original list.
But when we try to add a number and a list using the + operator, we get an error called
a TypeError:
>>> d + 2 #you can't add a list and an integer
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
d + 2
TypeError: can only concatenate list (not "int") to list
This is because you can’t add a number and a list using the addition symbol. Although
you can add two lists together, append an item to a list, and even multiply a list by a
number, you can concatenate a list only to another list.
REMOVING ITEMS FROM A LIST
Removing an item from a list is just as easy: you can use the remove() function with the
item you want to remove as the argument, as shown next. Make sure to refer to the item
you’re removing exactly as it appears in the code; otherwise, Python won’t understand
what to delete.
>>> b = [4,5,True,'hello']
>>> b.remove(5)
>>> b
[4, True, 'hello']
In this example, b.remove(5) removes 5 from the list, but notice that the rest of the items
stay in the same order. The fact that the order is maintained like this will become
important later.
USING LISTS IN LOOPS
Often in math you need to apply the same action to multiple numbers. For example, an
algebra book might define a function and ask you to plug a bunch of different numbers
into the function. You can do this in Python by storing the numbers in a list and then
using the for loop you learned about in Chapter 1 to perform the same action on each
item in the list. Remember, when you perform an action repeatedly, it’s known as
iterating. The iterator is the variable i in for i in range(10), which we’ve used in previous
programs, but it doesn’t always have to be called i; it can be called anything you want,
as in this example:
>>> a = [12,"apple",True,0.25]
>>> for thing in a:
print(thing)
12
apple
True
0.25
Here, the iterator is called thing and it’s applying the print() function to each item in the
list a. Notice that the items are printed in order, with each item on a new line. To print
everything on the same line, you need to add an end argument and an empty string to
your print() function, like this:
>>> for thing in a:
print(thing, end='')
12appleTrue0.25
This prints all the items on the same line, but all the values run together, making it hard
to distinguish between them. The default value for the end argument is the line break, as
you saw in the preceding example, but you can insert any character or punctuation you
want by putting it in the quotes. Here I’ve added a comma instead:
>>> a = [12,"apple",True,0.25]
>>> for thing in a:
print(thing, end=',')
12,apple,True,0.25,
Now each item is separated by a comma, which is much easier to read.
ACCESSING INDIVIDUAL ITEMS WITH LIST INDICES
You can refer to any element in a list by specifying the name of the list and then
entering its index in square brackets. The index is an item’s place or position number in
the list. The first index of a list is 0. An index enables us to use a meaningful name to
store a series of values and access them easily within our program. Try this code out in
IDLE to see indices in action:
>>> name_list = ['Abe','Bob','Chloe','Daphne']
>>> score_list = [55,63,72,54]
>>> print(name_list[0], score_list[0])
Abe 55
The index can also be a variable or an iterator, as shown here:
>>> n = 2
>>> print(name_list[n], score_list[n+1])
Chloe 54
>>> for i in range(4):
print(name_list[i], score_list[i])
Abe 55
Bob 63
Chloe 72
Daphne 54
ACCESSING INDEX AND VALUE WITH ENUMERATE()
To get both the index and the value of an item in a list, you can use a handy function
called enumerate(). Here’s how it works:
>>> name_list = ['Abe','Bob','Chloe','Daphne']
>>> for i, name in enumerate(name_list):
print(name,"has index",i)
Abe has index 0
Bob has index 1
Chloe has index 2
Daphne has index 3
Here, name is the value of the item in the list and i is the index. The important thing to
remember with enumerate() is that the index comes first, then the value. You’ll see this
later on when we put objects into a list and then access both an object and its exact
place in the list.
INDICES START AT ZERO
In Chapter 1 you learned that the range(n) function generates a sequence of numbers
starting with 0 and up to, but excluding, n. Similarly, list indices start at 0, not 1, so the
index of the first element is 0. Try the following to see how this works:
>>> b = [4,True,'hello']
>>> b[0]
4
>>> b[2]
'hello'
Here, we create a list called b and then ask Python to show us the item at index 0 in list
b, which is the first position. We therefore get 4. When we ask for the item in list b at
position 2, we get 'hello'.
ACCESSING A RANGE OF LIST ITEMS
You can use the range (:) syntax inside the brackets to access a range of elements in a
list. For example, to return everything from the second item of a list to the sixth, for
example, use the following syntax:
>>> myList = [1,2,3,4,5,6,7]
>>> myList[1:6]
[2, 3, 4, 5, 6]
It’s important to know that the 1:6 range syntax includes the first index in that range, 1,
but excludes the last index, 6. That means the range 1:6 actually gives us the items with
indexes 1 to 5.
If you don’t specify the ending index of the range, Python defaults to the length of the
list. It returns all elements, from the first index to the end of the list, by default. For
example, you can access everything from the second element of list b (index 1) to the
end of the list using the following syntax:
>>> b[1:]
[True, 'hello']
If you don’t specify the beginning, Python defaults to the first item in the list, and it
won’t include the ending index, as shown here:
>>> b[:1]
[4]
In this example, b[:1] includes the first item (index 0) but not the item with index 1. One
very useful thing to know is that you can access the last terms in a list even if you don’t
know how long it is by using negative numbers. To access the last item, you’d use -1,
and to access the secondtolast item, you’d use -2, like this:
>>> b[-1]
'hello'
>>> b[-2]
True
This can be really useful when you are using lists made by other people or using really
long lists where it’s hard to keep track of all the index positions.
FINDING OUT THE INDEX OF AN ITEM
If you know that a certain value is in the list but don’t know its index, you can find its
location by giving the list name, followed by the index function, and placing the value
you’re searching for as its argument inside parentheses. In the shell, create list c, as
shown here, and try the following:
>>> c = [1,2,3,'hello']
>>> c.index(1)
0
>>> c.index('hello')
3
>>> c.index(4)
Traceback (most recent call last):
File "<pyshell#85>", line 1, in <module>
b.index(4)
ValueError: 4 is not in list
You can see that asking for the value 1 returns the index 0, because it’s the first item in
the list. When you ask for the index of 'hello', you’re told it’s 3. That last attempt,
however, results in an error message. As you can see from the last line in the error
message, the cause of the error is that 4, the value we are looking for, is not in the list, so
Python can’t give us its index.
To check whether an item exists in a list, use the in keyword, like this:
>>> c = [1,2,3,'hello']
>>> 4 in c
False
>>> 3 in c
True
Here, Python returns True if an item is in the list and False if the item is not in the list.
STRINGS USE INDICES, TOO
Everything you’ve learned about list indices applies to strings, too. A string has a
length, and all the characters in the string are indexed. Enter the following in the shell
to see how this works:
>>>>> len(d) #How many characters are in 'Python'?
6
>>> d[0]
'P'
>>> d[1]
'y'
>>> d[-1]
'n'
>>> d[2:]
'thon'
>>> d[:5]
'Pytho'
>>> d[1:4]
'yth'
Here, you can see that the string 'Python' is made of six characters. Each character has
an index, which you can access using the same syntax you used for lists.
SUMMATION
When you’re adding a bunch of numbers inside a loop, it’s useful to keep track of the
running total of those numbers. Keeping a running total like this is an important math
concept called summation.
In math class you often see summation associated with a capital sigma, which is the
Greek letter S (for sum). The notation looks like this:
The summation notation means that you replace n with i starting at the minimum value
(listed below the sigma) and going up to the maximum value (listed above the sigma).
Unlike in Python’s range(n), the summation notation includes the maximum value.
CREATING THE RUNNING_SUM VARIABLE
To write a summation program in Python, we can create a variable called running_sum (sum
is taken already as a builtin Python function). We set it to a value of zero to begin with
and then increment the running_sum variable each time a value is added. For this we use
the += notation again. Enter the following in the shell to see an example:
>>> running_sum = 0
>>> running_sum += 3
>>> running_sum
3
>>> running_sum += 5
>>> running_sum
8
You learned how to use the += command as a shortcut: using running_sum += 3 is the same
as running_sum = running_sum + 3. Let’s increment the running sum by 3 a bunch of times to
test it out. To do this, add the following code to the arithmetic.py program:
arithmetic.py
running_sum = 0
➊ for i in range(10):
➋ running_sum += 3
print(running_sum)
We first create a running_sum variable with the value 0 and then run the for loop 10 times
using range(10) ➊. The indented content of the loop adds 3 to the value of running_sum on
each run of the loop ➋. After the loop runs 10 times, Python jumps to the final line of
code, which in this case is the print statement that displays the value of running_sum at the
end of 10 loops.
From this, you might be able to figure out what the final sum is, and here’s the output:
30
In other words, 10 multiplied by 3 is 30, so the output makes sense!
WRITING THE MYSUM() FUNCTION
Let’s expand our running sum program into a function called mySum(), which takes an
integer as a parameter and returns the sum of all the numbers from 1 up to the number
specified, like this:
>>> mySum(10)
55
First, we declare the value of the running sum and then increment it in the loop:
arithmetic.py
def mySum(num):
running_sum = 0
for i in range(1,num+1):
running_sum += i
return running_sum
To define the mySum() function, we start the running sum off at 0. Then we set up a range
of values for i, from 1 to num. Keep in mind that range(1,num) won’t include num itself! Then
we add i to the running sum after every loop. When the loop is finished, it should
return the value of the running sum.
Run the function with a much larger number in the shell. It should be able to return the
sum of all the numbers, from 1 to that number, in a flash:
>>> mySum(100)
5050
Pretty convenient! To solve for the sum of our more difficult sigma problem from
earlier, simply change your loop to go from 0 to 20 (including 20) and add the square of
i plus 1 every loop:
arithmetic.py
def mySum2(num):
running_sum = 0
for i in range(num+1):
running_sum += i**2 + 1
return running_sum
I changed the loop so it would start at 0, as the sigma notation indicates:
When we run this, we get the following:
>>> mySum2(20)
2891
EXERCISE 21: FINDING THE SUM
Find the sum of all the numbers from 1 to 100. How about from 1 to 1,000?
See a pattern?
FINDING THE AVERAGE OF A LIST OF NUMBERS
Now that you have a few new skills under your belt, let’s improve our average function.
We can write a function that uses lists to find the average of any list of numbers,
without us having to specify how many there are.
In math class you learn that to find the average of a bunch of numbers, you divide the
sum of those numbers by how many numbers there are. In Python you can use a
function called sum() to add up all the numbers in a list, like this:
>>> sum([8,11,15])
34
Now we just have to find out the number of items in the list. In the average() function we
wrote earlier in this chapter, we knew there were only two numbers. But what if there
are more? Fortunately, we can use the len() function to count the number of items in a
list. Here’s an example:
>>> len([8,11,15])
3
As you can see, you simply enter the function and pass the list as the argument. This
means that we can use both the sum() and len() functions to find the average of the items
in the list by dividing the sum of the list by the length of the list. Using these builtin
keywords, we can create a concise version of the average function, which would look
something like this:
arithmetic.py
def average3(numList):
return sum(numList)/len(numList)
When you call the function in the shell, you should get the following output:
>>> average3([8,11,15])
11.333333333333334
The good thing about this version of the average function is that it works for a short list
of numbers as well as for a long one!
EXERCISE 22: FINDING THE AVERAGE
Find the average of the numbers in the list below:
d = [53, 28, 54, 84, 65, 60, 22, 93, 62, 27, 16, 25, 74, 42, 4, 42,
15, 96, 11, 70, 83, 97, 75]
SUMMARY
In this chapter you learned about data types like integers, floats, and Booleans. You
learned to create a list, add and remove elements from a list, and find specific items in a
list using indices. Then you learned how to use loops, lists, and variables to solve
arithmetic problems, such as finding the average of a bunch of numbers and keeping a
running sum.
In the next chapter you’ll learn about conditionals, another important programming
concept you’ll need to learn to tackle the rest of this book.
3
GUESSING AND CHECKING WITH CONDITIONALS
“Put your dough into the oven when it is hot: After making sure that it is in fact
dough.” —Idries Shah, Learning How to Learn
In almost every program you write for this book, you’re going to instruct the computer
to make a decision. You can do this using an important programming tool called
conditionals. In programming we can use conditional statements
like “If this variable is more than 100, do this; otherwise, do that” to check whether
certain conditions are met and then determine what to do based on the result. In fact,
this is a very powerful method that we apply to big problems, and it’s even at the heart
of machine learning. At its most basic level, the program is guessing and then
modifying its guesses based on feedback.
In this chapter you learn how to apply the guessandcheck method using Python to
take user input and tell the program what to print depending on the input. You then use
conditionals to compare different numerical values in different mathematical situations
to make a turtle wander around the screen randomly. You also create a number
guessing game and use the same logic to find the square root of large numbers.
COMPARISON OPERATORS
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out
As you learned in Chapter 2, True and False (which we capitalize in Python) are called
Boolean values. Python returns Booleans when comparing two values, allowing you to
use the result to decide what to do next. For example, we can use comparison operators
like greater than (>) or less than (<) to compare two values, like this:
>>> 6 > 5
True
>>> 6 > 7
False
Here, we ask Python whether 6 is greater than 5, and Python returns True. Then we ask
whether 6 is greater than 7, and Python returns False.
Recall that in Python we use one equal sign to assign a value to a variable. But checking
for equality requires two equal signs (==), as shown here:
>>> 6 = 6
SyntaxError: can't assign to literal
>>> 6 == 6
True
As you can see, when we try to check using only one equal sign, we get a syntax error.
We can also use comparison operators to compare variables:
>>> y = 3
>>> x = 4
>>> y > x
False
>>> y < 10
True
We set the variable y to contain 3, and then set the variable x to contain 4. Then we use
those variables to ask whether y is greater than x, so Python returns False. Then we
asked whether y is less than 10, which returns True. This is how Python makes
comparisons.
MAKING DECISIONS WITH IF AND ELSE STATEMENTS
You can have your program make decisions about what code to run using if and else
statements. For example, if the condition you set turns out to be True, the program runs
one set of code. If the condition turns out to be False, you can write the program to do
something else or even do nothing at all. Here’s an example:
>>> y = 7
>>> if y > 5:
print("yes!")
yes!
Here, we are saying, assign variable y the value 7. If the value of y is more than 5, print
“yes!”; otherwise, do nothing.
You can also give your program alternative code to run using else and elif. Since we'll
be writing some longer code, open a new Python file and save it as conditionals.py.
conditionals.py
y = 6
if y > 7:
print("yes!")
else:
print("no!")
In this example we’re saying, if the value of y is more than 7, print “yes!”; otherwise,
print “no!”. Run this program, and it should print “no!” because 6 is not larger than 7.
You can add more alternatives using elif, which is short for “else if.” You can have as
many elif statements as you want. Here’s a sample program with three elif statements:
conditionals.py
age = 50
if age < 10:
print("What school do you go to?")
elif 11 < age < 20:
print("You're cool!")
elif 20 <= age < 30:
print("What job do you have?")
elif 30 <= age < 40:
print("Are you married?")
else:
print("Wow, you're old!")
This program runs different code depending on which of the specified ranges the value
of age falls into. Notice you can use <= for “less than or equal to” and you can use
compound inequalities like if 11 < age < 20: for “if age is between 11 and 20.” For
example, when age = 50, the output is the following string:
Wow, you're old!
Being able to have your programs make decisions quickly and automatically according
to the conditions you define is an important aspect of programming!
USING CONDITIONALS TO FIND FACTORS
Now let’s use what you’ve learned so far to factor a number! A factor is a number that
divides evenly into another number; for example, 5 is a factor of 10 because we can
divide 10 evenly by 5. In math class, we use factors to do everything from finding
common denominators to determining whether a number is prime. But finding factors
manually can be a tedious task involving a lot of trial and error, especially when you’re
working with bigger numbers. Let’s see how to automate factoring using Python.
In Python you can use the modulo operator (%) to calculate the remainder when
dividing two numbers. For example, if a % b equals zero, it means that b divides evenly
into a. Here’s an example of the modulo in action:
>>> 20 % 3
2
This shows that when you divide 20 by 3, you get a remainder of 2, which means that 3
is not a factor of 20. Let’s try 5 instead:
>>> 20 % 5
0
Now we get a remainder of zero, so we know that 5 is a factor of 20.
WRITING THE FACTORS.PY PROGRAM
Let’s use the modulo operator to write a function that takes a number and returns a list
of that number’s factors. Instead of just printing the factors, we’ll put them in a list so
we can use the factors list in another function later. Before we start writing this
program, it’s a good idea to lay out our plan. Here are the steps involved in the
factors.py program:
1. Define the factors function, which takes a number as an argument.
2. Create an empty factors list to fill with factors.
3. Loop over all the numbers from 1 to the given number.
4. If any of these numbers divides evenly, add it to the factors list.
5. Return the list of factors at the end.
Listing 31 shows the factors() function. Enter this code into a new file in IDLE and save
it as factors.py.
factors.py
def factors(num):
'''returns a list of the factors of num'''
factorList = []
for i in range(1,num+1):
if num % i == 0:
factorList.append(i)
return factorList
Listing 31: Writing the factors.py program
We first create an empty list called factorList, which we’ll later fill with the factors as we
find them. Then we start a loop, beginning with 1 (we can’t divide by zero) and ending
with num + 1, so that the loop will include num. Inside the loop we instruct the program to
make a decision: if num is divisible by the current value of i (if the remainder is 0), then
the program appends i to the factors list. Finally, we return the list of factors.
Now run factors.py by pressing the F5 key or by clicking Run ▸ Run Module, as
shown in Figure 31.
Figure 31: Running the factors.py module
After running this module, you can use the factors function in the normal IDLE
terminal by passing it a number you want to find the factors for, like this:
>>> factors(120)
[1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120]
You found all the factors of 120 using the factors function! This is much easier and
faster than using trial and error.
EXERCISE 31: FINDING THE FACTOR
The factors() function could come in handy for finding the greatest common
factor (GCF) of two numbers. Write a function that will return the GCF of two
numbers, like this:
>>> gcf(150,138)
6
THE WANDERING TURTLE
Now that you know how to instruct a program to make decisions automatically, let’s
explore how to let a program execute indefinitely! To start, we’ll make a turtle walk
around the screen and use conditionals to make it turn around if it goes beyond a
certain point.
The turtle’s window is a classic xy grid whose x and yaxes go from –300 to 300 by
default. Let’s limit the turtle’s position to anywhere between –200 and 200 for x and y,
as shown in Figure 32.
Figure 32: The rectangle of coordinates the turtle is limited to
Open a new Python file in IDLE and save it as wander.py. First, let’s import the turtle
module. To do so, add the following code:
from turtle import *
from random import randint
Note that we also need to import the randint function from the random module to
generate random integers.
Writing the wander.py Program
Now let’s create a function called wander to make the turtle wander around the screen, as
shown in Listing 32. To do this, we use Python’s infinite while True loop, which always
evaluates to True. This will make the turtle wander around without stopping. To stop it,
you can click the X on the turtle graphics window.
wander.py
speed(0)
def wander():
while True:
fd(3)
if xcor() >= 200 or xcor() <= 200 or ycor()<= 200 or ycor() >= 200:
lt(randint(90,180))
wander()
Listing 32: Writing the wander.py program
First, we set the turtle’s speed to 0, which is the fastest, and then define the wander()
function. Inside the function we use the infinite loop, so everything inside while True will
execute forever. Then the turtle goes forward three steps (or 3 pixels) and evaluates its
position using a conditional. The functions for the xcoordinate and ycoordinate of a
turtle are xcor() and ycor(), respectively.
Using the if statement, we tell the program that if any one of the conditional statements
is True (the turtle is outside the specified region), then make the turtle turn left a
random number of degrees, between 90 and 180, to prevent it from straying. If the
turtle is inside the rectangle, the conditional evaluates to False and no code is executed.
Either way, the program returns to the top of the while True loop and does fd(3) again.
Running the wander.py Program
When you run the wander.py program, you should see something like Figure 33.
Figure 33: The output of wander.py
As you can see, the turtle walks in a straight line until its xcoordinate gets to 200. (The
turtle always starts walking to the right in the positive xdirection.) Then it turns left a
random number of degrees, between 90 and 180, and keeps walking straight again.
Sometimes the turtle is able to walk outside of the boundary lines, because after the 90
degree turn it’s still pointed off the screen and you’ll see it turning around every loop,
trying to get back into the rectangle. This causes the little blobs outside the rectangle
you see in Figure 33.
CREATING A NUMBER-GUESSING GAME
CREATING A NUMBER-GUESSING GAME
You successfully used conditionals to create a turtle that seemed to make decisions on
its own! Let’s use conditionals to write an interactive numberguessing program that
seems conscious. In this game I think of a number between 1 and 100, and you guess
what the number is. How many guesses do you think you would need to guess my
number correctly? To narrow down your options, after each incorrect guess, I tell you
whether you should guess higher or lower. Fortunately, we can use the average function
we wrote in Chapter 2 to make this task infinitely easier.
When you make an incorrect guess, your next guess should depend on whether your
guess was too low or too high. For example, if your guess was too low, your next guess
should be the middle number between your last guess and the maximum value the
number can be. If your guess was too high, your next guess should be the middle
number between your last guess and the minimum value the number can be.
This sounds like calculating the average of two numbers—good thing we have the average
function! We’ll use it to write the numberGame.py program, which makes smart
guesses by narrowing down half the possible numbers every time. You’ll be surprised
how quickly you can hone in on the answer.
Let’s take this one step at a time, starting with making a random number generator.
MAKING A RANDOM NUMBER GENERATOR
First, we need the computer to choose a number at random between 1 and 100. Create a
new file in IDLE and save it as numberGame.py. Then enter the code in Listing 33.
number Game.py
from random import randint
def numberGame():
#choose a random number
#between 1 and 100
number = randint(1,100)
Listing 33: Writing the numberGame() function
Here, we import the random module and assign a random integer to a variable using the
randint() function. Then we create a number variable that will hold a random number
between 1 and 100, generated each time we call it.
TAKING USER INPUT
TAKING USER INPUT
Now the program needs to ask the user for input so they can take a guess! Here’s an
example you can enter into the interactive shell to see how the input() function works:
>>> name = input("What's your name? ")
What's your name?
The program prints the text “What’s your name?” in the shell, asking the user to input
their name. The user types something, presses ENTER, and the program saves the input.
We can check whether Python saves the user input to the name variable, like so:
What's your name? Peter
>>> print(name)
Peter
When we ask the program to print name, it prints the user input that was saved in that
variable (in this case, Peter).
We can create a function called greet() that we’ll use later in our program:
def greet():
name = input("What's your name? ")
print("Hello, ",name)
greet()
The output will be the following:
>>>
What's your name? Al
Hello, Al
>>>
Try writing a short program that takes the user’s name as input, and if they enter
“Peter,” it will print “That’s my name, too!” If the name is not “Peter,” it will just print
“Hello” and the name.
CONVERTING USER INPUT TO INTEGERS
CONVERTING USER INPUT TO INTEGERS
Now you know how to work with text that the user inputs, but we’ll be taking in number
inputs in our guessing game. In Chapter 2 you learned about basic data types, like
integers and floats, that you can use to perform math operations. In Python, all input
from users is always taken in as a string. This means that if we want numbers as inputs,
we have to convert them to an integer data type so we can use them in operations.
To convert a string to an integer, we pass the input to int(), like this:
print("I'm thinking of a number between 1 and 100.")
guess = int(input("What's your guess? "))
Now whatever the user enters will be transformed into an integer that Python can
operate on.
USING CONDITIONALS TO CHECK FOR A CORRECT GUESS
Now the numberGame.py program needs a way to check whether the number the user
guessed is correct. If it is, we’ll announce that the guess is right and the game is over.
Otherwise, we tell the user whether they should guess higher or lower.
We use the if statement to compare the input to the content of number, and we use elif
and else to decide what to do in each circumstance. Revise the existing code in
numberGame.py to look like the code in Listing 34.
number Game.py
from random import randint
def numberGame():
#choose a random number
#between 1 and 100
number = randint(1,100)
print("I'm thinking of a number between 1 and 100.")
guess = int(input("What's your guess? "))
if number == guess:
print("That's correct! The number was", number)
elif number > guess:
print("Nope. Higher.")
else:
print("Nope. Lower.")
numberGame()
Listing 34: Checking for a correct guess
If the random number held in number is equal to the input stored in guess, we tell the user
their guess was correct and print the random number. Otherwise, we tell the user
whether they need to guess higher or lower. If the number they guessed is lower than
the random number, we tell them to guess higher. If they guessed higher, we tell them
to guess lower.
Here’s an example of the output so far:
I'm thinking of a number between 1 and 100.
What's your guess? 50
Nope. Higher.
Pretty good, but currently our program ends here and doesn’t let the user make any
more guesses. We can use a loop to fix that.
USING A LOOP TO GUESS AGAIN!
To allow the user to guess again, we can make a loop so that the program keeps asking
for more guesses until the user guesses correctly. We use the while loop to keep looping
until guess is equal to number, and then the program will print a success message and
break out of the loop. Replace the code in Listing 34 with the code in Listing 35.
number Game.py
from random import randint
def numberGame():
#choose a random number
#between 1 and 100
number = randint(1,100)
print("I'm thinking of a number between 1 and 100.")
guess = int(input("What's your guess? "))
while guess:
if number == guess:
print("That's correct! The number was", number)
break
elif number > guess:
print("Nope. Higher.")
else:
print("Nope. Lower.")
guess = int(input("What's your guess? "))
numberGame()
Listing 35: Using a loop to allow the user to guess again
In this example, while guess means “while the variable guess contains a value.” First, we
check whether the random number it chose is equal to the guess. If it is, the program
prints that the guess is correct and breaks out of the loop. If the number is greater than
the guess, the program prompts the user to guess higher. Otherwise, it prints that the
user needs to guess lower. Then it takes in the next guess and the loop starts over,
allowing the user to guess as many times as needed to get the correct answer. Finally,
after we’re done defining the function, we write numberGame() to call the function to itself
so the program can run it.
TIPS FOR GUESSING
Save the numberGame.py program and run it. Each time you make an incorrect guess,
your next guess should be exactly halfway between your first guess and the closest end
of the range. For example, if you start by guessing 50 and the program tells you to guess
higher, your next guess would be halfway between 50 and 100 at the top of the range, so
you’d guess 75.
This is the most efficient way to arrive at the correct number, because for each guess
you’re eliminating half the possible numbers, no matter whether the guess is too high
or too low. Let’s see how many guesses it takes to guess a number between 1 and 100.
Figure 34 shows an example.
Figure 34: The output of the numberguessing game
This time it took six guesses.
Let’s see how many times you can multiply 100 by a half before you get to a number
below 1:
>>> 100*0.5
50.0
>>> 50*0.5
25.0
>>> 25*0.5
12.5
>>> 12.5*0.5
6.25
>>> 6.25*0.5
3.125
>>> 3.125*0.5
1.5625
>>> 1.5625*0.5
0.78125
It takes seven times to get to a number less than 1, so it makes sense that on average it
takes around six or seven tries to guess a number between 1 and 100. This is the result
of eliminating half the numbers in our range with every guess. This might not seem like
a useful strategy for anything but numberguessing games, but we can use this exact
idea to find a very accurate value for the square root of a number, which we’ll do next.
FINDING SQUARE ROOTS
You can use the numberguessing game strategy to approximate square roots. As you
know, some square roots can be whole numbers (the square root of 100 is 10, for
example). But many more are irrational numbers, which are neverending, never
repeating decimals. They come up a lot in coordinate geometry when you have to find
the roots of polynomials.
So how could we possibly use the numberguessing game strategy to find an accurate
value for a square root? You can simply use the averaging idea to calculate the square
root, correct to eight or nine decimal places. In fact, your calculator or computer uses
an iterative method like the numberguessing strategy to come up with square roots
that are correct to 10 decimal places!
APPLYING THE NUMBER-GUESSING GAME LOGIC
For example, let’s say you don’t know the square root of 60. First, you narrow your
options down to a range, like we did for the numberguessing game. You know that 7
squared is 49 and 8 squared is 64, so the square root of 60 must be between 7 and 8.
Using the average() function, you can calculate the average of 7 and 8 to get 7.5, which is
your first guess.
>>> average(7,8)
7.5
To check whether 7.5 is the correct guess, you can square 7.5 to see if it yields 60:
>>> 7.5**2
56.25
As you can see, 7.5 squared is 56.25. In our numberguessing game, we’d be told to
guess higher since 56.25 is lower than 60.
Because we have to guess higher, we know the square root of 60 has to be between 7.5
and 8, so we average those and plug in the new guess, like so:
>>> average(7.5, 8)
7.75
Now we check the square of 7.75 to see if it’s 60:
>>> 7.75**2
60.0625
Too high! So the square root must be between 7.5 and 7.75.
WRITING THE SQUAREROOT() FUNCTION
We can automate this process using the code in Listing 36. Open a new Python file and
name it squareRoot.py.
squareRoot.py
def average(a,b):
return (a + b)/2
def squareRoot(num,low,high):
'''Finds the square root of num by
playing the Number Guessing Game
strategy by guessing over the
range from "low" to "high"'''
for i in range(20):
guess = average(low,high)
if guess**2 == num:
print(guess)
elif guess**2 > num: #"Guess lower."
high = guess
else: #"Guess higher."
low = guess
print(guess)
squareRoot(60,7,8)
Listing 36: Writing the squareRoot() function
Here, the squareRoot() function takes three parameters: num (the number we want the
square root of), low (the lowest limit num can be), and high (the upper limit of num). If the
number you guess squared is equal to num, we just print it and break out of the loop. This
might happen for a whole number, but not for an irrational number. Remember,
irrational numbers never end!
Next, the program checks whether the number you guess squared is greater than num, in
which case you should guess lower. We shorten our range to go from low to the guess by
replacing high with the guess. The only other possibility is if the guess is too low, in
which case we shorten our range to go from the guess to high by replacing low with the
guess.
The program keeps repeating that process as many times as we want (in this case, 20
times) and then prints the approximate square root. Keep in mind that any decimal, no
matter how long, can only approximate an irrational number. But we can still get a very
good approximation!
In the final line we call the squareRoot() function, giving it the number we want the
square root of, and the low and high numbers in the range we know the square root has
to be in. Our output should look like this:
7.745966911315918
We can find out how close our approximation is by squaring it:
>>> 7.745966911315918**2
60.00000339120106
That’s pretty close to 60! Isn’t it surprising that we can calculate an irrational number
so accurately just by guessing and averaging?
EXERCISE 32: FINDING THE SQUARE ROOT
Find the square root of these numbers:
200
1000
50000 (Hint: you know the square root has to be somewhere
between 1 and 500, right?)
SUMMARY
In this chapter, you learned about some handy tools like arithmetic operators, lists,
inputs, and Booleans, as well as a crucial programming concept called conditionals. The
idea that we can get the computer to compare values and make choices for us
automatically, instantly, and repeatedly is extremely powerful. Every programming
language has a way to do this, and in Python we use if, elif, and else statements. As
you’ll see throughout this book, you’ll build on these tools to tackle meatier tasks to
explore math.
In the next chapter, you’ll practice the tools you learned so far to solve algebra
problems quickly and efficiently. You’ll use the numberguessing strategy to solve
complicated algebraic equations that have more than one solution! And you’ll write a
graphing program so you can better estimate the solutions to equations and make your
math explorations more visual!
PART 2
RIDING INTO MATH TERRITORY
ylists
tory
pics
torials
ers & Deals
ghlights
ttings
Support
Sign Out
4
TRANSFORMING AND STORING NUMBERS WITH ALGEBRA
“Mathematics may be defined as the subject in which we never know what we are
talking about, nor whether what we are saying is true.”
—Bertrand Russell
If you learned algebra in school, you’re probably familiar with the idea of replacing
numbers with letters. For example, you can write 2x where x is a placeholder that can
represent any number. So 2x represents the idea of multiplying two by some unknown
number. In math
class, variables become “mystery numbers” and you’re required to find what numbers
the letters represent. Figure 41 shows a student’s cheeky response to the problem
“Find x.”
Figure 41: Locating the x variable instead of solving for its value
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
upport
Sign Out
As you can see, this student has located the variable x in the diagram instead of solving
for its value. Algebra class is all about solving equations like this: solve 2x + 5 = 13. In
this context, “to solve” means to figure out which number, when you replace x with that
number, makes the equation true. You can solve algebra problems by balancing
equations, which requires a lot of rules you have to memorize and follow.
Using letters as placeholders in this way is just like using variables in Python. In fact,
you already learned how to use variables to store and calculate numerical values in
previous chapters. The important skill math students should learn is not solving for
variables but rather using variables. In fact, solving equations by hand is only of limited
value. In this chapter you use variables to write programs that find unknown values
quickly and automatically without having to balance equations! You also learn to use a
programming environment called Processing to graph functions to help you explore
algebra visually.
SOLVING FIRST-DEGREE EQUATIONS
One way to solve a simple equation like 2x + 5 = 13 with programming is by using brute
force (that is, plugging in random numbers until we find the right one). For this
particular equation we need to find a number, x, that when we multiply it by 2 and then
add 5, returns 13. I’ll make an educated guess that x is a value between −100 and 100,
since we’re working with mostly doubledigit numbers or lower.
This means that we can write a program that plugs all the integers between −100 and
100 into the equation, checks the output, and prints the number that makes the
equation true. Open a new file in IDLE, save it as plug.py, and enter the code in Listing
41 to see such a program in action.
def plug():
➊ x = 100 #start at 100
while x < 100: #go up to 100
➋ if 2*x + 5 == 13: #if it makes the equation true
print("x =",x) #print it out
➌ x += 1 #make x go up by 1 to test the next number
plug() #run the plug function
Listing 41: Bruteforce program that plugs in numbers to see which one satisfies the
equation
Here, we define the plug() function and initialize the x variable at -100 ➊. On the next
line we start a while loop that repeats until x equals 100, which is the upper limit of the
range we set. We then multiply x by 2 and add 5 ➋. If the output equals 13, we tell the
program to print the number, because that’s the solution. If the output does not equal
13, we tell the program to keep going through the code.
The loop then starts over, and the program tests the next number, which we get by
incrementing x by 1 ➌. We continue the loop until we hit a match. Be sure to include the
last line, which makes the program run the plug() function we just defined; if you don’t,
your program won’t do anything! The output should be this:
x = 4
Using the guessandcheck method is a perfectly valid way to solve this problem.
Plugging in all the digits by hand can be laborious, but using Python makes it a cinch! If
you suspect the solution isn’t an integer, you might have to increment by smaller
numbers by changing the line at ➌ to x += .25 or some other decimal value.
FINDING THE FORMULA FOR FIRST-DEGREE EQUATIONS
Another way to solve an equation like 2x + 5 = 13 is to find a general formula for this
type of equation. We can then use this formula to write a program in Python. You might
recall from math class that the equation 2x + 5 = 13 is an example of a firstdegree
equation, because the highest exponent a variable has in this equation is 1. And you
probably know that a number raised to the first power equals the number itself.
In fact, all firstdegree equations fit into this general formula: ax + b = cx + d, where a,
b, c, and d represent different numbers. Here are some examples of other firstdegree
equations:
On each side of the equal − 5 = 22, where
22 is the only term on the right side of the equal sign:
Using the general formula, you can see that a = 3, b = −5, equal sign by subtracting
cx and b from both sides of the equation, like this:
ax − cx = d − b
Then we can factor out the x from ax and cx:
x(a − c) = d − b
Finally, divide both sides by a − c to isolate x, which gives us the value of x in terms of a,
b, c, and d:
Now you can use this general equation to solve for any variable x when the equation is a
firstdegree equation and all coefficients (a, b, c, and d) are known. Let’s use this to
write a Python program that can solve firstdegree algebraic equations for us.
WRITING THE EQUATION() FUNCTION
To write a program that will take the four coefficients of the general equation and print
out the solution for x, open a new Python file in IDLE. Save it as algebra.py. We’ll write
a function that takes the four numbers a, b, c, and d as parameters and plug them into
the formula (see Listing 42).
def equation(a,b,c,d):
''''solves equations of the
form ax + b = cx + d''''
return (d b)/(a c)
Listing 42: Using programming to solve for x
Recall that the general formula of a firstdegree equation is this:
This means that for any equation with the form ax + b = cx + d, if we take the
coefficients and plug them into this formula, we can calculate the x value. First, we set
the equation() function to take the four coefficients as its parameters. Then we use the
expression (d - b)/(a − c) to represent the general equation.
Now let’s test our program with an equation you’ve already seen: 2x + 5 = 13. Open the
Python shell, type the following code at the >>> prompt, and press ENTER:
>>> equation(2,5,0,13)
4.0
If you input the coefficients of this equation into the function, you get 4 as the solution.
You can confirm that it’s correct by plugging in 4 in place of x. It works!
EXERCISE 41: SOLVING MORE EQUATIONS FOR X
Solve 12x + 18 = –34x + 67 using the program you wrote in Listing 42.
USING PRINT() INSTEAD OF RETURN
In Listing 42, we used return instead of print() to display our results. This is because
return gives us our result as a number that we can assign to a variable and then use
again. Listing 43 shows what would happen if we used print() instead of return to find x:
def equation(a,b,c,d):
''''solves equations of the
form ax + b = cx + d''''
print((d b)/(a − c))
Listing 43: Using print() doesn’t let us save the output
When you run this, you get the same output:
>>> x = equation(2,5,0,13)
4.0
>>> print(x)
None
But when you try to call the x value using print(), the program doesn’t recognize your
command because it hasn’t saved the result. As you can see, return can be more useful in
programming because it lets you save the output of a function so you can apply it
elsewhere. This is why we used return in Listing 42.
To see how you can work with the returned output, use the equation 12x + 18 = −34x +
67 from Exercise 41 and assign the result to the x variable, as shown here:
>>> x = equation(12,18,-34,67)
>>> x
1.065217391304348
First, we pass the coefficients and constants of our equation to the equation() function so
that it solves the equation for us and assigns the solution to the variable x. Then we can
simply enter x to see its value. Now that the variable x stores the solution, we can plug it
back into the equation to check that it’s the correct answer.
Enter the following to find out what 12x + 18, the left side of the equation, evaluates to:
>>> 12*x + 18
30.782608695652176
We get 30.782608695652176. Now enter the following to do the same for −34x + 67, the
right side of the equation:
>>> -34*x + 67
30.782608695652172
Except for a slight rounding discrepancy at the 15th decimal place, you can see that
both sides of the equation evaluate to around 30.782608. So we can be confident that
1.065217391304348 is indeed the correct solution for x! Good thing we returned the
solution and saved the value instead of just printing it out once. After all, who wants to
type in a number like 1.065217391304348 again and again?
EXERCISE 42: FRACT IONS AS COEFFICIENTS
Use the equation() function to solve the last, most sinisterlooking equation
you saw on page 55:
SOLVING HIGHER-DEGREE EQUATIONS
Now that you know how to write programs that solve for unknown values in first
degree equations, let’s try something harder. For example, things get a little more
complicated when an equation has a term raised to the second degree, like
x + 3x − 10 = 0. These are called quadratic equations, and their general form looks like
ax + bx + c = 0, where a, b, and c can be any number: positive or negative, whole
numbers, fractions, or decimals. The only exception is that a can’t be 0 because that
would make this a firstdegree equation. Unlike firstdegree equations, which have one
solution, quadratic equations have two possible solutions.
To solve an equation with a squared term, you can use the quadratic formula, which is
what you get when you isolate x by balancing the equation ax + bx + c = 0:
The quadratic formula is a very powerful tool for solving equations, because no matter
what a, b, and c are in ax + bx + c = 0, you can just plug them in to the formula and use
basic arithmetic to find your solutions.
We know that the coefficients of x + 3x − 10 = 0 are 1, 3, and −10. When we plug those
in to the formula, we get
Isolate x and this simplifies to
2
2
2
2
2
There are two solutions:
which is equal to 2, and
which is equal to −5.
We can see that replacing x in the quadratic formula with either of these solutions
makes the equation true:
(2) + 3(2) − 10 = 4 + 6 − 10 = 0
(−5) + 3(−5) − 10 = 25 − 15 − 10 = 0
Next, we’ll write a function that uses this formula to return two solutions for any
quadratic equation.
USING QUAD() TO SOLVE QUADRATIC EQUATIONS
Let’s say we want to use Python to solve the following quadratic equation:
2x + 7x − 15 = 0
To do this, we’ll write a function called quad() that takes the three coefficients (a, b, and
c) and returns two solutions. But before we do anything, we need to import the sqrt
method from the math module. The sqrt method allows us to find the square root of a
number in Python, just like a square root button on a calculator. It works great for
positive numbers, but if you try finding the square root of a negative number, you’ll see
an error like this:
>>> frommath importsqrt
>>> sqrt(-4)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
2
2
2
sqrt(4)
ValueError: math domain error
Open a new Python file in IDLE and name it polynomials.py. Add the following line to
the top of your file to import the sqrt function from the math module:
from math import sqrt
Then enter the code in Listing 44 to create the quad() function.
def quad(a,b,c):
''''Returns the solutions of an equation
of the form a*x**2 + b*x + c = 0''''
x1 = (b + sqrt(b**2 4*a*c))/(2*a)
x2 = (b sqrt(b**2 4*a*c))/(2*a)
return x1,x2
Listing 44: Using the quadratic formula to solve an equation
The quad() function takes the numbers a, b, and c as parameters and plugs them in to the
quadratic formula. We use x1 to assign the result of (the first solution), and x2 w
|
https://pt.b-ok.xyz/book/3679894/3740a4?dsource=recommend
|
CC-MAIN-2020-16
|
refinedweb
| 17,923 | 68.3 |
Conan: A Python package manager¶
Conan is a C and C++ package manager, and to deal with the vast variability of C and C++ build systems, compilers, configurations, etc., it was designed with a great flexibility in mind, trying to let the users do almost what they want. if we want to create a python package that wraps the functionality of, lets say the Poco C++ library, it can be easily done. Poco itself has transitive (C/C++) dependencies, but they are already handled by Conan. Furthermore, a very interesting thing is that nothing has to be done in advance for that library, thanks to useful tools as pybind11, that allows to create python bindings easily.
So let’s build a package with the following files:
- conanfile.py: The package recipe.
- __init__.py: necessary file, blank.
- pypoco.cpp: The C++ code with the
pybind11wrapper for Poco that generates a python extension (a shared library that can be imported from python).
- CMakeLists.txt: recipe for convenience straigthforward:
The conanfile.py has a few more lines than the above, but it is still quite easy to understand:
from conans import ConanFile, tools, CMake class PocoPyReuseConan(ConanFile): name = "PocoPy" version = "0.1" requires = "Poco/1.9.0@pocoproject/stable", "pybind11/any@memsharded, the Poco library and the pybind11 library that we will be using to create the binary
extension.
As we are actually building some C++ code, we need a few important things:
- Input
settingsthat define the OS, compiler, version and architecture we are using to build our extension. This is necessary because the binary we are building must match the architecture of the python interpreter that we will be using.
- The
build()method is used actually to invoke CMake. See we had to hardcode the python path in the example, as the CMakeLists.txt call to
find_package(PythonLibs)didn’t find my python installed in C:/Python27, quite a standard path. I have added the
cmakegenerator too to be able to easily use the declared
requiresbuild information inside my CMakeLists.txt.
- The CMakeLists.txt is not posted here, but is basically the one used in the pybind11 example with just 2 lines to include the conan generated cmake file build retrieve the dependencies and build the package. The next invocation will use the
cached binaries and be much faster. Note how we have to specify
-s arch=x86 to build matching the architecture of the python interpreter
to be used, in our case, 32 bits.
We can also read in the output of the conan install the dependencies that are being pulled:
Requirements OpenSSL/1.0.2l@conan/stable from conan.io Poco/1.9.0@pocoproject/stable from conan.io PocoPy/0.1@memsharded/testing from local pybind11/any@memsharded/stable from conan.io zlib/1.2.11@conan/stable from conan.io
This is the great thing about using Conan for this task, by depending on Poco, other C and C++ transitive dependencies are being retrieved and used in the application.
If you want to have a further look to the code of these examples, you can check this github repo. The above examples and code have been tested only in Win10, VS14u2, but might work with other configurations with little or no extra work.
|
https://docs.conan.io/en/1.3/howtos/other_languages_package_manager/python.html
|
CC-MAIN-2020-40
|
refinedweb
| 545 | 63.19 |
React Native Touch Through View
react-native-touch-through-view
React Native Touch Through View is a simple component library that allows for scroll views and table views to scroll over interactable content without poor performing size and bounds animations.
You can achieve Spotify or Apple maps style drawer effects with the full performance of UIScrollView and without laggy onScroll events.
Installation
Simply use
react-native link react-native-touch-through-view to add the library
to your project.
How to use it
- Import the library
import { TouchThroughView, TouchThroughWrapper } from 'react-native-touch-through-view';
- Wrap your ListView or ScrollView in the
<TouchThroughWrapper>element.
- Add
<TouchThroughView />elements wherever you want the users touch to be passed through to the view behind. You can style these views just like any other view and put them anywhere in the view you want.
eg.
// Markup for listview with a touch through header. <TouchThroughWrapper style={styles.scrollWrapper}> <ListView style={styles.scroller} dataSource={dataSource} renderHeader={() => <TouchThroughView style={styles.touchThroughView} />} renderRow={(rowData) => { return ( <View style={styles.itemRow}> <Text>{rowData}</Text> </View> ) }}> </ListView> </TouchThroughWrapper>
Have a look at the demo in the example directory if you need more help.
Issues
Currently we are working through an issue at #8 with Android devices on that latest version of React Native not properly passing through touch events.
|
https://reactnativeexample.com/react-native-touch-through-view/
|
CC-MAIN-2019-35
|
refinedweb
| 218 | 55.24 |
CHI - Unified cache handling interface
version 0.60);
CHI provides a unified caching API,..
If the item exists in cache (even if expired), place the CHI::CacheObject object in the provided SCALARREF..
Amount of time from now until this data expires. DURATION may be an integer number of seconds or a duration expression.
The epoch time at which the data expires..
Do a set, but only if $key is not valid in the cache.
Do a set, but only if $key is valid in the cache..
Remove all entries from the namespace.
CHI strives to accept arbitrary keys and values for caching regardless of the limitations of the underlying driver..
It is possible to a cache to have one or more subcaches. There are currently two types of subcaches: L1 and mirror..
CHI is intended as an evolution of DeWitt Clinton's Cache::Cache package. It starts with the same basic API (which has proven durable over time) but addresses some implementation shortcomings that cannot be fixed in Cache::Cache due to backward compatibility concerns. In particular:.
CHI handles its own serialization, passing a flat binary string to the underlying cache backend. The notable exception is CHI::Driver::RawMemory which does no serialization..
Jonathan Swartz <[email protected]>
This software is copyright (c) 2012 by Jonathan Swartz.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
|
http://search.cpan.org/~jswartz/CHI-0.60/lib/CHI.pm
|
CC-MAIN-2017-09
|
refinedweb
| 241 | 67.55 |
Unit Testing, Agile Development, Architecture, Team System & .NET - By Roy Osherove
Ads Via DevMavens
This post is a continuation of my Quest to test FxCop rules. The previous one was about writing pure unit tests for FxCop rules. This one is about writing Integration tests with a new framework I’ve developed called FxCopUnit.
For the past few days I’ve been struggling with FxCop – I’ve been Reflectoring the hell out of it (Reflector 5.0 is amazingly cool).
The purpose of all this fussing around is to create some sort of usable framework that would allow an easier testing experience for creating custom FxCop rules. I’ve already described how you can write real unit tests for custom FxCop rules here, but the framework I’m discussing here is meant for writing integration tests for FxCop rules . The main differences between the two is that integration tests usually take longer to run, harder to manage, need configuration and can’t be performed until the full (or at least some parts are full) system is in place.
Still, Integration testing has its advantages. For instance, the ability to realize that everything works together like clockwork. The analogy equivalent of Integration tests vs. unit tests for me (which I’m also using in my upcoming book) is that of a car’s engine. When you turn your key in the ignition, and the engine roars, you know all is well. Or maybe, you hear a slight noise from the engine. If you do, what’s the possibility that you’ll be able to recognize what the source of the problem is? That’s the classic integration test: all the parts work together as one single unit, and it’s just as hard to separate origins for problems – however- when they work, you know they work well together as a system. A unit test would test and run each of the engine parts on it’s own – easier to test, but you just won’t know the system really works until you get to that final system (integration) test.
Enough rambling.
I’ve used Sasha Goldstein’s code sample as a basis to create a more elaborate framework that will allow your custom rules to go through all the stages of running in FxCop, up to the XML report in the end. The main goals of the framework are:
The full downloads for this framework are available here:
In the full source download you’ll also find samples on how to use the framework but you’ll get a nice little 5 minute guide to it in both of them).
The FxCopUnit also uses an earlier framework I wrote called XtUnit which allows attaching custom attributes to tests which perform actions before or after the test. In this case I used it to create a custom attribute that initializes FxCop to the specified rules and types.
Here’s how you could write a simple Integration test for FxCop with FxCopUnit:
2. Create a new test fixture class
3. Inherit your class from FxCopTestFixture
Add the attribute to the top of the class to specify the location of your custom rules:
[TestFixture]
[FxCopCustomRuleLocation("TeamAgile.FxCopRuleTesting.SampleRules.dll")]
public class MytestsClass: FxCopTestFixture
{...}
4. Create a new test:
[Test]
[FxCopRuleToTest("Rule0001", "FxCopCustomRules.CustomRules",true)]
public void RunRuleAgainstMethod()
{
}
Note the FxCopRuleToTest attribute on the test. Specify the rule ID and Rule category as written in the Rule XML file manifest located inside your custom rules library (in the sample source it is RuleManifest.Xml – complied as Embedded resource).
The third parameter setup up FxCop engine so that the current test library will also be the main target to test the rules against.
Alternatively, you can specify the name of the target assembly to test against.
You can also specify the specific type that your rule will run against (all other types in the assembly will be ignored by the rules engine) .
Here’s a test that specifies a rule, and a specific method to test against.
It then tells FxCop to analyze the targets and does some simple asserts against the resulting FxCop report.
MethodInfo methodInfo = MethodBase.GetCurrentMethod() as MethodInfo;
FxRunner.EnableMethodToCheck(methodInfo);
FxRunner.Analyze();
FxReport.Assert.AtLeastOneAnalysisProblem();
Console.WriteLine(FxReport.Document.InnerXml);
The test uses two objects which are available once you inherit from FxCopTestFixture:
FxRunner:
Helper used to specify rules, types and other logic, as well as to start the analysis process by FxCop.
FxReport:
A report object that is generated only after calling FxRunner.Analyze(). It will be null before that.
Asserting against output:
Most of the asserts should be performed against the FxReport object, which already has a property named “Assert”. It is an AssertFxCop object which has some very simple asserts in it. It can be extended though- it’s a partial class. (so is the FxCopReport class)
FxCopUnit is very much work in progress. I wanted this out there so people can start using it and perhaps send me some interesting assert methods I can add built in to the current framework.
Your comments are appreciated.
PingBack from
|
http://weblogs.asp.net/rosherove/archive/2007/02/24/introducing-fxcopunit-a-framework-for-integrated-fxcop-rule-testing.aspx
|
crawl-002
|
refinedweb
| 849 | 62.07 |
and Entrepreneurship
As self-employment and entrepreneurship become increasingly important in our modern economies, Simon C. Parker provides a timely,
denitive and comprehensive overview of the eld. In this book he brings
together and assesses the large and disparate literature on these subjects and provides an up-to-date overview of new research ndings. Key
issues addressed include: the impact of ability, risk, personal characteristics and the macroeconomy on entrepreneurship; issues involved in raising nance for entrepreneurial ventures, with an emphasis on the market
failures that can arise as a consequence of asymmetric information; the
job creation performance of the self-employed; the growth, innovation
and exit behaviour of new ventures and small rms; and the appropriate role for governments interested in promoting self-employment and
entrepreneurship. This book will serve as an essential reference guide
to researchers, students and teachers of entrepreneurship in economics,
business and management and other related disciplines.
S I M O N C . P A R K E R is Professor and Head of Economics at the University of Durham. He is also Director of the Centre for Entrepreneurship
at Durham Business School. Professor Parker has published widely
in economics journals on a variety of issues on self-employment and
entrepreneurship.
The Economics of
Self-Employment and
Entrepreneurship
Simon C. Parker
Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, So Paulo
Cambridge University Press
The Edinburgh Building, Cambridge , UK
Published in the United States of America by Cambridge University Press, New York
Information on this title:
Simon C. Parker, 2004
This publication is in copyright. Subject to statutory exception and to the provision of
relevant collective licensing agreements, no reproduction of any part may take place
without the written permission of Cambridge University Press.
First published in print format 2004
-
-
-
-
---- hardback
--- hardback
For Lisa
Contents
List of Figures
List of Tables
Preface
Glossary of commonly used symbols
page xi
xii
xiii
xv
1 Introduction
1.1
1.2
1.3
1.4
1
2
3
5
8
9
12
12
14
14
18
20
24
24
26
27
29
31
37
2 Theories of entrepreneurship
39
39
43
43
46
54
61
64
65
vii
viii
Contents
68
68
68
70
74
74
74
75
76
83
84
86
86
94
99
102
106
107
113
114
115
120
123
124
124
126
129
129
132
135
137
139
140
142
150
154
156
158
159
160
165
165
165
167
Contents
6.1.3 Credit co-operatives, mutual guarantee schemes
and trade credit
6.2 Equity nance
6.2.1 Introduction
6.2.2 The scale of the equity nance market for
entrepreneurs
6.2.3 Factors affecting the availability of equity nance for
entrepreneurs
6.2.4 Equity rationing, funding gaps and under-investment
6.2.5 Policy recommendations
6.3 Conclusion
Notes
ix
169
171
171
171
173
174
176
177
178
179
180
180
181
182
183
183
186
189
191
193
193
193
194
197
197
204
206
208
208
213
213
215
216
218
218
220
222
227
229
IV Government policy
233
235
236
Contents
10.2
10.3
10.4
10.5
10.6
Notes
11 Conclusions
11.1 Summary
11.2 Implications for policy-makers
Note
References
Author index
Subject index
236
241
242
246
249
249
251
253
253
255
257
260
262
266
266
268
271
272
308
308
Figures
page 59
140
146
148
151
211
xi
Tables
xii
page 9
10
10
80
99
104
226
237
Preface
xiv
Preface
VARIABLES
a
A
, , , ,
b
B
BAD
c, c()
C
D
dz
e
E
E
()
()
f (), F()
g(), G()
g
= (, . . .)
hE
h S, h
H
I
IIN
k
xv
xvi
L
L
M, NM
n
nj
p
P
B
q
q (, . . .)
Q
r
rA
rR
R
Rf
Rs
s
s ch
S
2
j
t
T
Ti j , Ti j ()
u, v,
U()
V()
w, w E
wS
W, X, M
(), ()
x
x
xE
yj
ynj
zi
zi
xvii
INDEXES
i
j
OTHER SYMBOLS
(prime)
ABBREVIATIONS OF ORGANISATIONS
AND DATA-SETS
BHPS
CBO
CPS
FES
GHS
xviii
LFS
NCDS
NFIB
NLS
NLSY
OECD
PSID
SBA
SIPP
Introduction
The entrepreneur is at the same time one of the most intriguing and one of the
most elusive characters . . . in economic analysis. He has long been recognised as
the apex of the hierarchy that determines the behaviour of the firm and thereby
bears a heavy responsibility for the vitality of the free enterprise society. (Baumol,
1968, p. 64)
Self-employment is unquestionably the oldest way by which individuals offer and
sell their labour in a market economy. At an earlier time, it was also the primary
way. Despite this history, its principal features and the characteristics that differentiate self-employment from wage and salary employment have attracted the
attention of only a handful of students of the labour market. (Aronson, 1991, p. ix)
Introduction
The remainder of this chapter is organised as follows. Section 1.3 discusses issues in the definition and measurement of entrepreneurship and
Introduction
1.3
The problem of defining the word entrepreneur and establishing the boundaries
of the field of entrepreneurship still has not been solved. (Bruyat and Julien, 2001,
p. 166)
Introduction
goods of mainly one goods manufacturer also has limited discretion about
the nature of his or her business. And like other self-employed workers,
franchisees face uncertainty. In their case, not only is their income uncertain, but there is also a possibility that the franchisor will either go out
of business, or refuse to renew the franchise agreement at the expiration
of its term.8
Two other grey categories include unpaid family workers who work
in a business run by a self-employed person; and members of worker
co-operatives, who are not obviously either employees or self-employed
workers in the conventional sense of the term. Both groups tend to be
more numerous in developing than in developed countries, and in rural
than in urban areas. According to Bregger (1996, p. 5), Unpaid family
workers are persons who work on a family farm or in a family business
for at least 15 hours a week and who receive no earnings or share of
the profits of the enterprise. Blanchflower (2000) detected substantial
variation within developed countries in the proportion of self-employed
workers who are unpaid family workers, being as high as 33 per cent in
Japan, compared with 14 per cent in Italy and just 1.7 per cent in the USA.
As Blanchflower points out, it may not make sense just to discard unpaid
family workers from the self-employment count, since they often share
indirectly (e.g. via consuming household goods) the proceeds generated
by the business. Worker co-operatives are also relatively uncommon in the
UK, and tend to be larger and better established in European countries,
such as France, Italy and Spain (Spear, 1992).
Section 1.4 documents some international evidence on levels of, and
trends in, aggregate self-employment rates. At the aggregate level, it is
likely that alternative measures of self-employment are highly correlated
with each other, allowing trends within a given country to be identified
fairly reliably (Blau, 1987). However, to the extent that different countries
use different definitions of self-employment, cross-country comparisons
of levels have to be treated with caution.
1.4
There is great diversity in the level and time-series pattern of selfemployment rates across countries. This is evident from tables 1.1, 1.2 and
1.3, which summarise data for a selection of OECD countries, Eastern
European transition economies and developing countries, respectively.9
Two additional features of these tables stand out. One is that selfemployment rates are higher on average in developing than developed
countries. A second is that the treatment of agricultural workers makes
Introduction
1970
1980
1990
2000
13.83
18.81
22.68
34.25
15.86c
30.51
25.93
21.87
21.79
38.97
7.28
8.94
13.20
19.18
31.29
14.09
22.17
23.59
16.65
17.90
35.59
7.36
8.70
9.74
17.18
21.67
16.16
16.79
23.26
12.23
10.03
30.47
8.05
8.50
9.52
14.05
25.64
15.05
13.26
24.53
9.64
9.24
26.27
13.32
7.33
10.66
11.34
28.53
13.49
10.56
24.48
10.46d
7.03
20.49
11.34
6.94
8.33
14.44
25.20
10.00
12.71
18.97
12.02
8.61
21.55
6.27
7.26
7.05
13.75
14.33
12.73
10.71
19.20
9.06
6.53
20.63
7.11
7.51
7.40
11.50
19.89
12.34
9.32
22.24
7.84
6.12
20.69
12.41
6.55
9.46
9.35
25.48
11.72
8.06
23.21
9.25d
4.83
17.69
10.83
All workers
USA
Canadab
Japan
Mexico
Australia
Franceb
Italy
Netherlandsb
Norway
Spainb
UK
B
1960
Non-agricultural workers
USA
Canadab
Japan
Mexico
Australia
Franceb
Italy
Netherlandsb
Norway
Spainb
UK
10.45
10.17
17.38
23.01
11.01c
16.90
20.60
15.08
10.14
23.60
5.89
Notes: a Self-employment rates defined as employers plus persons working on their own
account, as a proportion of the total workforce.
b Includes unpaid family workers c 1964 not 1960 d 1999 not 2000.
Source: OECD Labour Force Statistics, issues 19802000, 197081 and 196071.
10
1980
1990
25.44
3.37
27.17
9.16
1992
1994
1998/99b
10.18
10.25
16.93
16.94
6.21
6.49
22.44
11.70
5.29
14.59
14.50
14.56
12.81
7.80
8.00
0.76
Notes: a Self-employment rates defined as employers plus persons working on their own
account, as a proportion of the total workforce.
b 1998/99 is 1998 for Poland and 1999 for the Russian Federation.
Source: UN Yearbook of Labour Statistics, various issues.
1970sb
1980sb
1990sb
13.03
29.19
10.30
26.14
n.a.
28.20
16.72
27.19
n.a.
20.78
44.79
42.97
48.86
17.10
29.44
37.81
40.27
21.80
36.46
37.27
34.81
24.70
37.11
37.03
7.33
44.04
21.94
26.94
29.83
45.56
33.92
46.90
22.90
29.65
38.83
33.07
55.95
24.74
29.75
29.59
28.02
48.18
26.68
28.45
Africa
Mauritius
Egypt
Americas
Bolivia
Costa Rica
Dominican Rep.
Ecuador
Asia
Bangladesh
Korean Rep.
Pakistan
Sri Lanka
Thailand
Notes: a Self-employment rates defined as employers plus persons working on their own
account, as a proportion of the total workforce. Includes agricultural workers.
b 1960s is either 1960, 1961, 1962 or 1963 for all countries; 1970s is some year between
1970 and 1976; 1980s is 1980 or 1981 except Ecuador (1982), Costa Rica (1984) and
Bolivia (1989); 1990s is some year between 1990 and 1996.
Source: UN Yearbook of Labour Statistics, various issues.
Introduction
11
However, if agricultural workers are excluded, table 1.1 shows that a revival in US self-employment occurred during the 1970s and 1980s, a
finding that has also been observed by some other authors.12 But unlike
these other authors, table 1.1 reveals that this revival in non-agricultural
US self-employment has apparently come to an end: by 2000 the nonagricultural self-employment rate had fallen back to below its 1970 level.
The US experience is mirrored by France, which has also seen its overall self-employment rate decline steadily since the start of the twentieth
century (Steinmetz and Wright, 1989).13 However, this trend is not observed in every OECD country. For example, table 1.1 shows that both
Canadian self-employment rates exhibited U-shaped patterns, increasing particularly strongly in the 1990s.14 In contrast, both measures of the
UK self-employment rate increased dramatically in the 1980s, a finding
that attracted substantial research interest when it was first discovered
(Hakim, 1988; Campbell and Daly, 1992). It declined in the 1990s, especially among males (Moralee, 1998). According to Storey (1994a), the
UK historical trend in self-employment was one of steady decline between 1910 and 1960, followed by increase from 1960 to 1990, with the
rate in 1990 being similar to that in 1910.
Most researchers tend to exclude agricultural workers from their definitions of self-employment, on the grounds that farm businesses have
very different characteristics to non-farm businesses. It has been known
at least since Kuznets (1966) that the agricultural sector tends to decline
as an economy develops and that this may distort self-employment
trends (Blanchflower, 2000). Consequently, to analyse trends we focus
henceforth on panel B of table 1.1. These data indicate a striking variety
of patterns over 19602000. Four countries (Japan, France, Norway and
Spain) had steadily declining self-employment rates. Six witnessed a revival in self-employment at some point within the period (USA, Canada,
Mexico, Italy, the UK and the Netherlands); and one (Australia) had a
relatively stable self-employment rate.
Finally, we will say a word about the relative importance of small firms
in the economy. The overwhelming majority of US businesses employ
fewer than five individuals (see, e.g. White, 1984; Brock and Evans, 1986,
chapter 2, for details). There are high rates of business formation and dissolution among small firms, especially in industries like retailing, where
low capital requirements make entry easy and keep profits modest. The
aggregate number of small businesses grew in the USA in the post-war
period, but their relative economic importance (measured in terms of
their employment share or share of gross domestic product (GDP)) declined somewhat over that period. The most recent evidence suggests that
the share of private non-farm GDP accounted for by small businesses in
12
the USA has now stabilised, at around 50 per cent over the last two
decades (SBA, 2002a). That the earlier decline was not greater is mainly
attributable to the growth of the service sector, in which small firms are
disproportionately concentrated. We will return to the issue of changing
industrial structure later in the book.
1.4.2
Developing countries
Introduction
13
14
1.5
This section attempts three tasks. First, we discuss issues relating to the
definition and measurement of self-employment incomes, and review evidence about the levels of and trends in average self-employment incomes
relative to average paid-employment incomes. Second, we analyse the inequality of self-employment incomes. Third, we review evidence from
earnings functions on the determinants of self-employment incomes.
1.5.1
Measurement issues
Self-employment income can be measured in several different ways. Consider the following identity:
Net profit Revenue Costs Draw + Retained earnings.
Net profit from running an enterprise is a widely used measure of selfemployment income. An alternative is Draw, the amount of money drawn
from the business on a regular basis by the owner. This represents the
consumption-generating value of the business and as such may be less
prone to income under-reporting. A less frequently used third measure
is Draw augmented by the growth in business equity (Hamilton, 2000).
It should be stressed at the outset that any analysis of self-employment
income data should be performed with the utmost caution. There are
several reasons for this:
1. Income under-reporting by the self-employed. This is possibly the most serious problem with using self-employment data. It is partly attributable
to self-employed respondents who over-claim business tax deductions,
or under-report gross incomes to the tax authorities, mistrusting interviewers claims that they are truly independent of the tax inspectorate.
Ways of estimating self-employment income under-reporting rates are
discussed in chapter 10, subsection 10.4.1.
2. Different ways of treating owners of incorporated businesses. Incorporated
self-employed individuals are usually treated as employees of their
company. Because they are richer on average, their exclusion from
the self-employed sample may bias downwards the average income of
the self-employed.20 On the other hand, including the incorporated
self-employed is not without its problems, since it is not clear how to
interpret the salary that an incorporated self-employed business owner
chooses to pay her/himself.
3. Relatively high non-response rates to survey income questions by the selfemployed. This problem can be quite pervasive and can substantially
bias estimates of absolute and relative returns to self-employment
Introduction
15
(Devine, 1995).21 There are several possible reasons for survey nonresponse. One is mistrust of survey interviewers by self-employed respondents, for the reasons given above. A second is that richer people
(of whom a disproportionate number are self-employed see below)
have a higher marginal valuation of time, so participate less in surveys. Third, many self-employed do not accurately know their incomes,
which according to Meager, Court and Moralee (1994) accounted for
two-thirds of missing British income cases in the 1991 British Household Panel Survey (BHPS) rather than refusal to co-operate with the
survey.
4. A failure to deal properly with negative incomes and top-coding can introduce biases (Devine, 1995). Many researchers either drop negative
income observations or round them up to a small positive number
before applying logarithmic transformations; both practices impart an
upward bias to average self-employment income. Top-coding on the
other hand, which is a procedure of truncating very high earnings values to a maximum level, imparts a downward bias.
5. Ignoring employee fringe benefits that are unavailable in self-employment biases upwards any relative income advantage to self-employment. Some
of these benefits can be substantial, especially employer contributions
to health care and occupational pension schemes (Holtz-Eakin, Penrod
and Rosen 1996; Wellington, 2001).
6. Self-employment incomes include returns to capital as well as returns to
labour. National Accounts experts have long argued about how best
to disentangle these returns, which might explain why few researchers
choose to separate them in practice.22 Headen (1990) proposed an
especially straightforward approach, which works as follows. Let h j ,
y j and w j denote an individuals work hours, total labour income
and wage rate respectively in sector j = {E, S }, where E is paidemployment and S is self-employment. Also, let yk denote returns
to capital in self-employment. While h j and y j values are observed
in most data sets, w j s are not and must be calculated (in E) or estimated (in S ). We have yE = w E h E and yS = w Sh S + yk . To estimate
yk , first calculate w E = yE / h E and estimate an earnings function like
ln w E = X + u, where X is a vector of personal characteristics, is
a vector of coefficients and u is a random disturbance (see chapter 1,
Second, predict
subsection 1.5.3). This yields parameter estimates .
w S for the self-employed from ln
w S = X. This can be taken as the
return to self-employed labour assuming (i) that employee incomes
are purely returns to labour, and (ii) that the self-employed have the
same rates of return to personal characteristics as employees do (see
subsection 1.5.3 for a critical assessment of this assumption). Finally,
16
Introduction
17
Conversely, however, Hamilton may have over-stated the income differential by ignoring the possibility of income under-reporting and business
tax deduction opportunities for the self-employed.
There is also evidence that US median incomes in self-employment
have lagged behind median employee incomes for several decades
(Carrington, McCue and Pierce, 1996: Current Population Survey
(CPS) data, 196792).24 Aronson (1991: US Social Security data, 1951
88) showed that a 48 per cent income advantage to the self-employed in
19514 had dwindled to a 23 per cent advantage by 19759. This became a 10 per cent disadvantage by 19804, widening to a 20 per cent
disadvantage by 19858. It appears that a similar story holds irrespective
of occupation and education (SBA, 1986); and adjusting for the longer
average work hours of the self-employed reduced further their relative
income position by around 70 per cent according to Aronson (1991).
The UK has also witnessed a downward trend in relative average
self-employment incomes since the 1970s (Robson, 1997; Clark and
Drinkwater, 1998).25 In contrast to the USA, the UK evidence points to a
relative income advantage to self-employment. Disagreement centres on
how large this advantage is. General Household Survey (GHS) microdata point suggests a small premium to self-employment of 7 per cent
over 198395, according to Clark and Drinkwater (1998) (see also
Meager, Court and Moralee, 1996). In contrast, aggregate UK National
Accounts data suggest a greater difference, of 35 per cent in terms of
pre-tax gross income in 1993 according to Robson (1997). It may be relevant that the latter, unlike the former estimate, includes an adjustment
for income under-reporting by the self-employed.
Evidence from eleven OECD countries supports the notion that in
many countries the self-employed are not well remunerated relative to employees. According to OECD (1986), only in West Germany did the ratio
of median self-employment to paid-employment incomes exceed unity.
In Finland, Sweden and Japan the ratios were below that of the USA.
Similar evidence was also found independently by Covick (1983) and
Kidd (1993) for Australia; and Covick noted the same downward trend
in relative self-employment incomes as observed in the USA and the UK.
The special circumstances prevailing in the transition economies of
Eastern Europe may help explain why opposite findings have been found
there. Earle and Sakova (2000) studied self-employment choices and
incomes in six Eastern European countries between 1988 and 1993:
Poland, Russia, Slovakia, Bulgaria, Hungary and the Czech Republic.
They found that, in all countries apart from Poland, the mean income of
employees was less than that of own-account self-employed individuals,
which in turn was less than the mean income of self-employed employers.
18
We conclude this section with three puzzles. One is why, if the selfemployed in the USA earn less on average than employees do, and if they
are only moderately older on average than employees are, they nevertheless possess substantially greater savings and asset holdings (Quadrini,
1999; Gentry and Hubbard, 2001). A second puzzle is why individuals
remain in self-employment despite apparently earning less and working longer hours (see chapter 8, section 8.2) than employees do. Third,
why do entrepreneurs invest in undiversified and hence risky private businesses, when they could obtain similar rates of return from less risky publicly traded equity (Moskowitz and Vissing-Jrgensen, 2002)? A possible
answer to the first puzzle is income (but not asset) under-reporting by the
self-employed, reflecting the greater taxation of income than wealth. A
tentative answer to the second puzzle is proposed in section 8.2. Possible
answers to the third include non-pecuniary benefits to entrepreneurship,
a preference for skewed returns and systematic over-estimation by entrepreneurs of the probability of survival and success in entrepreneurship.
1.5.2
Income inequality
It is now well established that in most countries the incomes of the selfemployed are more unequal than employees are. This fact usually becomes immediately obvious when histograms of incomes are graphed separately for the two groups.26 Relatively large numbers of the self-employed
are concentrated in the lower and upper tails of their income distribution,
compared with employees. Consequently, when data from the two occupations are combined, the self-employed are invariably observed to be
disproportionately concentrated in both the upper and lower tails of the
overall income distribution. In their British analysis based on 1991 BHPS
data, Meager, Court and Moralee (1996) showed that this result is not an
artefact of sampling error, and remained after controlling for observable
characteristics such as gender, work status, work hours, age, education,
industry and occupation.27
The same story of pronounced self-employment income inequality is
observed when sample data are mapped into scalar inequality measures,
such as the Gini coefficient or the mean log deviation.28 Typical results
were obtained by Parker (1999b), who computed a range of inequality
measures from UK Family Expenditure Survey (FES) data over 1979
1994/5. Parker reported that self-employment income inequality indices
were between two and five times as great as those for employees, depending on the year and the particular inequality index chosen.29 Arguably the
UK context is particularly interesting because self-employment income
inequality grew especially rapidly in the 1980s, the same decade when
Introduction
19
20
results (e.g. compare Mayer, 1975 with Bland, Elliott and Bechhofer,
1978).
Finally, we mention for completeness that even less is known about
the wealth distribution of entrepreneurs. Although there are models of
entrepreneuria wealth transfers and accumulation (Shorrocks, 1988;
Banerjee and Newman, 1993; Parker, 2000), none explains why wealth
distribution takes its observed shape. According to estimates compiled by
Parker (2003b), older self-employed Britons enjoy above-average wealth
holdings, yet only moderate wealth inequality.
1.5.3
Earnings functions
Methods
In this subsection we ask whether it is possible to explain individuals
self-employment incomes in terms of a few personal and economic variables. The most popular method for attempting this is estimation of a socalled earnings function. Earnings functions were originally developed
by human capital theorists to explain the determinants of employment
earnings. An earnings function typically regresses log earnings, ln y, on
a set of explanatory variables that includes age or experience, a, years of
education, s ch and a vector of other personal and family characteristics,
X. Let u be a stochastic disturbance term, and index individuals by i in
a sample of size n. Employee earnings functions typically take the form
ln yi = 0 + 1 ai + 2 ai2 + 3 s chi + Xi + ui
i = 1, . . . , n ,
(1.1)
where the s and are coefficients. The 3 coefficient measures the rate
of return to an extra year of education, and for this reason is of particular
interest to human capital theorists.
In principle, it is a straightforward matter to estimate (1.1) using a
sample of self-employed individuals. However, there are several reasons
why one would expect the coefficients of (1.1), and their interpretation,
to differ from those obtained using employee samples.
First, the self-employed rate of return to schooling may differ from
employees rate of return. On one hand, entrepreneurial success is likely
to depend on numerous factors other than formal education, implying
that the self-employed 3 will be low relative to its value for employees
(Brown and Sessions, 1998, 1999). Indeed, formal education might
even inculcate attitudes that are antithetical to entrepreneurship (Casson,
2003). On the other hand, if employers demand education from their
workers primarily as an otherwise unproductive screening device (the
screening hypothesis), then the self-employed who do not face this
Introduction
21
(1.2)
(as in, e.g. Amit, Muller and Cockburn, 1995), where zi is an indicator
(dummy) variable for self-employment/paid-employment status. While
(1.2) looks attractive by providing a direct estimate of relative occupational earnings advantage, it imposes the strong restrictions of identical
rates of return to all of the explanatory variables for both occupations,
which, for the reasons given above, are unlikely to hold.
When estimating earnings functions, it is necessary to avoid selection
bias. Incomes are observed only in the occupation that individuals choose
to participate in; and those who participate in self-employment might
not be a random sample from the population. Rather, they might possess characteristics that make them particularly favourably disposed to
self-employment. Without correcting for this, the estimated coefficients
of (1.1) will be susceptible to bias. By correcting for this bias, it becomes
possible to ask whether self-employed people (and employees) could improve their lot by switching into the other occupation. A popular practical
way of removing selection bias is Heckmans (1979) method.
22
Heckmans method comprises two steps. The first step estimates the
participation equation
zi = Wi + vi ,
(1.3)
(1.4)
Introduction
23
(1.5)
24
where i is the proportion of work hours i devotes to S; the s are vectors of coefficients; and the Xs are matrices of observations on personal
and occupation-relevant characteristics. Because i may be endogenously
chosen, (1.5) can be estimated only after an equation for i is specified
on a set of exogenous variables. This permits direct comparison of the
two occupations coefficients.
1.6
(1.6)
(1.7)
(1.8)
Introduction
25
Non-linear methods are needed to maximise (1.9) to estimate the parameters (up to a scalar transformation since is unknown). It is standard
to normalise 2 to unity without loss of generality.
The logit model arises if the distribution function of vi is assumed to
be that of the logistic distribution, in which case (1.8) becomes
Pr(zi = 1) =
exp{ Wi }
.
1 + exp{ Wi }
(1.10)
26
Microeconomic theory teaches us that relative prices often affect individual choices. If this precept is true for occupational choice, then one of the
explanatory variables in the matrix W above should be relative income, or
its logarithm: (ln yi S ln yi E ). However, we know from subsection 1.5.3
that occupational incomes are endogenous, and prone to selection effects, so this information needs to be incorporated into the probit model
to obtain efficient and unbiased estimates of the parameters of interest.
The structural probit model is a popular method that accomplishes this.
The first stage of the structural probit model is to estimate selectivitycorrected earnings functions separately for the self-employed and
employees. Extending the discussion in subsection 1.5.3, and letting M
denote the vector of explanatory variables used in the earnings functions,
one estimates the equations
zi = Wi + vi
[ln yi S|zi = 1] =
S Mi
i {S, E}
+ Si S + ui S
[ln yi E |zi = 0] = E Mi + E i E + ui E
(1.12)
iS
i E,
(1.13)
(1.14)
where i S = (zi )/(zi ) and i E = (zi )/[1 (zi )] are the Inverse
Mills Ratios to correct for selectivity into each occupation. Equation (1.12) is called the reduced form probit and is not of direct interest:
its principal role is to correct for selection bias in the earnings functions
(1.13) and (1.14).
Introduction
27
The second stage of the structural probit model generates the predicted log incomes from both occupations derived from (1.13) and (1.14),
namely ln
yi S and ln
yi E . The third stage estimates the structural probit
model
zi = [ln
yi S ln
yi E ] + Xi + vi ,
(1.15)
While the models described above are widely used and appropriate for
most applications, it is sometimes necessary to extend them. We describe
three extensions below.
First, although individuals may wish to become self-employed, they
may not have the opportunity to do so. This motivates the use of the bivariate probit (BVP) model, which separates individuals opportunities to
variable representing the former effect and let z2i represent the latter effect. Potentially different factors impinge on willingness and opportunity,
suggesting the specifications
z1i
= 1 W1i + v1i
(1.16)
z2i
(1.17)
2 W2i
+ v2i ,
28
where (v1i , v2i ) are distributed as bivariate normal variates with correlation coefficient : the joint distribution function is (, ; ). As before,
define zi as an indicator variable, equal to 1 if individual i becomes selfemployed, and 0 otherwise. Evidently
Pr(zi = 1) = Pr[min(z1i
, z2i
) 0] = (1 W1i , 2 W2i ; ) ,
n
i =1
(1.18)
Introduction
29
if hiE 1
1
0
if hiE 0
hiE = Xi + ui .
This model can be estimated by double-limit tobit maximum likelihood
(see Vijverberg, 1986, for details). However, in the light of the discussion
in subsection 1.6.2, a limitation of this model is its omission of relative occupational returns from the set of explanatory variables, X. Incorporating
this extension into (1.19) can be expected to complicate the estimation
substantially which may account for its absence from the applied entrepreneurship literature to date.
1.6.4
t = 1, . . . , T ,
(1.20)
30
(1.21)
where is an intercept common to all individuals. A more general specification allows the intercept to vary across individuals, giving rise to the
fixed-effects model:
s i t = Xi t + i + vi t .
(1.22)
Introduction
31
(1.23)
1. Of course, these types of surveys can be severely criticised for asking hypothetical questions, without forcing individuals to bear the constraints of
self-employment as they would if they acted upon their declared preferences.
Indeed, much lower rates of serious entrepreneurial intention emerge from
longitudinal analysis of wage and salary workers (Katz, 1990). For this reason,
we will often adopt in this book the standard economic practice of ignoring
studies that report interviewees declared preferences, focusing instead on revealed preferences.
2. Intrapreneurship the practice of entrepreneurship within corporations is
an emerging field in economics. For an important recent contribution, see
Gromb and Scharfstein (2002).
3. According to CPS data compiled by Bregger (1996), 38 per cent of selfemployed Americans run incorporated businesses. These tend to be businesses
that employ others, which might explain why incorporation rates among new
(and typically small) entrants to self-employment are about half this rate (Evans
and Jovanovic, 1989).
4. Harvey (1995) cites the UK legal case of Young and Woods v. West, whereby
the criteria for a worker being under a contract of service includes the worker
not determining their own hours, not supplying their own materials and equipment, not allocating or designating their own work, not being able to nominate
a substitute to work in their place and not setting their rate of pay (see also
Leighton, 1983).
5. See also Marsh, Heady and Matheson (1981), Casey and Creigh (1988) and
Hakim (1988).
32
6. Firms certainly appear to exercise some discretion about the mode of employment contract they offer. For example, in her exploration of new laws
penalising companies that misclassify employees as self-employed to avoid
tax payments, Moralee (1998) found that in response to the new laws the
number of employees in the construction industry increased sharply while
the number of self-employed workers decreased sharply.
7. According to Moralee (1998), 13 per cent of the UK self-employed in 1997
were home-workers, with little change in self-employed home-working taking
place over the 1990s. Moralee also observed that 61 per cent of teleworkers
were self-employed.
8. Williams (2001) argued that franchisees take less risk than independent selfemployed business owners, because of profit sharing arrangements with franchisors and lower demand uncertainty resulting from selling a known product. Williams also observed a lower variance of self-employment incomes
among franchisees than non-franchisees in his 1987 CBO sample of full-time
self-employed workers. However, he appears to over-state the case, not least
because exit rates are higher among franchisees than independent business
owners (Bates, 1994).
9. Data limitations can be quite severe, especially for developing and transition
economies. They largely determined the countries selected, and account for
the exclusion of Germany in particular.
10. The primary source for the US entries in table 1.1 is the CPS Monthly Household Labour Force Survey.
11. In his historical study, Phillips (1962) characterised US self-employment as
a shrinking world within a growing economy. Phillips predicted that selfemployment would eventually serve as a refuge only for older, handicapped
or unproductive workers as a safeguard against unemployment.
12. See Blau (1987), Steinmetz and Wright (1989), Aronson (1991), Bregger
(1996) and Williams (2000).
13. See also Kuznets (1966, table 4.2) who documented declining selfemployment shares between the mid-nineteenth and mid-twentieth century
in Germany, Switzerland, Canada and the UK, as well as in the USA and
France.
14. See also Lin, Picot and Compton (2000), Manser and Picot (2000), Kuhn
and Schuetze (2001) and Moore and Mueller (2002). Self-employment accounted for most overall job growth in Canada in the 1990s, which was concentrated among own-account workers.
15. Agriculture was never fully collectivised in Poland, which accounts for its high
rate of self-employment for all workers inclusive of agriculture.
16. According to Blanchflower, Oswald and Stutzer (2001), Poles topped the
list of respondents to a survey of 25,000 people in twenty-three countries
asking whether they would prefer to be self-employed to being a wage worker:
80 per cent responded in the affirmative. Blanchflower, Oswald and Stutzer
concluded that there is no shortage of potential entrepreneurs in the transition
economies.
17. For further discussion about the state of entrepreneurship in Eastern Europe,
see OECD (1998, ch. XIII) and Smallbone and Welter (2001). Tyson, Petrin
and Rogers (1994) and Luthans, Stajkovic and Ibrayeva (2000) describe the
Introduction
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
33
34
28.
29.
30.
31.
32.
33.
34.
35.
Introduction
35
36. These findings are consistent with those of Evans and Leighton (1989b),
Headen (1990), Maxim (1992) and Hamilton (2000). Of these studies,
Hamilton provides the most detailed evidence of the gains to the selfemployed from switching to paid-employment.
37. For example, Vijverberg (1986) reported that some 20 per cent of respondents
in a 1976 Malaysian survey data set performed work mixing. The authors
calculations using 1994/5 FES data revealed that only 1.4 per cent of UK
workers mixed paid-employment and self-employment. The proportion of
self-employed people doing work mixing (3.3 per cent) exceeded the proportion of employees doing so (1.1 per cent).
38. An alternative to the three-step approach is structural estimation of the parameters of an underlying utility maximisation model (Brock and Evans, 1986).
However, this approach is complicated, not obviously superior and has not
been widely used.
39. In simple terms, a non-stationary process is one in which there is no mechanism forcing values of the series to revert to the mean.
40. See, e.g., Harris and Sollis (2003) for an introduction to cointegration
analysis.
Part I
Entrepreneurship: theories,
characteristics and evidence
Theories of entrepreneurship
40
willing to take risks: his role is to bring the two sides of the market
together, bearing all the risks involved in this process.
Subsequent researchers have developed Cantillons thoughts in two
separate directions. Kirzner (1973, 1985) emphasised the importance
of the entrepreneur as a middleman or arbitrageur, who is alert to
profitable opportunities that are in principle available to all. Successful entrepreneurs merely notice what others have overlooked and profit
from their exceptional alertness. Kirzner did not explain where alertness comes from, nor whether individuals or government can deliberately cultivate it.2
Following Knight (1921), the second line of research highlights the
importance of uncertainty. According to Knight, entrepreneurs face
uncertainty from the unknown availability of natural resources, technological change and fluctuating prices. Although factor prices are
contractible and certain, output prices (and hence profits) are not.3
Hence entrepreneurs need to possess particular characteristics such
as self-confidence, judgement, a venturesome nature, foresight and
luck. One of Knights key contributions was to recognise that the decision to become a worker or an entrepreneur depends on the riskadjusted relative rewards in each sector. In his own words:
The labourer asks what he thinks the entrepreneur will be able to pay, and in
any case will not accept less than he can get from some other entrepreneur, or
by turning entrepreneur himself. In the same way the entrepreneur offers to
any labourer what he thinks he must in order to secure his services. (Knight,
1921, p. 273)
Thus Knight viewed individuals not as born entrepreneurs or nonentrepreneurs, but opportunists, who can turn their hand to entrepreneurship when the risk-adjusted returns there are relatively
favourable or alternatively to paid-employment when they are not.
It will be seen in section 2.2 how modern economic research has followed directly in this tradition, making explicit the risk-adjusted returns Knight referred to.4
2. Co-ordination of factors of production According to Jean-Baptiste Say
(1828), the chief contribution of the entrepreneur is to combine and
co-ordinate factors of production. The entrepreneur stands at the centre of the economic system, directing and rewarding the various factors
of production, and taking the residual as profit. Personal characteristics such as judgement, perseverance and experience required for
successful entrepreneurship would be in scarce supply, providing high
profits to these entrepreneurs. Furthermore, all of these characteristics
would have to be present simultaneously in order for an entrepreneur
Theories of entrepreneurship
41
42
5. Personal or psychological traits This line of thought relates entrepreneurship to the possession of personal characteristics. It is discussed in
chapter 3, section 3.2.
While not exhaustive, the above list includes many of the most influential traditional views about entrepreneurs. The brevity of our overview
was deliberate. Much of this material has been discussed extensively before and, as others have noted, A tome could be written on the connections and contradictions between these theories (Barreto, 1989, p. 43).
We close our discussion by drawing three conclusions. First, we contend that there is a broad dichotomy underlying these theories. The dichotomy is between those in the neoclassical tradition (such as Knight,
1921, Marshall, 1930 and Schultz, 1980) who believe that entrepreneurs
lead markets into equilibrium, and those in the Austrian tradition (such
as Kirzner, 1973) who see entrepreneurs as part of an ongoing disequilibrium process. Rosen (1997) has attempted to find some common ground
between the two schools of thought.
Second, we would argue that none of the above theories is complete.
That is, none of them provides necessary or sufficient conditions for identifying entrepreneurship. For example, farmers can face uncertainty and
corporate employees can contribute to the development of an innovation,
without either being in any sense an entrepreneur. This is what makes
entrepreneurship an elusive, and almost certainly multidimensional, concept (Parker, 2002a).
Third, some writers have claimed that modern economics ignores the
entrepreneur (Baumol, 1968; Barreto, 1989; Kirchhoff, 1991; Rosen,
1997; Casson, 2003). For example, according to Baumol, the theoretical firm is entrepreneur-less the Prince of Denmark has been expunged
from the discussion of Hamlet (1968, p. 66). Such writers give the impression that modern economic theory is concerned purely with establishing general equilibrium, and that in contrast entrepreneurship is all
about disrupting that equilibrium, for example by innovation. They also
claim that ability (e.g. superior judgement) and other distinctive traits
of entrepreneurs are missing from the modern economists models. In
fact, each of these criticisms misses the mark. First, economics is about
much more than ArrowDebreu general equilibrium theory, which occupies only a small area within the subject. Second, economists are well
aware that market adjustment takes time: equilibrium is merely a useful way of thinking about the long-term effects of change. And modern
economics can analyse innovations that change production technologies,
for example establishing the conditions under which such innovations are
likely to be adopted in preference to continuation with existing technology
(see, e.g., King and Levine, 1993). Third, as will be seen in section 2.2,
Theories of entrepreneurship
43
2.2.1
Modern economic theories of entrepreneurship differ in at least two important respects from those described above. Perhaps the most important
distinction relates to the dominance of the utility maximising paradigm
in the modern literature. Modern theories take as their starting point
the Knightian premise that individuals do not have to be entrepreneurs.
They can choose between entrepreneurship and some outside option
(usually taken to be paid-employment); and they choose the occupation
that offers them the greatest expected utility. Most theories treat occupational choice as a discrete, rather than a continuous, decision. This
follows Kanbur (1981), who noted the difficulty of viewing occupational
choice as an adjustment at the margin of a continuous process, such as
engaging a little bit more in entrepreneurial activity (p. 163). However, some researchers have also analysed how individuals mix their time
between different occupations, which resembles more a continuous than
a discrete choice.
A second distinctive feature of modern economic theories of entrepreneurship is that they often assume that product markets are perfectly competitive, that technology is given and that individual workers
and entrepreneurs are price takers. These assumptions are primarily simplifying, and are sometimes relaxed where this does not complicate the
analysis too much. To fix ideas, consider an economy without uncertainty,
where a firms average costs of production c(q ) are increasing in output
q . Suppose there are n S firms, each of which is run by one entrepreneur.
Firms are identical and each produces q units of output. Total supply is
n Sq = Q(P), where product demand Q(P) is decreasing in the output
price P. Each entrepreneur is a price taker in P, i.e. cannot influence P
44
(2.1)
The number of firms, and hence aggregate output and price, is determined where demand equals supply.
In this scenario occupational choice is straightforward. Individuals can
either operate a firm and earn profits or take some outside wage w > 0
offered by an employer. In the absence of compensating differentials,
such as pleasant or unpleasant working conditions, and absent switching
costs, it must be the case that = w, otherwise individuals would have an
incentive to switch to the occupation with the highest return. For example,
suppose > w. This cannot be an equilibrium because workers would
then switch into entrepreneurship, increasing n S and therefore Q and
so reducing P and profit by (2.1) until equality between and w was
restored. A similar argument can be used to rule out an equilibrium with
< w.
This simple model can be used to determine the equilibrium number
of firms, or equivalently the total number (or share, if the workforce is
normalised to size unity) of entrepreneurs. It can also be used to establish simple comparative static results for example that an exogenous
increase in the outside wage w results in fewer entrepreneurs, n S (de Wit,
1993). It can also be extended to analyse, among other things, the effect of uncertainty on entrepreneurship (see subsection 2.2.2 below for
further details).
This simple model of identical competitive firms evidently suffers from
several serious drawbacks. It assumes that all firms are of equal sizes,
and so cannot explain why large and small enterprises coexist in actual
markets. It also rules out interesting questions such as who becomes an
entrepreneur?. For these reasons, richer models have been developed,
which are reviewed below.
Before proceeding, it might be helpful to define some of the terms that
will be used extensively in what follows. While they can be found in many
standard economics texts, it is convenient to group them together and
establish a common notation.
To commence, consider a utility function U() whose argument is income, y. This utility function is assumed to be concave, having a positive
first derivative with respect to y, i.e. Uy (y) > 0, and a negative second
derivative, i.e. Uyy (y) < 0. Viewed graphically, utility is strictly increasing in income, but extra units of income increase utility by progressively
smaller amounts. This utility function is also said to embody risk aversion,
something that is implied by its negative second derivative. If Uyy ( y) = 0,
Theories of entrepreneurship
45
individuals would be risk neutral; and if Uyy ( y) > 0 (a case where the
utility function is convex), individuals would be risk lovers.7 Only the riskaverse case is of much practical interest (see below). The following definitions propose some useful ways of quantifying risk aversion.
Definition 1. Given a twice-differentiable utility function U( y), the Arrow
Pratt coefficient of absolute risk aversion at income y is defined as r A( y) =
Uyy ( y)/Uy ( y).
Definition 2. The utility function U( y) exhibits decreasing absolute risk
aversion if r A( y) is a decreasing function of y.
Definition 3. Given a twice-differentiable utility function U( y), the coefficient of relative risk aversion at income y is defined as r R( y) =
yUyy ( y)/Uy ( y).
The concept of absolute risk aversion is useful for describing preferences over risky outcomes that involve absolute gains or losses of income.
In contrast, relative risk aversion is more appropriate for risky situations
where outcomes are percentage gains or losses of income. Individuals
whose preferences are described by decreasing absolute risk aversion
(Definition 2) take more risks as they become better off. While this often
yields economically reasonable results about risk taking behaviour, it is
sometimes too weak and is complemented by the stronger assumption of
non-increasing relative risk aversion. This assumption states that individuals become more willing to risk fractions of their income as their income
increases. It is a stronger assumption than decreasing absolute risk aversion because, by r R( y) = yr A( y), decreasing relative risk aversion implies
decreasing absolute risk aversion, but the converse does not necessarily
follow. It will be convenient in several places in this book to consider the
case where both apply, encapsulated in the following assumption.
Assumption 1. The utility function U( y) exhibits decreasing absolute risk
aversion and non-increasing relative risk aversion.
Assumption 1 has received theoretical and empirical support from
many sources (see, e.g., Stiglitz, 1970). In view of the popular belief
that entrepreneurs are gamblers, it might appear odd that we assume entrepreneurs at the outset to be risk averse rather than risk lovers. But evidence shows that entrepreneurs behaviour seems to be better described
by moderate and calculated risk taking than outright gambling (Meredith,
Nelson and Neck, 1982).8
It is also helpful to have a precise definition of an increase in risk. Two
useful and general definitions are second-order stochastic dominance
(SOSD) and mean-preserving spread (MPS). Both definitions rank two
46
return distributions, with distribution functions F( y) and G( y). Consider the following ranking:
U( y) d F( y) U( y) dG( y) ,
(2.2)
where U() does not necessarily have to be (though often is) the utility
function defined earlier.
Definition 4 (Second-order stochastic dominance). For any distributions F() and G() with the same mean, F() second-order stochastically
dominates (is less risky than) G() if, for every non-decreasing function U(),
(2.2) holds.
Definition 5 (Mean preserving spread). For any distributions F() and
G() with the same mean, G() is a mean preserving spread of (i.e. is in this
sense riskier than) F() if, for U() some concave function, (2.2) holds.
SOSD evidently places less structure on U() than MPS, which is in
turn a more general measure of increase in risk than an increase in
variance because it implies (but is not implied by) the latter. Under both
definitions, every risk averter prefers F() to G().
Definition 6 (First-order stochastic dominance). The distribution
F() first-order stochastically dominates G() if, for every non-decreasing
function U(), (2.2) holds.
Definition 6 implies that every expected utility maximiser who prefers
more to less prefers F() to G(). Equivalently, for any amount of money
income y, the probability of getting at least y is higher under F() than
under G().
2.2.2
Homogeneous individuals
Theories of entrepreneurship
47
48
E[U ]
=
> 0.
=
H
E[U ]
Hence a MPS causes an increase in industry price which increases E( ).
Hence together with (1), the total effect of the MPS on expected profits and hence the inducement to enter entrepreneurship is ambiguous
a priori.9
It is not possible to obtain more definitive results for the case of price
uncertainty even if the additional structure of Assumption 1 is imposed
on the problem. However, Assumption 1 does clarify that a higher w definitely decreases the equilibrium number of entrepreneurs (Appelbaum
and Katz, 1986).
The studies considered so far investigated the consequences of greater
risk in the economy, perhaps caused by more volatile trading conditions.
But what if there is a general increase in risk aversion among individuals?
This might reflect a change in tastes within an economy; alternatively it
can be thought of as a device to analyse the implications of cross-country
differences in risk attitudes.10 Kanbur (1979) studied the effects of greater
risk aversion on the equilibrium number of entrepreneurs. Suppose that
all individuals have a common index of absolute risk aversion, r A; normalise the size of the workforce and the output price to unity without loss
of generality. Letting E denote the expectations operator, an individual is
indifferent between hiring H workers in entrepreneurship and taking the
Theories of entrepreneurship
49
(2.3)
1
.
1 + H(w; r A)
(2.4)
Kanbur showed that the effects of a generic change in r A depend crucially on whether entrepreneurs hire employees before or after the outcome
of the random shock is revealed.
Proposition 3 (Kanbur, 1979). (i) If labour is hired after the realisation
of is known, then an increase in risk aversion r A decreases the equilibrium
number of entrepreneurs. (ii) If labour is hired before the realisation of is
known, then even invoking Assumption 1, an increase in risk aversion r A has
an ambiguous effect on the number of entrepreneurs, since expected returns in
both occupations decrease.
Proof. (i) In this case, entrepreneurs face no risk when choosing H to
maximise V(w; r A), so the first-order condition is simply q H (H, ) w =
0, where a subscript again denotes a derivative. Thus a change in r A has
no effect on the H implied by this condition. But for any degree of risk
an increase in r A clearly decreases expected utility in the risky occupation, namely entrepreneurship, and thereby n S. Equilibrium is restored
because the reduction in aggregate labour demand needed to satisfy (2.4)
reduces the equilibrium wage until (2.3) holds again.
(ii) Differentiate both sides of (2.3) to obtain
dw/dr A = (Vr A Ur A ) / (Uw Vw ) ,
where Vr A and Ur A are the marginal indirect utilities in entrepreneurship and paid-employment, respectively. Now is a MPS of w, so
Vr A Ur A < 0. Hence as r A increases, there is less incentive to become
an entrepreneur. But differentiation of the LHS of (2.3) yields Vw =
HEU < 0, which together with Vr A Ur A < 0 implies dw/dr A < 0,
implying less incentive to become an employee. Since both occupations
are less attractive, the effects of an increase in r A on the equilibrium
50
number of entrepreneurs, employees per firm and returns in entrepreneurship and paid-employment are all ambiguous in general.
Proposition 3 is of interest partly because of what it says and does not
say about cross-country comparisons of entrepreneurship. For example,
it is sometime asserted that Europeans are more risk averse than Americans (see chapter 3, subsection 3.2.4). Case (i) of Proposition 3, where
entrepreneurs hire workers only once uncertainty has been resolved, appears to provide some theoretical backing to this view. However, there are
at least two reasons to treat this argument with scepticism. First, most
entrepreneurs who hire workers in practice do so continuously and therefore in the presence of uncertainty, so making case (ii) the relevant one.
But as we have seen, it is not possible to establish a clear link between
risk aversion and the amount of entrepreneurship in this case. Second,
the Kanbur model assumes that every individual is identical, and that
all entrepreneurs hire workers two unrealistic assumptions. These assumptions are relaxed in some of the models discussed below.
Dynamic models of risky entrepreneurship with costly switching
The models discussed so far and in all other sections apart from this one
assume costless switching between occupations. Thus if entrepreneurship
becomes attractive relative to paid-employment, workers are assumed to
move immediately into entrepreneurship; the converse also applies. However, in some cases it seems reasonable to suppose that individuals incur
costs of switching occupation. These costs could be economic in nature
involving, for example, lost sector-specific experience, costs of raising
start-up capital (if entering entrepreneurship), or re-training costs (if entering paid-employment). Or they could be non-pecuniary involving, for
example, the sudden loss of a pleasant compensating differential, disruption to an accustomed lifestyle, or a feeling of rootlessness or failure.
One consequence of assuming costless switching is that it is possible
to analyse occupational choice in a static framework. If individuals can
switch effortlessly in the next period, one need be concerned only with
comparing payoffs in different occupations in the current period. This
greatly simplifies the analysis of occupational choice, which is no doubt
one reason why zero switching costs are so commonly assumed. Allowing
for switching costs necessitates a more comprehensive forward-looking,
dynamic modelling framework. We now explore two models of this type.11
In the first model, Dixit and Rob (1994) assumed the existence of two
occupations, which while not labelled as such by those authors, can be
thought of fairly naturally as paid-employment, E, and entrepreneurship, S. Each entrepreneur in S produces output q whose evolution
Theories of entrepreneurship
51
(2.5)
where > 0 is the mean growth rate of output; q > 0 is the standard
deviation of stochastic shocks to output; and dz is the increment of a
Wiener process, which can be thought of as a continuous representation
of random draws from a standard normal distribution. Equation (2.5) is
a representation of a dynamic output process that contains both deterministic and stochastic components.
The size of the workforce is normalised to unity. The two goods sell
at potentially different output prices: it is possible to use them to define
a price index and hence a measure of real income, y. Aggregate output
in S at time t is n S(t)q (t), where n S(t) is the number of individuals who
choose to be entrepreneurs at t. Each employee produces a single unit of
output with certainty, so aggregate output in E is 1 n S(t).
All individuals are risk averse and forward-looking, possessing rational
expectations about the stochastic process underlying the shocks and the
economys responses to them. The shocks in S represent genuine uncertainty, and if especially favourable or unfavourable may create incentives
to switch occupation. However, each switch costs c > 0 in utility, and the
future gains from switching are uncertain because the output price in S
(and hence income) is uncertain. The key point of the DixitRob model
is that uncertainty generates an option value to remain in the present
occupation and to defer a costly switch.
Individuals are infinitely lived. Letting y(t) denote real income at t, >
0 the rate at which individuals discount future returns,12 and ti the dates
of each switch (i = 1, . . . , n), individuals seek to maximise the objective
t
ti
.
(2.6)
E
U[y(t)] e dt
ce
0
52
(or those who heavily discount the future) are more willing to bear a
switching cost in order to realise certain current gains despite future uncertainty. Third, the thresholds diverge as the switching cost c increases:
individuals will tend to stick with their current occupation, even if it is
relatively unsatisfactory, because the cost of switching to the other more
favourable occupation deters movement.
In short, Dixit and Rob showed that there may be hysteresis in occupational choice. Individuals may remain in entrepreneurship even if the
returns there at a given instant are less than those available in an alternative
occupation. It is rational to remain in the occupation not only because of
the switching cost, but also because there is an option value to wait and
see if conditions in the currently unfavourable occupation improve. Only
if output changes such that this option value becomes sufficiently small
will switching become worthwhile.13
Although Dixit and Rob did not discuss this implication of their work,
the hysteresis result is useful because it goes some way to explaining
why there is relatively little voluntary switching between self- and paidemployment from year to year, despite the apparent income differential
between them. US estimates of the proportion switching from E to S
in any given year are only 23.5 per cent.14 The figures for switching
out of self-employment into paid-employment are higher: for example,
using PSID data on non-agricultural males over 196689, Fairlie (1999)
reported one-year exit rates of 18.5 per cent for whites and 36.6 per cent
for blacks. This primarily reflects the high failure rates of small businesses,
especially newly established ones (see chapter 9, section 9.3).
It was seen above that the higher the switching cost, the less switching
takes place. In the limit, these costs may be so high that no individual
ever anticipates switching. In this case, and if utility embodies
constant
R
relative risk aversion so that U( y) = y1r / 1 r R , for r R 0 (see
Definition 3), then individuals have an objective that is a special case
of (2.6), namely
R
[y(t)]1r t
E
e dt ,
(2.7)
1rR
0
where y(t) is an individuals total personal income, defined below. It
is worth exploring occupational choice using this simplified model for
two reasons. First, we can easily investigate the effects of introducing
uncertainty into the hitherto safe sector, E, as well as in S. Second, it
is possible to allow for mixing of work hours between the occupations,
enabling occupational choice to be analysed as a continuous, rather than
just a discrete, choice.
Theories of entrepreneurship
53
To this end, Parker (1996, 1997a) assumed that incomes in both occupations, y j for j = {S, E}, follow potentially different but uncorrelated
Brownian motions:
dy j = j y j .dt + j y j .dz ,
(2.8)
for 0 1 ,
(2.9)
r R( S E )2
S E
dy
54
Theories of entrepreneurship
55
(2.11)
k, H
where r is the rental price of capital, i.e. the interest rate. Using subscripts
to denote derivatives, the first-order conditions for this problem, in k and
H, respectively, are
xq H.() [H.()] () r = 0
for
x x
(2.12)
for
x x ,
(2.13)
from which we can derive demand functions for labour H(x, w, r ) and
capital k(x, w, r ); where x denotes the marginal entrepreneur, defined im = w. The marginal entrepreneur is the individual who
plicitly by (x)
is indifferent between entrepreneurship and paid-employment. Both demand functions are increasing functions of ability x. This implies that
more able entrepreneurs run larger firms (irrespective of whether size
is defined in terms of employment or capital assets), even though the
capitallabour ratio is invariant to ability (to see the latter, take the
ratio of (2.12) and (2.13)). Individuals with ability x x enter entrepreneurship and the rest become workers. Hence the proportion of
implying a mix of workers between the occuentrepreneurs is 1 F(x),
pations if x < x < x. To close the model, the equilibrium factor prices w
and r are determined by equating the demands for and supplies of each
factor.
The dynamic Lucas model
To place greater structure on the model, and to relate entrepreneurship
to economic growth, Lucas invoked Gibrats Law. This Law (which is
explained in greater detail in chapter 9, section 9.2) takes firm growth
rates to be independent of firm size. In the context of Lucas model,
the Law not only ensures that there is a uniquely determined marginal
but also that the following proposition holds.17
entrepreneur x,
56
Theories of entrepreneurship
57
that Lucas model is highly aggregated and simplified, glossing over industry composition effects that may be important given the concentration
of self-employed workers in particular sectors (see chapter 3, subsection 3.3.1).18 Among possible omitted factors is technological change,
which may be a more important cause of macroeconomic growth than
changes in the capital stock analysed by Lucas. For example, if technological change occurs in ways that disproportionately benefit smaller firms,
then more rather than less entrepreneurship may result. The growth
of the service sector may also be relevant. Rising levels of prosperity
often translate into greater demand for services that entrepreneurs may
be particularly efficient at supplying. Finally, it may be inappropriate to
treat entrepreneurial managerial ability as exogenous, especially if entrepreneurs learn over time (Otani, 1996).
Variants and extensions to the Lucas model
Several variants of Lucass model have been proposed (e.g. Calvo and
Wellisz, 1980; Oi, 1983; Blau, 1985; Bond, 1986; Brock and Evans,
1986; de Wit and van Winden, 1991). In each of these models, the
ablest individuals select into entrepreneurship. In the model of Calvo
and Wellisz (1980), for example, x describes the ability to learn about
productivity-enhancing technological information. An individuals output, q (x), is assumed to grow through time t according to the differential equation q (x, t) = x[q (t) q (x, t)], where the dot indicates a time
derivative and the term in square brackets measures the gap between the
individuals output and the maximum available given the stock of knowledge at time t, i.e. q (t). Thus the greater the individuals learning ability
x, or the greater the gap to be made up, the faster the individual learns
and the more she produces. Calvo and Wellisz showed that in steady-state
equilibrium, the greater the growth rate in the total stock of knowledge
and therefore potential output q (t), the more able is the marginal en Hence, given a fixed distribution of ability, the smaller is
trepreneur x.
the number of entrepreneurs and the larger the average firm size.19 This
result is interesting because it provides another rationale for Lucass prediction of ever-declining entrepreneurship and an ever-increasing average
firm size. However, the CalvoWellisz model is ad hoc and partial equilibrium in nature: ideally a general equilibrium analysis of both occupations
with optimising behaviour is needed to fully understand the impact of
technological change on entrepreneurship.
These models all assume that heterogeneous abilities generate heterogeneous returns only in entrepreneurship: returns in paid-employment
are assumed to be invariant to ability. A couple of papers have relaxed this
assumption. Suppose each individual possesses a pair of abilities (x, x E )
58
that are productive in both occupations, the former being ability in entrepreneurship and the latter being ability in paid-employment. Jovanovic
(1994) assumed that returns in paid-employment are given by w.x E ,
where w > 0 is a constant. An individual becomes an entrepreneur if
(x, w) := max{xq (H) wh} w x E ,
H
(2.14)
for x > x .
Theories of entrepreneurship
59
j=S
(a)
x~
Ability x
j=E
(b)
x~
Ability x
j=S
j=E
~x1
x~ 2
(c)
Ability x
Figure 2.1 Occupational choice with two occupations, entrepreneurship (S ) and paid-employment (E )
(a) E attracts the ablest entrepreneurs: x > x enter E
(b) S attracts the ablest entrepreneurs: x > x enter S
(c) Multiple marginal entrepreneurs, x1 , and x2
60
c.
p(x)[R
D] = w(x)
(2.15)
This model not only shows how the different occupations can coexist in
equilibrium (rather than just assuming that this is so, as was previously
the case), but also generates a rich variety of potential occupational choice
outcomes. These include the single crossings of expected returns depicted
in figure 2.1(a) and (b), and also multiple crossings (multiple marginal
entrepreneurs) as in figure 2.1(c). This model also has some implications
for the efficiency of bank financing of entrepreneurial investments as
we will explain in chapter 5.
A distinct but related contribution by Barzel (1987) identified the residual claimant feature of entrepreneurship stressed by Knight as a means
of resolving imperfect information and hidden action problems, and enabling mutually beneficial productive collaborations to take place. As an
Theories of entrepreneurship
61
What if individuals can choose freely between entrepreneurship and paidemployment, as in the models just discussed, but face uncertainty in entrepreneurship and have heterogeneous aversion to risk rather than heterogeneous entrepreneurial ability? The economic implications of this scenario
have been analysed by Kihlstrom and Laffont (1979) (henceforth KL79).
In Kihlstrom and Laffonts own words, their model is a formalisation, for
a special case, of Knights discussion of the entrepreneur (1979, p. 745).
This is because entrepreneurs exercise control over the production process, bear the risks associated with production, and freely choose whether
to become entrepreneurs or workers as in Knight but in the special
case where all individuals possess identical managerial abilities.
Below, let identify individuals from a continuum defined on the
unit interval. Suppose without loss of generality that higher values of
indicate greater aversion to risk, as measured by r A( ). Individuals have
62
quasi-concave utility functions U(y; ), where y is income. All individuals start with common exogenous non-labour income I > 0, which is
sufficiently great to rule out the possibility of bankruptcy. Individuals in
paid-employment all receive the safe wage w, where w > 0 equates aggregate labour demand and supply; but entrepreneurs face uncertain profits
because of random shocks to their production function q = q (H, ),
where H is the number of hired workers. Unlike the Lucas model there is
no explicit treatment of capital. Higher values of correspond to greater
output. The value of is revealed to individuals only after they have
made their occupational choices, labour hiring and production decisions.
Let H(w, ) be s optimal labour demand, i.e. the H that maximises
EU(I + ; ). With a unit output price, entrepreneurs stochastic profits
are
(w, ) = q (H(w, ), ) w H(w, ) .
In the usual way, individual chooses to become an entrepreneur if
EU(I + (w, ); ) U(I + w; ) ,
(2.16)
Theories of entrepreneurship
63
sized firms by result KL79.2. Second, individuals could be made better off if risks were shared, but there is no mechanism for facilitating this. Third, in general the wrong number of individuals become
entrepreneurs. On the one hand risk aversion causes too few individuals to become entrepreneurs (from the standpoint of efficiency), but on
the other hand risk aversion causes too small a demand for labour by
result KL79.2, and hence w is too low, causing too many individuals
to choose entrepreneurship. In general, the two effects will offset each
other and the net effect cannot be predicted without further information about tastes and technology.22
KL79.5 Apart from the problems described in KL79.4 and caused by the
maldistribution of risks across individuals, the equilibrium is in other
respects efficient. One way of achieving full efficiency would be to
introduce a risk-sharing mechanism such as a stock market (Kihlstrom
and Laffont, 1983a).
Perhaps the most widely cited of the above results is the first one,
KL79.1. The prediction that individuals who are relatively less risk averse
are more likely to become entrepreneurs is intuitive, and has also motivated empirical tests (see chapter 3, subsection 3.2.4). However, KL79s
other results are also thought-provoking, and shed further light on the
interaction between risk and entrepreneurship.
For example, result KL79.3 can be compared with part (ii) of Proposition 3 stated earlier, due to Kanbur (1979). Both models predict the
employee wage to decline in response to an increase in risk aversion; but
they generate different predictions about the equilibrium number of entrepreneurs. This is attributable to differences in the structure of the two
models, in particular the heterogeneity of risk aversion in KL79 compared
with homogeneity in Kanbur (1979).
Regarding result KL79.5, others have echoed KL79s recommendation
of introducing risk sharing mechanisms. For example, Grossman (1984)
proposed a similar model to Kanbur (1979) in which the absence of markets for risk sharing causes an inefficiently small number of entrepreneurs.
Grossman showed how allowing free trade with foreigners who have a
comparative advantage in entrepreneurship-rich goods reduces the supply of domestic entrepreneurs even further. Yet he concluded that the
provision of risk sharing mechanisms to stimulate domestic entrepreneurship would be a better solution than imposing welfare-reducing tariffs or
other trade restrictions. Of course, an obvious problem with the specific
solution of a stock market to share risks is that it is likely to be impractical
for small firms. The high fixed costs incurred by a stock market listing
are known to deter small firms from diversifying their risks in this way
(see chapter 6, section 6.2 for more on this).
64
Before we conclude, it is appropriate to pinpoint one important contribution made by both the KL79 and the Lucas (1978) models. It relates to
a fundamental question about why it is that, when large firms have scale
economies in production, small firms exist at all. Both KL79 and Lucas
propose explanations based on exogenous heterogeneous entrepreneurial
characteristics which, in conjunction with concave production functions,
rule out an equilibrium in which one firm produces all the output. Of
course, this is not the only reason why small entrepreneurial firms can
coexist with large ones. Small entrepreneurial firms might be able to avoid
agency problems, diseconomies of scale and diluted incentives to innovate
that can hinder the economic performance of large firms (Williamson,
1985; Reid and Jacobsen, 1988). Also, small entrepreneurial ventures
might be more efficient at supplying small batches of goods or customised
goods and services than their larger rivals, who might have a comparative
advantage at producing standardised products in large production runs.
Part of the interest of the KL79 and Lucas models is therefore that they
can explain the coexistence of small entrepreneurial and large corporate
firms even in the absence of these special factors.
2.3
Conclusion
This chapter reviewed early and modern economic theories of entrepreneurship. While the early theories tended to treat issues in a general and discursive manner, modern economic analysis asks more precisely targeted questions focused on occupational choice. Its approach is
therefore narrower, but it arguably obtains sharper results. For example,
modern theories predict what types of individuals are likely to become
entrepreneurs, and why they do so, as well as tracing out the implications
for economic efficiency. Being tightly focused, this approach also has the
advantage of generating hypotheses that can be tested and falsified in
the accepted scientific tradition. An example is Kihlstrom and Laffonts
(1979) prediction that the least risk-averse individuals are more likely to
become entrepreneurs, and run larger firms.
Another strength of the modern theories is that they clarify what can,
and cannot, be said about the determinants of entrepreneurship. For
example, we saw that greater risk in entrepreneurship does not necessarily reduce the equilibrium number of entrepreneurs. The reason is
that greater risk in entrepreneurship also affects employees indirectly by
decreasing the equilibrium wage. We also showed why rational individuals might not switch between entrepreneurship and paid-employment
despite apparently being able to make clear-cut gains from doing so; and
how imperfect information enables the entrepreneurial function to be
Theories of entrepreneurship
65
1. See, for example, Hebert and Link (1988), Barreto (1989), Binks and Vale
(1990), Chell, Haworth and Brearley (1991) and van Praag (1999). Hebert
and Links monograph provides a particularly thorough account of the entrepreneur in the history of economic thought, from the prehistory of entrepreneurship through to the modern era. Van Praag provides an illuminating
comparison between competing views of entrepreneurship.
2. More recently Gifford (1998) endogenised alertness in a model of limited entrepreneurial attention. Entrepreneurs endowed with high levels of managerial
ability optimally spend their time operating numerous projects: they therefore
face a high opportunity cost of perceiving new innovative opportunities, which
renders them less alert.
3. Knight viewed profits as a fluctuating residual, not as a return to the entrepreneurial factor of production. In contrast, Frederick Hawley (1907) regarded profit as a reward to risk-taking. According to Hawley, what sets the
entrepreneur apart is his willingness to be the ultimately responsible agent in
the productive process, liable for ownership of output but also for loss. This
willingness entitles him to direct and guide production.
4. One aspect of Knights writing that has arguably generated more heat than light
is the distinction between risk and uncertainty or, more accurately, informed
and uninformed uncertainty. Informed uncertainty occurs when an individual
does not know in advance the (random) outcome of a draw from a given probability distribution, but does know the form and parameters of the underlying
probability distribution. Then individuals can form expectations of events.
In contrast, uninformed uncertainty occurs when individuals are not only
ignorant of the outcomes of the random draw, but also do not know the form
of the probability distribution. Some authors have claimed that the latter kind
of uncertainty precludes systematic optimising choice. However, quite apart
from the fact that a careful reading of Knights treatise points to his apparent
belief in informed rather than uninformed uncertainty (LeRoy and Singell,
1987), the whole distinction between informed and uninformed uncertainty
66
5.
6.
7.
8.
9.
10.
11.
12.
13.
Theories of entrepreneurship
67
14. The estimates are: circa 2 per cent (Meyer, 1990; van Praag and van
Ophem, 1995: National Longitudinal Survey (NLS)); 2.5 per cent (Evans
and Leighton, 1989b: CPS); 3 per cent (Boden, 1996: CPS; Dunn and HoltzEakin, 2000: NLS); and 3.4 per cent (Fairlie, 1999: PSID). Boden calculated
that the female switching rate was about 1 per cent lower than that of males.
According to Evans and Leighton (1989b), switching into self-employment
by Americans occurs steadily up to age forty and then levels off. See Taylor
(2001, p. 546) for British evidence on switching rates.
15. Parker (1996) obtained some time-series evidence suggesting that greater risk
in entrepreneurship, proxied by the number of strikes, was significantly associated with a lower aggregate self-employment rate in the UK in the post-war
period. However, he did not control for risk in paid-employment. While Foti
and Vivarelli (1994) proposed the number of involuntary job losses as a measure of wage uncertainty, this measure also carries alternative interpretations,
and confounds the impact of unemployment on new-firm creation.
16. This assumption has been relaxed in a model by Jovanovic (1982), where
entrepreneurs learn about their x by observing their performance in entrepreneurship. Discussion of the Jovanovic model is deferred until chapter
9, section 9.1.
17. The proof is straightforward but technical: the interested reader is referred to
Lucas (1978) original article.
18. Brock and Evans (1986) went so far as to dismiss the empirical relevance of
this model, and another by Kihlstrom and Laffont (1979), discussed below,
concluding that they were developed primarily to study general equilibrium
issues and have limited empirical content (1986, n. 39, p. 204).
19. If young entrepreneurs learn fastest then it can be shown that the age of the
youngest entrepreneur and the average firm size are both decreasing functions
of the rate of technological progress. Making ability two-dimensional, so individuals are characterised by youth and ability, Calvo and Wellisz (1980)
showed that faster technological progress leads to an equilibrium outcome
where older, inherently less able entrepreneurs are replaced by younger and
inherently more able entrepreneurs. See Gifford (1998) for another twodimensional model of ability, comprising managerial ability (for operating
existing projects) and entrepreneurial ability (for innovating new projects).
20. Proofs are omitted for brevity: the interested reader is referred to the original
KL79 article.
21. Strictly speaking, this result requires either the utility or the production function to be strictly concave.
22. For example, in the special case where all individuals are equally risk averse,
it can be shown that there will be too many entrepreneurs in equilibrium.
Another special case is constant returns to scale technology, under which
only one firm is optimal, compared to the greater number that would emerge
in the competitive equilibrium.
Chapter 2 discussed several theories of entrepreneurship, the role of entrepreneurs and the factors influencing individuals to participate in entrepreneurship. The purpose of this chapter is to fill out the picture of
entrepreneurship that has been sketched so far. Complementing the theoretical analysis of chapter 2, section 2.2, section 3.1 reviews the evidence
about the impact of financial rewards on entrepreneurial behaviour. It also
explores the role of specific aspects of entrepreneurial ability embodied
in human and social capital. Section 3.2 focuses on linkages between entrepreneurship, family circumstances and personal characteristics. Section 3.3 summarises theory and evidence about the broader macroeconomic factors that affect entrepreneurship, including economic development, changes in industrial structure, unemployment, regional effects
and government policy variables. Throughout, the self-employed are invariably used as a working empirical definition of entrepreneurs. Section
3.4 briefly summarises the main results of the chapter and concludes.
3.1
3.1.1
Earnings differentials
The most widely used tool for estimating the effects of earnings differentials on participation in entrepreneurship is the structural probit model
described in chapter 1, subsection 1.6.2. Recall from (1.15) that only if
,
the estimated coefficient on the earnings differential term in the probit model, is positive and significant does a relative earnings advantage in
entrepreneurship increase the likelihood of participation in entrepreneurship.
Taking self-employment to be a working definition of entrepreneurship,
(1.15) has been estimated by several British researchers, most of whom
have reported positive estimates. Estimates include 0.365 (Rees and
Shah, 1986); 0.036 (Dolton and Makepeace, 1990); 0.090.13 (Clark
and Drinkwater, 2000); and 0.597 (Taylor, 1996). The first two estimates
68
69
are insignificantly different from zero; the latter two are statistically significant. Parker (2003a) obtained mixed results ( took varying signs) using
several British data-sets from different years; the estimate of was positive but marginally insignificant for switchers between paid-employment
and self-employment. Gill (1988) and Fujii and Hawley (1991) obtained
estimates based on US data. This evidence is also mixed, the former
reporting significant negative and the latter significant positive estimates. For other countries, Bernhardt (1994) estimated to be positive
and significant for a sample of Canadian white, full-time non-agricultural
males. De Wit (1993) and de Wit and van Winden (1989, 1990, 1991)
reported insignificant positive estimates using Dutch data; and Earle
and Sakova (2000) reported negative estimates using household data
from six Eastern European transition economies.1
In short, relative earnings do not play a clear-cut role in explaining
cross-section self-employment choice. One might attribute the mixed
empirical results to the variety of different data-sets and specifications
used by researchers. However, one could just as easily conclude that the
failure to obtain a clear positive effect from relative earnings despite the
variety of specifications and data-sets indicates non-robustness in the relative earnings motive for self-employment. Several explanations for this
inconclusive result can be proposed. First, it is not clear that previous
researchers have successfully isolated variables that affect earnings in the
two sectors but not occupational choice itself as required to identify the
structural probit model (see subsection 1.6.2). Second, the poor quality of
self-employment data may also be partly responsible for the conflicting
results.2 Third, in developing and transition economies market imperfections might undermine neoclassical occupational choices (Earle and
Sakova, 2000), although this explanation is less convincing for developed
economies.
Alternatively, these results may simply be telling us that pecuniary rewards are not the primary motive for choosing self-employment. For example, participation in self-employment might be motivated by lifestyle
considerations, for instance as a means of being ones own boss. Another
possibility is that the self-employed suffer from unrealistic optimism and
remain in a low-return occupation because they anticipate high future
profits. While there might be some truth in these hypotheses, there is
so much economic evidence that human beings adjust their behaviour in
response to changes in relative prices that it would be puzzling if the same
calculus ceased to apply entirely in the realm of occupational choice.
At a more aggregate level, two time-series studies have found that the
difference between average aggregate income in self-employment and
paid-employment is a significant determinant of post-war trends in the
70
Human capital
71
prediction does not rest on ad hoc assumptions such as the young having an innate taste for risk, or irrational expectations such as youthful
over-optimism.
Descriptive studies tend to find that self-employment is concentrated
among individuals in mid-career, i.e. between thirty-five and forty-four
years of age (see, e.g., Cowling, 2000 and Reynolds et al., 2002, for international evidence). Aronson (1991) demonstrated that self-employed
Americans of both sexes were older on average than their employee counterparts throughout the entire post-second World War period. Numerous
other descriptive studies from a variety of countries confirm these findings.
Before we turn to the econometric evidence, we mention two important
caveats to the use of age as a measure of experience. Age and experience
are not synonymous, yet a common practice (often dictated by data limitations) is to measure experience as current age minus school-leaving
age. This measure is imperfect because it takes no account of breaks from
labour force participation in individuals work histories. This may be a
particularly salient consideration when analysing female entrepreneurship. Second, it is important to separate cohort effects from experience
effects. To see this, consider using a cross-section of data to cross-tabulate
self-employment rates by age. Suppose that there has been a secular decline in self-employment over time. Then older cohorts will be observed
to have higher self-employment rates than younger cohorts, irrespective
of any experience effects. To separate cohort effects from genuine experience effects, either longitudinal (panel) data or accurate measures of
years of actual work experience are required. It might also be helpful to
distinguish between experience in paid-employment and experience in
self-employment, since different types of experience might generate different returns and so impact differently on occupational choice. Several
empirical studies make this distinction, as discussed below.
Despite these caveats, most econometric investigations have explored
the effects of age on self-employment using cross-section data. Most of
these studies have found a significant positive relationship between these
two variables, while a minority report insignificant effects.3
Age may have different effects on the willingness and opportunity to
become self-employed. For example, using the bivariate probit estimation approach described in chapter 1, subsection 1.6.3, van Praag and
van Ophem (1995) found that the opportunity to become self-employed
was significantly higher for older than for younger Americans. However,
older workers were significantly less willing to become self-employed than
younger workers were. These findings receive some support from international survey evidence reported by Blanchflower, Oswald and Stutzer
72
73
Education
As with age, one can advance arguments to propose either a negative or
a positive relationship between entrepreneurship and education. On one
hand, more educated workers might select themselves into occupations
in which entrepreneurship is more common, such as managerial occupations for professionals (Evans and Leighton, 1989b) and skilled craft
jobs for manual workers (Form, 1985). As Keeble, Walker and Robson (1993) showed, there are many opportunities for self-employment
in knowledge-based industries. Also, greater levels of education may
promote entrepreneurship because more educated people are better informed about business opportunities.
On the other hand, the skills that make good entrepreneurs are unlikely to be the same as those embodied in formal qualifications (Casson,
2003). In particular, one hesitates to suggest education as a proxy for
managerial ability in entrepreneurship a` l`a Lucas (1978) (see chapter 2,
section 2.2). As noted in chapter 1, subsection 1.5.3, entrepreneurs may
also have fewer incentives to acquire formal educational qualifications
than employees if education is an unproductive screening device used
chiefly by employers to sort hidden worker types. Additional grounds for
doubting the impact of education on the decision to be an entrepreneur
rests on the result that rates of return to education appear to be greater for
employees than for the self-employed (see chapter 1, subsection 1.5.3).
Most econometric studies of the effects of education on selfemployment are cross-sectional. In these studies, educational attainment
is usually measured either as years of education completed, or as a set of
dummy variables registering whether survey respondents hold particular
qualifications. As with age, the evidence generally points to a positive relationship between educational attainment and the probability of being
or becoming self-employed.4 However, many other studies have found
insignificant effects of education on self-employment;5 and several have
detected negative effects.6
It is possible that the divergent results in this branch of the literature
can be attributed to the use of different econometric specifications, in
particular whether controls for financial variables and occupational status are included (Le, 1999). One might expect an individuals specific
occupation to be related to education, imparting possible upward bias
to education coefficients in earnings functions that omit detailed occupational controls. Also, effects of education on self-employment appear
to be sensitive to the industry in which self-employment is performed.
For example, Bates (1995, 1997) reported positive and significant effects
of education on the probability of entering self-employment in skilled
services; negative and significant effects on the probability of entering
74
self-employment in construction; and insignificant effects on the probability of entering self-employment in manufacturing and wholesaling.
Bates concluded that the overall impact of education on self-employment
is obscured by aggregation across dissimilar industries. Another potentially important factor is different cultural traditions. Borooah and Hart
(1999) presented some British evidence that higher education is associated with a greater probability of self-employment among whites, but a
lower probability of self-employment among Indians.
3.1.3
Social capital
Social capital is the name given to social relations that facilitate individual actions. It may exist at the country level, for example in the degree
of trust in government and other institutions; at the community level,
such as the quality of connections within communities; and at the individual level, in the form of confidence or motivation (Glaeser, Laibson
and Sacerdote, 2000). Sanders and Nee (1996) suggested that social relations may increase entrepreneurial success by providing instrumental
support, such as cheap labour and capital; productive information, such
as knowledge about customers, suppliers, and competitors; and psychological aid, such as helping the entrepreneur to weather emotional stress
and to keep their business afloat. In principle, social capital might be used
to compensate for limited financial or human capital.
Gomez and Santor (2001) tested whether social capital affects success
in entrepreneurship. They did this by augmenting a self-employed earnings function with two proxy variables: whether respondents belonged
to any community organisation (club) that meets regularly, and selfreported estimates of the value of ones own social contacts and how well
one knows ones neighbours. Using data on borrowers from a Toronto
microfinance organisation from the 1990s, Gomez and Santor found that
self-employed club members earned significantly and substantially more
than self-employed non-members. It is not yet clear, however, whether
social capital increases entry into self-employment.7
3.2
3.2.1
Marital status
75
and Preisendorfer
(1998) that emotional support from a spouse improves the survival and
profitability prospects of new German business ventures.
3.2.2
Entrepreneurship is often believed to offer greater flexibility than paidemployment in terms of the individuals discretion over the length, location and scheduling of their work time (Quinn, 1980). To the extent that
people with poor health or disabilities need such flexibility, it might be expected that, all else equal, they are more likely to be self-employed. In addition, self-employment may offer a route out of employer discrimination
against the disabled. However, self-employment may be a poor choice for
76
individuals in poor health. Some jobs with high self-employment concentrations such as construction are intrinsically less suited to those with disabilities not to mention more dangerous, implying that self-employment
can also cause disability and ill-health. Work hours and stress are also
greater on average in self-employment (see chapter 8, section 8.2). And
whereas many employees receive health cover from their employers, the
self-employed must provide their own.12
Survey evidence from the UK suggests that self-employed men actually have slightly better (self-reported) health than male employees do,
whereas self-employed females are slightly less healthy than their employee counterparts (Curran and Burrows, 1989). In contrast, Fredland
and Little (1981) reported that mature American self-employed workers were in significantly poorer health than employees. Probit estimates
reflect mixed effects of ill-health on self-employment status.13
In summary, the association between self-employment and ill-health
and disability is ambiguous. It is unclear at present what underlies the
lack of agreement between the various empirical studies; but it would
seem that there is ample scope for further research on this topic.
3.2.3
Psychological factors
Entrepreneurial traits
A large psychological literature has developed which claims that entrepreneurs possess special traits that predispose them to entrepreneurship. Economists are now catching on to this idea, by including psychological variables in cross-section probit models of self-employment
choice.
In their review of the role of psychological factors in entrepreneurship
research, Amit, Glosten and Muller (1993) identified four traits that have
attracted substantial research interest:
1. Need for achievement. One of the first systematic attempts to provide a psychological profile of entrepreneurs was McClelland (1961).
McClelland highlighted the constructive role of business heroes who
promote the importance of entrepreneurial achievement to subsequent generations. According to McClelland, the key characteristic
of successful entrepreneurs is the need for achievement (n-Ach),
rather than a desire for money (1961, pp. 2337). In McClellands
words: a society with a generally high level of n-Ach will produce
more energetic entrepreneurs who, in turn, produce rapid economic
development (p. 205). McClellands conclusions were drawn from
results of applying Thematic Apperception Tests (see Brockhaus,
1982, for a description and a critique). As well as having n-Ach,
77
McClelland also argued that entrepreneurs are proactive and committed to others; like to take personal responsibility for their decisions;
prefer decisions involving a moderate amount of risk; desire feedback
on their performance; and dislike repetitive, routine work. A corollary
of McClellands thesis is that the achievement motive can be deliberately inculcated through socialisation and training, although results
from such efforts have drawn a mixed response (Chell, Haworth and
Brearley 1991). It is not clear that n-Ach can be coached, as has
been claimed; and it is questionable whether entrepreneurship is the
only vocation in which n-Ach can be expressed (Sexton and Bowman,
1985).14
2. Internal locus of control. Another psychological trait is a persons innate
belief that their performance depends largely on their own actions,
rather than external factors. Psychologists call this having a high internal locus of control. Since self-employment often offers greater scope
for individuals to exercise their own discretion at work than does paidemployment, it follows that those with a high internal locus of control
might have a greater probability of being self-employed. A psychological metric known as the Rotter Scale (Rotter, 1982) provides the basis
for empirical tests of this hypothesis. The more a survey respondent believes a range of factors to be under her control, as opposed to outside
her control, the lower her Rotter score in any given test. While Evans
and Leighton (1989b) and Schiller and Crewson (1997) obtained evidence from probit regressions supporting the locus of control hypothesis, van Praag and van Ophem (1995) obtained contrary results. The
mixed findings may reflect the fact that having a high locus of control is not unique to entrepreneurs, since it has also been identified
among successful business managers (Sexton and Bowman, 1985).
3. Above-average risk taking propensity. As chapter 2, subsection 2.2.4
showed, Kihlstrom and Laffonts (1979) model of entrepreneurship
predicts that entrepreneurs are less risk averse than employees are.
Evidence on this issue will be discussed in subsection 3.2.4.
4. A tolerance of ambiguity (Timmons, 1976; Schere, 1982). It is proposed
that entrepreneurs have a greater capacity than employees for dealing
with environments where the overall framework is ill defined.
The above list is by no means exhaustive. Others have claimed that
entrepreneurs exhibit Type A behaviour, which is characterised by competitiveness, aggression, a striving for achievement and impatience (Boyd,
1984). Another trait is claimed to be over-optimism (see below). Still others have argued that entrepreneurs are misfits or displaced persons who
live outside the mainstream of society, and are possibly prone to deviant
and criminal behaviour (Shapero, 1975; Kets de Vries, 1977). Kets de
78
79
are amenable to glib generalisations in terms of their psychological characteristics. Traits are unlikely to be unique to entrepreneurs, raising a
demarcation problem; and being unobservable ex ante, they are virtually impossible to separate ex post from luck and other extraneous factors
(Amit, Glosten and Muller, 1993). There is also, as Kaufmann and Dant
have pointed out, a tendency in this literature to personify entrepreneurs
as embodiments of all that may be desirable in a business person, and
almost deify entrepreneurs in the process (1998, pp. 78). The conclusion reached by several authors, including this one, is that psychological
factors are neither necessary nor sufficient conditions for entrepreneurs
or entrepreneurship.
Love of independence and job satisfaction
It is commonly suggested that an attractive feature of entrepreneurship is
independence in the workplace, something that is variously referred to as
a love of autonomy or being ones own boss. This idea can be traced back
to Knight (1921), and has been emphasised by non-economists (Scase
and Goffee, 1982; Cromie, 1987; Dennis, 1996), as well as by economists
seeking explanations of why individuals remain self-employed despite
apparently earning less than employees do (Aronson, 1991; Hamilton,
2000).
This subsection reviews evidence about the love of independence in
entrepreneurship, before asking whether it feeds through into greater
happiness among entrepreneurs relative to employees, in terms of both
job satisfaction and lifework balance.
Based on an analysis of 466 male self-employed Britons from the
1991 wave of the BHPS, Taylor (1996) found that fewer self-employees
than paid-employees regarded pay and security as important job aspects. The proportions were 37 and 32 per cent compared with 48 and
57 per cent, respectively. However, greater proportions of self-employed
workers felt that initiative (51 per cent) and the enjoyment of work itself (57 per cent) were important job aspects, compared with 21 and
41 per cent of employees, respectively. This bears out the idea that the
self-employed enjoy relative freedom from managerial constraints and
working for themselves. These non-pecuniary factors were significantly
associated with being self-employed, even after controlling for personal
characteristics (see also Burke, Fitz-Roy and Nolan, 2000; and Hundley,
2001b).16
Table 3.1 summarises reasons for being self-employed cited by respondents of the UKs spring 2000 LFS. These responses bear out the importance of independence, the single most important reason cited by
80
All
Men
Women
To be independent
Wanted more money
Better conditions of work
Family commitments
Capital, space, equipment
opportunities
Saw the demand
Joined the family business
Nature of occupation
No jobs available locally
Made redundant
Other reasons
No reason given
No. valid responses (000) a
31
13
5
7
33
15
6
2
25
7
3
21
12
8
6
22
3
9
15
3
2,960
12
9
6
21
3
11
14
4
2,156
11
8
7
23
2
3
18
3
804
Note: Columns do not sum to 100 per cent because respondents can
give up to four reasons.
a Imputed percentages based on all those who gave a valid response to
the reasons for becoming self-employed questions.
Source: LFS (2000).
the LFS respondents. The next most important reason is the nature of
the occupation, perhaps reflecting the fact that self-employment is the
chief or only mode of employment in some locations or occupations (e.g.
forestry or construction). Both men and women have similar responses,
although women stress independence a little less than men, and family
commitments substantially more (see also Hakim, 1989a).
It should be remembered, however, that not all people enter selfemployment in order to gain independence. Nor is it clear that people
always obtain much actual independence from being self-employed, especially those who work long hours (see chapter 8, section 8.2) or who work
in one the grey areas between paid-employment and self-employment.17
Numerous studies show that the self-employed consistently claim to
enjoy greater job satisfaction than employees do, even after controlling
for job and personal characteristics such as income gained and hours
worked. For example, using British NCDS data from 1981 and 1991,
Blanchflower and Oswald (1998) reported that approximately 46 per cent
of the self-employed claimed they were very satisfied with their job, compared with only 29 per cent for employees. Blanchflower and Freeman
81
82
83
debt finance. But also unlike realists, optimists make negative expected
returns net of opportunity costs, leading to higher exit rates.
There may also be policy implications. Most of the models cited above
find that over-optimistic behaviour causes distortions in the economy
as a whole. In a practical vein, Cooper, Woo and Dunkelberg (1988)
recommended that entrepreneurs be encouraged to form relationships
with outsiders, such as non-executive board members and professional
advisors. Outsiders have the objectivity and detachment to counteract
unrealistic optimism hopefully without extinguishing the essential fire
of entrepreneurial zeal.
3.2.4
Chapter 2, subsections 2.2.2 and 2.2.4 distinguished between risk attitudes (e.g. individual risk aversion embodied in the utility function) and
the actual or perceived level of risk itself. Below, we continue with this
distinction, first summarising empirical work on risk attitudes, followed
by empirical work on levels of risk.
There are various ways of measuring risk attitudes. One is to ask people how they would choose between risky hypothetical situations. Examples include Brockhaus (1980) Choice Dilemma Questionnaire, and
van Praag and Cramers (2001) interview questions about gambling. The
results are mixed. Whereas Brockhaus found insignificant differences in
responses between entrepreneurs and non-entrepreneurs, van Praag and
Cramer claimed that entrepreneurs were significantly more willing to
gamble than employees were. Van Praag et al. (2002) also claimed that
risk aversion significantly decreased the probability that given individuals would choose to be entrepreneurs consistent with the theory of
Kihlstrom and Laffont (1979) outlined in chapter 2, subsection 2.2.4.
But, while Uusitalo (2001) reported similar findings, Tucker (1988) detected insignificant effects from risk attitudes on self-employment choice
using a specially framed survey question from the PSID. And direct evidence indicates that self-employed people are less likely to participate in
lotteries than employees at least in Scandinavia (Lindh and Ohlsson,
1996; Uusitalo, 2001).
It is also unclear what these findings really tell us. It is all too
easy to conflate genuine risk attitudes with optimism, since there is
evidence that entrepreneurs interpret the same business stimuli more
favourably than non-entrepreneurs do (Palich and Bagby, 1995; Norton
and Moore, 2002). Thus researchers could misconstrue adventurous actions based on over-optimistic expectations of outcomes as evidence of
greater risk tolerance. There are also likely to be inherent reporting biases
84
Family background
It has been widely recognised that self-employment tends to run in families. There are several reasons why having a self-employed parent might
increase the probability that a given individual turns to self-employment
85
himself. Self-employed parents might offer their offspring informal induction in business methods, transfer business experience and provide
access to capital and equipment, business networks, consultancy and
reputation. Also, children may be motivated to become entrepreneurs
if this eventually entitles them to inherit the family business. This transmission process could be especially important in some sectors, such as
agriculture, where parents often pass on farms to their children.
In contrast, sociologists have stressed the role of the family as a channel through which cultural values can be passed on to individuals. Hence
family backgrounds in which entrepreneurship is prominent can be expected to foster similar favourable attitudes in the familys offspring.
The self-employed certainly seem to have more pro-business attitudes
on average than employees do20 though the extent to which this is
attributable to the inculcation of family values is questionable. Households with self-employed heads might also furnish role models although
of course they could also convey some of the less savoury aspects of
self-employment, such as long hours and family stress (see above). Role
models are also suggested by findings of a negative relationship between
the size of a workers employer and the propensity of workers to opt
for self-employment (Storey, 1994a): presumably larger firms offer fewer
entrepreneurial role models. But this negative relationship might also reflect more favourable working conditions in larger firms, since it is known
that larger firms offer wage premiums, which may deter switching into
self-employment.
The direct evidence points clearly to strong intergenerational links
between parents and children. In work based on 1979 US NFIB survey data, Lentz and Laband (1990) observed that around half of all
US self-employed proprietors were second-generation business people;
while sons of self-employed fathers were three times more likely to be
occupational followers than the average worker (Laband and Lentz,
1983). Parental self-employment both increases the fraction of time that
offspring spend in self-employment and reduces the age at which they
enter it (Dunn and Holtz-Eakin, 2000). Followers also earn higher selfemployment incomes than non-followers in self-employment (Lentz and
Laband, 1990). These effects are robust to the inclusion of observable
characteristics in probit models of self-employment choice, which invariably identify significant positive and substantial effects from dummy variables representing fathers self-employment status.21 The US evidence is
mixed on whether blacks as well as whites have positive self-employment
fatherhood effects (c.f. Fairlie, 1999; Hout and Rosen, 2000). For white
Americans, the likelihood of self-employment increases if the father is a
manager, and decreases if the father is unskilled (Evans and Leighton,
1989b). De Wit and van Winden (1989, 1990) noted that if a father
86
3.3.1
Economic development
This section asks how economic development affects the nature and extent of entrepreneurship, from both a theoretical and an empirical perspective. Economic development can occur in a number of ways, that
have potentially different impacts on entrepreneurship. Leading on from
the seminal work of Lucas (1978), one form of economic development
involves exogenous increases in the capital stock, capital being one of the
inputs to entrepreneurs production functions. A second form of development is technological progress, which can either be exogenous (shifting
entrepreneurs production functions) or endogenous (e.g. knowledge
grows as a result of efforts to exploit it). A third form of development
is driven by endogenous increases in personal wealth stocks, enabling individuals to engage in risky investments that they were unable to afford
before. All three forms of development can be analysed as special cases
87
(3.1)
88
89
d(t)
(t)
= 0 (t).
(3.3)
dt
0 (t)
0 (t) = n S(t)(t)
(t)
= n S(t)(t) ,
(3.4)
(3.5)
(3.6)
(with (0) > 0 given), where (t) is aggregate consumption (= output)
at time t and > 0 is the discount rate. In contradistinction, the social
welfare optimum is characterised by the steady-state pair {n
S , } that
is the steady state solution of the problem (3.6) subject also to (3.4) and
90
(3.5) i.e. which unlike the competitive equilibrium takes account of the
aggregate knowledge spillover.
Proposition 6 (Schmitz, 1989). The steady-state competitive equilibrium
characterised by {nS, } does not maximise social welfare; and nS < n
S , implying there are too few entrepreneurs in equilibrium relative to the social optimum.
The competitive equilibrium is not welfare maximising because atomistic individuals do not take account of the effects of their own behaviour
on the aggregate knowledge spillover. The free-market economy is predicted to generate too little entrepreneurship. More entrepreneurship is
desirable because it increases the aggregate value of the spillover by (3.3)
and (3.5). One policy implication is to encourage technology-based entrepreneurship in order to increase economic growth.
Endogenous growth of personal wealth Banerjee and Newman (1993) proposed a model in which banks make only secured loans. The greater the
loan size, the greater the temptation for borrowers to take the money and
run and forfeit their collateral. Anticipating this, banks limit the scale of
loans (and therefore also the size of investment projects) according to individuals wealth. Thus the initial distribution of wealth determines who
becomes an entrepreneur with workers (an employer), who becomes
an entrepreneur without workers (self-employed), and who becomes a
worker in one of the firms run by the employers. Each individual lives
for a single period: they choose how much of their wealth to bequeath
to their offspring. This imparts path dependence to capital k(t) and, because of the above capital market imperfection, also to aggregate wealth
and the occupational structure of the economy. (In terms of the production function (3.1), A is fixed and = 0; and there are two versions of
q [, ], one for employers and one for the self-employed.)
Various development paths can arise in Banerjee and Newmans model;
two are of particular interest. In one, an economy F starts with a small
fraction of workers, so wages are relatively high and plenty of individuals
possess the collateral to become self-employed. Although some successful
self-employed people in F have sufficient wealth to become employers,
they cannot find cheap workers, and so choose to remain self-employed.
This becomes a self-perpetuating outcome via the bequest mechanism,
and it characterises the economys equilibrium. A second case is an economy E , say, starting with a large fraction of poor workers, so wages are
low. If individuals choose to bequeath little to their offspring, workers remain poor and face binding borrowing constraints in all subsequent generations. This economy converges to an equilibrium in which there are
91
92
2002; an exception is Parker and Robson, 2000). While this is broadly consistent with the predictions of
Lucas, Schaffner, and Calvo and Wellisz that self-employment rates
decline with economic development, GNP per capita is a crude measure of development and does not distinguish its underlying sources.
These empirical findings certainly do not give explicit support to any
of the particular theories outlined above.
It is hard to reach any definitive conclusions from this empirical work.
Also, among developed countries there has been, and continues to be,
enormous diversity of self-employment rates and trends (see chapter 1,
section 1.4). This is despite the fact that technological change has been
pervasive and broadly similar in these countries. It therefore seems unlikely that technological change alone can explain the observed variations
and trends in aggregate self-employment rates.
Changing industrial structure
Some jobs lend themselves more naturally to self-employment than
others. These include labour-intensive one to one personal services,
93
seasonal jobs and jobs with erratic demand that would be too costly for
large firms to organise, and which can be filled more cheaply by independent self-employed workers. Another consideration is the mix of skills
required in particular industries. For example, if entrepreneurs are jacks
of all trades with balanced skills sets, then industries like art (which requires disparate skills in artistic talent and business management) are
less likely to be populated by entrepreneurs than insurance, say, where
the required skills are more similar to each other (Lazear, 2002).
Capital requirements in different industries may also play a role. It is
unlikely that individuals will opt for self-employment in industries dominated by large, capital-intensive firms, since the latter often have a comparative and absolute advantage in raising capital. The evidence seems to
bear this conjecture out. White (1982) found that there were fewer small
US manufacturing firms in industries with high capital intensities; and
Acs and Audretsch (1989) reported that high capitallabour ratios were
associated with lower rates of US small business entry in 247 manufacturing industries.
No doubt reflecting the combined effects of these factors, most countries exhibit high concentrations of self-employed workers in particular
sectors and industries. The available evidence comprises both simple tabulations and results from self-employment probit models that include occupation and industry dummy variables. The latter have the advantage
that industry effects can be separated from other factors, such as skill
requirements, that also bear on occupational choice.27
In North America, male self-employed workers tend to be concentrated
in construction, services and retail trades; and in the sales, agriculture,
hotels, repairs, craft, managerial and professional occupations. The lowest self-employment rates by sector are observed in manufacturing. The
predominance of service sector self-employment has a long history. For
example, Aronson (1991) reported that about three-quarters of pre-first
World War non-farm US self-employment was in service-sector industries. The service sector has of course grown relative to manufacturing
since that time, although shifts have also occurred within the service sector especially since the 1950s, towards finance, insurance and personal
and business services. The role of self-employment in each of the transportation, communications and retail sectors has steadily declined. Similar patterns of industry and occupation self-employment are observed
in the UK, with high concentrations in construction, distribution, hotel
and repairs, banking and financial services. According to 1991 LFS data,
these sectors accounted for 62 per cent of all UK self-employment.28
The broad sectoral composition of self-employment appears to be fairly
similar to this in other OECD countries (Loufti, 1992).
94
Unemployment
There is now an extensive literature on the relationship between selfemployment and unemployment. One of the motivations for studying
this topic is the policy interest about promoting self-employment as a
95
96
Kuhn and Schuetze, 2001). For example, Evans and Leighton (1989b)
concluded that between 1968 and 1986 unemployed workers were about
twice as likely to start businesses as employees were; and almost three
times as many individuals enter self-employment from outside the labour
force as from unemployment (Dennis, 1996). To put this in perspective,
from one year to the next most unemployed people either remain unemployed or become employees; only a small minority become self-employed
(Cowling and Taylor, 2001). But these results all appear to support the
prosperity-pull hypothesis. The state of the business cycle also seems
to matter. According to Carrasco (1999), unemployed male Spaniards
are more likely to enter self-employment in boom times, i.e. when the
unemployment rate is low.
It has also been shown that, of the unemployed, those with more unstable work histories (including periods of past unemployment) are significantly more likely to enter self-employment and to be self-employed
(Evans and Leighton, 1989b; Carrasco, 1999; Knight and McKay, 2000;
Uusitalo, 2001). Evans and Leighton construed this as evidence that
the self-employed may be misfits who are driven into entrepreneurship. But, the evidence on this point is not clear-cut. A closer analysis
of the data reveals that a history of job changes, rather than unemployment per se, significantly increases the willingness of workers to become
self-employed (van Praag and van Ophem, 1995). Furthermore, Farber
(1999) reported that US employees who had lost their jobs in the previous
three years (job-losers) were significantly less likely to be self-employed
(by 3 percentage points) than non-losers. That remained the case even
after controlling for other personal characteristics of the survey respondents. This evidence suggests that self-employment in the USA is not a
transitional process following job loss unlike temporary and part-time
work.30
It may be important to distinguish between men and women when
measuring the inflow to self-employment from non-employment states.
Kuhn and Schuetze (2001) found that most of the increase in female
Canadian self-employment in the 1980s and 1990s was attributable to an
increase in retention rates in self-employment, whereas for men, most of
the increase was attributable to a decrease in stability in paid-employment
and inflows from unemployment (for similar British findings, see Blanchflower and Freeman, 1994).31 It is also possible that the effects of unemployment on self-employment may vary from occupation to occupation.
For example, some professional occupations may be protected against
unlicensed new entrants, making the number of self-employed professionals less cyclical than the number of self-employed non-professionals
(Meager, 1992a). In principle, interacting local unemployment rates in
97
98
99
Table 3.2 Self-employment rates in the British regions, 1970 and 2000
Region
Rank in 1970
Rank in 2000
6.02
6.45
7.00
10.11
7.28
11.71
5.74
6.54
10.37
5.68
7.96
10.42
10.71
13.35
13.47
14.98
10.29
9.87
12.43
9.31
8
7
5
3
4
1
9
6
2
10
10
6
5
3
2
1
7
8
4
9
North
Yorkshire & Humberside
East Midlands
East Anglia
South East
South West
West Midlands
North West
Wales
Scotland
Note: The self-employment rate is defined as the number of self-employed jobs (male plus
female) in the region divided by the regions labour force.
Source: Abstract of Regional Statistics, 1974 (HMSO, London, table 39) and Regional Trends,
2001 (The Stationery Office, London, tables 5.1, 5.5).
vary over time as governments alter the tax-benefit system and their
stance on labour market intervention and thereby the flexibility of the
economy.
To conclude, the true impact of unemployment on self-employment
probably lies somewhere between the strong positive and strong negative
estimates recorded in the present literature. Modest positive or negative
effects look like the safest bet, though on balance, it seems to the author that the cross-section studies are likely to be the least misleading.
This is because several of the cross-section studies include some measure
of relative incomes, in addition to variables capturing localised demand
conditions. In contrast, the problems of omitted variable and aggregation
bias are likely to be more pronounced in the time-series studies.
3.3.3
Regional factors
Previous research has identified substantial and persistent regional variations in self-employment and business start-up rates, in a variety of
countries, including the UK and the US (Georgellis and Wall, 2000). Regional variations have been observed within neighbourhoods and cities,
and across broader administrative regions. Table 3.2 contains some illustrative British data that point to pronounced regional differences in
self-employment rates. These differences have been fairly persistent over
the last thirty years. For example, the Spearman correlation coefficient
for table 3.2s rank orderings in 1970 compared with 2000 is 0.87.
100
101
rates of entrepreneurship. Robson investigated the determinants of regional variations in UK male regional self-employment rates using pooled
time-series cross-section data from the eleven standard regions of the UK
(comprising the ten in table 3.2 plus Northern Ireland) over 197393.
Robson regressed regional male self-employment rates on several regional
explanatory variables, including net housing wealth, nhw j ; income shares
accounted for by agriculture, agr i c j , and Construction, Distribution,
Hotels and Catering, cdhc j ; GDP per capita; real average earnings; the
unemploymentvacancy ratio; the long-term unemployment rate; and
proxies for average regional age and education profiles. Strikingly, Robson found that, of all these variables, only the first three were statistically
significant in a long-run model of the log male self-employment rate, n Sj ,
where j denotes a region:
ln
n Sj = j + 0.031 agr i c j + 0.047 cdhc j + 0.207 ln nhw j ,
(3.7)
and where the j are regional fixed effects. Thus a 10 per cent increase
in a regions real net housing wealth is predicted to increase that regions
male self-employment rate by over 2 per cent. Clearly housing wealth
whose values closely reflect house prices plays a central role in explaining
regional variations self-employment rates, as suggested above. However,
taken together the last three variables on the RHS of (3.7) explained only
35 per cent of the differential in the self-employment ratio between the
highest- and lowest-ranked regions for male self-employment, namely the
North and the South-West of England.37 The regional dummies j accounted for 23 per cent of the NorthSouth self-employment differential.
These presumably capture the effects of unobserved variables, perhaps
historical and cultural factors (Reynolds, Storey and Westhead, 1994;
Spilling, 1996; Georgellis and Wall, 2000).
Turning from self-employment rates to new-firm creation rates as a
measure of entrepreneurship, we note that there is a large economic
geography literature on spatial variations in small-firm formation rates.
That literature will not be exhaustively surveyed here: Reynolds, Storey
and Westhead (1994) supply an overview. Using data from six OECD
countries, Reynolds, Storey and Westhead found that firm birth rates
were highest in regions with high proportions of employment in small
firms, as well as high rates of in-migration, demand growth, employment
specialisation, and population densities (see also Spilling, 1996). However, many of these explanatory variables are likely to be endogenous.
Interestingly, local government expenditures and assistance programmes
were found to have only limited effects on regional firm birth rates.
Another dimension of regional variation is the distinction between urban and rural locations. Arguments can be made both for and against
102
the relative advantages for entrepreneurship in urban relative to rural locations. On one hand, urban markets tend to be larger and enjoy higher
average disposable incomes. On the other hand, inputs such as rent and
labour can be more expensive in urban areas; and there are often fewer
paid-employment opportunities in rural areas, increasing the relative attractiveness of new-firm creation and self-employment there. The evidence from self-employment probit regressions with an urban dummy
variable is mixed.38
There might also be systematic variation in entrepreneurial activity within a given urban area. A range of neighbourhood characteristics can potentially affect the returns to self-employment relative to
paid-employment. For example, higher average neighbourhood incomes,
population densities and commercial concentrations can generate higher
levels of demand for the services of small-scale entrepreneurs. Particular
neighbourhoods may also facilitate information exchange and the formation of social capital. Levels of education, home ownership, urban design
and community spirit may also vary across neighbourhoods, and in some
cases there may be an important ethnic dimension to urban composition
(see chapter 4 for more on the latter).
In summary, the economic literature on regional dimensions of entrepreneurship looks to be ripe for further investigation and extension.
This is especially true of the theory side, though our understanding of
the empirical structure of regional variations in entrepreneurship is also
incomplete. The available evidence suggests that many hard-to-observe
region-specific and individual-specific factors affect regional levels of entrepreneurship. To separate individual from regional factors it will almost certainly be necessary to deploy detailed micro-level cross-section
data, rather than aggregate data, which by their nature omit too many
individual-level variables to distinguish sharply between the different influences.
3.3.4
103
2002).
Public-sector employment might also crowd out self-employment: see
Boyd (1990) for evidence that this may have occurred among American
blacks.
Interest rates
Higher interest rates increase the cost of financing a business. This includes direct costs (debt repayments) and indirect, or opportunity, costs
such as tying up ones funds in a firm. Higher interest rates may therefore be expected to decrease firm births and increase firm deaths, and
so have a negative effect on self-employment. However, if banks offer
long-term loans at fixed interest rates, then new-firm starts measured at
104
No. +
No.
No. 0
6
36
7
25
20
4
0
17
2
2
1
1
11
4
2
3
2
4
4
8
0
14
3
0
0
0
2
3
21
5
2
0
18
10
10
5
0
2
7
0
3
6
2
3
0
2
2
1
Ref.
d
n. 3
e
nn. 46
nn. 911
n. 13
n. 19
f
g
h
i
n. 38
j
n. 39
k
l
Note: +, and 0 denote significantly positive, significantly negative and zero (insignificant)
coefficients, respectively. Only multivariate studies (i.e. those including controls for other
explanatory variables) are included; descriptive studies are excluded. Ref gives sources
of individual studies as footnotes (n.) in chapter 3, or in the following notes, where
semicolons separate the three groups of outcomes.
a Counting all the de Wit and de Wit and van Winden studies as one.
b Based on results summarised in chapter 7, section 7.1.
c Based on results summarised in chapter 10, section 10.4.
d Fujii and Hawley (1991), Bernhardt (1994), Parker (1996), Taylor (1996), Cowling and
Mitchell (1997), Clark and Drinkwater (2000), Gill (1988), Earle and Sakova (2000),
Rees and Shah (1986), Dolton and Makepeace (1990); de Wit and van Winden (various),
Parker (2003).
e Carroll and Mosakowski (1987), Tucker (1988), Evans and Leighton (1989b), van Praag
and van Ophem (1995), Bates (1997), Schiller and Crewson (1997), Quadrini (1999);
Tucker (1990: for professionals).
f See n.n 21 and 22. Additional positive effects found by Laband and Lentz (1983), Lentz
and Laband (1990), Dunn and Holtz-Eakin (2000), Lin, Picot and Compton (2000),
Cramer et al. (2002).
g Blau (1987), Acs, Audretsch and Evans (1994); Kuznets (1966), Schultz (1990), Acs,
Audretsch and Evans (1994), Folster
105
For positive effects see nn. 32 and 34, plus Storey and Jones (1987), Foti and Vivarelli
(1994), Georgellis and Wall (2000); Robson (1996, 1998a, 1998b), Lin, Picot and Compton (2000), Cullen and Gordon (2002); Acs, Audretesch and Evans (1994), Parker and
Robson (2000).
j Blau (1987), Robson (1998b); Carrasco (1999), Parker and Robson (2000).
k For positive effects, see n. 2 of chapter 7. For insignificant effects, see Taylor (2001) and
Uusitalo (2001).
l Long (1982a), Moore (1983a), Blau (1987), Evans and Leighton (1989a), Parker (1996),
Robson (1998b), Robson and Wren (1999), Bruce (2000), Parker and Robson (2000),
Schuetze (2000); Robson and Wren (1999), Parker and Robson (2000), Fo lster (2002);
Cowling and Mitchell (1997).
106
3.4
Conclusion
107
N OT E S
1. See also Clark, Drinkwater and Leslie (1998) for British evidence of effects
that differ across ethnic groups. In contrast, aggregate studies of new business
starts usually report positive effects from business profits relative to wages
(Creedy and Johnson, 1983; Foti and Vivarelli, 1994; Audretsch and Vivarelli,
1997; Goedhuys and Sleuwaegen, 2000; Lofstrom, 2002).
2. Income under-reporting is one possibility, although adjustments made by the
author to cope with this (Parker, 2003a) made little practical difference. Note
also that the exclusion of health insurance benefits from measured incomes
appears to have little effect on self-employment participation either (Bruce,
Holtz-Eakin and Quinn, 2000).
3. The following studies have reported positive (usually quadratic, i.e. increasing with age, but with diminishing returns at higher ages) and significant effects from age on the probability of being or becoming self-employed. For
the UK: Rees and Shah (1986), Taylor (1996), Clark and Drinkwater (1998,
2002), Clark, Drinkwater and Leslie (1998) and Borooah and Hart (1999).
For the USA: Moore (1983a), Borjas (1986), Brock and Evans (1986), Borjas
and Bronars (1989), Evans and Leighton (1989a), Boyd (1990), Fujii and
Hawley (1991), Holtz-Eakin, Joulfaian and Rosen (1994a, 1994b), Blanchflower and Meyer (1994), Robinson and Sexton (1994), Carr (1996), Bates
(1995, 1997), Boden (1996), Schiller and Crewson (1997), Schuetze (2000),
Flota and Mora (2001), Fairlie (2002) and Lofstrom (2002). For other countries: Maxim (1992), Schuetze (2000) and Moore and Mueller (2002) for
Canada; Kidd (1993) and Blanchflower and Meyer (1994) for Australia;
Laferr`ere and McEntee (1995) for France; Goedhuys and Sleuwaegen (2000)
for Cote
dIvoire; Uusitalo (2001) for Finland; and Blanchflower (2000),
Cowling (2000) and Blanchflower, Oswald and Stutzes (2001) using international data. Studies finding no significant effects of age on self-employment
include Taylor (1996) and Robson (1998a) for the UK; Blau (1987), Gill
(1988), Evans and Leighton (1989b), Evans and Jovanovic (1989) and Dunn
and Holtz-Eakin (2000) for the USA; and Bernhardt (1994) for Canada.
Lin, Picot and Compton (2000) reported significant negative effects for
Canada.
4. For the UK: Rees and Shah (1986), Dolton and Makepeace (1990), Taylor
(1996), and Clark and Drinkwater (1998). For the USA: Borjas (1986),
Gill (1988), Borjas and Bronars (1989), Evans and Leighton (1989a), Boyd
(1990: for blacks), Tucker (1990: for non-professionals), Fujii and Hawley
(1991), Blanchflower and Meyer (1994), Robinson and Sexton (1994), Carr
(1996), Bates (1995, 1997), Boden (1996), Schuetze (2000), Flota and Mora
(2001) and Lofstrom (2002). For other countries: Carrasco (1999) for Spain,
Blanchflower (2000) for nineteen OECD countries, Goedhuys and Sleuwaegen (2000) for Cote
dIvoire, Cramer et al. (2002) for the Netherlands and
Moore and Mueller (2002) for Canada.
5. For the UK: Robson (1998a), Taylor (2001) and Clark and Drinkwater (2002).
For the USA: Brock and Evans (1986), Evans and Leighon (1989b), Evans
and Jovanovic (1989), Boyd (1990: for Asians), van Praag and van Ophem
(1995), Schiller and Crewson (1997), and Dunn and Holtz-Eakin (2000).
108
6.
7.
8.
9.
10.
11.
12.
13.
and Preisendorfer
109
14. But Tucker (1988) offers some evidence from a probit model suggesting that achievement motivation significantly affects the choice of selfemployment.
15. Brock and Evans (1986) argued that many of the sociologists and psychologists studies are based on questionable sampling methods: The scientific
validity of these studies, which are seldom based on random samples and often use ambiguous or overly inclusive definitions of an entrepreneur, is open
to question (Brock and Evans, 1986, n. 9, p. 190). A salient bias could be
towards sampling only successful entrepreneurs, leading to the danger that
observed traits are confused with entrepreneurial experience (Amit, Glosten
and Muller, 1993).
16. KPMG (1999) observed that these lifestyle motives for self-employment
were strongest among founding entrepreneurs and weakest for those operating
growing and innovating firms, who were more likely to stress rapid further
growth as an objective.
17. See Scase and Goffee (1982) and MacDonald and Coffield (1991), whose
(rather unenthusiastic) survey respondents appeared to be more concerned
with making a living (getting by) than with being autonomous. Also, in
Lees (1985) survey of redundant British steelworkers who subsequently became self-employed, one-third claimed they did so because they had no other
choice. A similar proportion claim to be necessity entrepreneurs in the international GEM study (Reynolds et al., 2002), with higher proportions in
developing than in developed countries. In the USA, for example, only 8 per
cent of the self-employed ascribed their mode of employment to a lack of alternatives (Dennis, 1996). Of course, these responses are all based on declared
rather than revealed preferences, so should be treated with commensurate
caution.
18. C.f. Adam Smith (1937): The chance of gain is by every man more or less
overvalued, and the chance of loss is by most men undervalued.
19. See Parker (1996), Robson (1996), and Cowling and Mitchell (1997), respectively.
20. According to Blanchflower and Oswald (1990), higher proportions of British
self-employed people than employees believe that welfare benefits should be
reduced to increase self-reliance, and that people on unemployment benefit
were on the fiddle. Also, substantially more self-employed people described
themselves as Conservative voters, compared to employees; and fewer selfemployed people favoured redistribution from the rich to the poor than employees did.
21. For UK evidence see Taylor (1996, 2001), Blanchflower and Oswald (1998),
and Burke et al. (2000). For US evidence see Evans and Leighton (1989b),
Fairlie (1999) and Hout and Rosen (2000). See also de Wit and van Winden
(1989, 1990), Laferr`ere and McEntee (1995), Lindh and Ohlsson (1996)
and Uusitalo (2001) for evidence from the Netherlands, France, Sweden and
Finland, respectively.
22. Negative effects were reported by Laferr`ere and McEntee (1995) and Lindh
and Ohlsson (1996); positive effects appear in the North American studies of
Borjas and Bronars (1989) and Bernhardt (1994).
110
23. See also Lentz and Laband (1990), who split followers into heirs
and non-heirs to identify the role of managerial experience from mere
goodwill/network/brand-loyalty effects, since heirs have the latter but nonheirs do not. Lentz and Laband found that the importance of being a follower for relative self-employment earnings was similar for both groups, suggesting that the common factor was parental managerial experience. In any
case, only a minority of followers had inherited or purchased their parents
business.
24. See also Iyigun and Owen (1999), who argued that technological progress
generates greater income but also greater absolute risk in entrepreneurship,
such that the net incentive to become an entrepreneur decreases as economies
develop. However, this result is not general, since one can imagine many kinds
of technological change which in conjunction with particular preferences (e.g.
decreasing absolute risk aversion) lead to the opposite result. On a different
tack, Lazear (2002) argued that if entrepreneurs are jacks of all trades who
have to deploy a mix of skills in production, then technological progress that
demands additional skills requirements will decrease the number of suitably
equipped individuals and therefore also the number of entrepreneurs.
25. By relaxing the borrowing constraint in Banerjee and Newmans (1993)
model, financial development might also boost entrepreneurship. It should
be borne in mind, however, that economic and financial development often
go together. So financial development of itself is unlikely to be a practical
panacea for slow economic development.
26. See Fairlie and Meyer (2000) for further evidence against the ability of TFP
to explain trends in US self-employment.
27. Examples of the probit approach with industry and/or occupation dummies
include Long (1982a), Moore (1983a), Brock and Evans (1986), Evans and
Leighton (1989a) and Schuetze (2000) (all US studies); and Georgellis and
Wall (2000) for the UK.
28. According to Harvey (1995), self-employment accounted for 45 per cent of
the workforce in the UK construction industry in 1993; the next highest proportion was 14 per cent in Distribution, Hotels and Catering. Curran and
Burrows (1991) calculated that the highest self-employment growth rates over
19849 were in manufacturing rather than in services, especially in construction and engineering, with business and finance being the fastest growing
self-employment service sectors.
29. See, e.g., Hamilton (1989), Taylor (1996), Blanchflower and Oswald (1998)
and Clark and Drinkwater (1998, 2000) for the UK; van Praag and van
Ophem (1995) and Bruce (2000) for the USA; and Lindh and Ohlsson (1996)
for Sweden. Simple regional cross-tabulations bear out this finding (Whittington, 1984), though the international cross-section evidence presents a more
mixed picture (Reynolds, Storey and Westhead, 1994).
30. For supporting evidence, see Gordus, Jarley and Ferman (1981), Laferr`ere
and McEntee (1995) and Carroll and Mosakowski (1987). Moore and
Mueller (2002) observed that Canadians collecting unemployment benefit
were less likely to enter self-employment, but that those with longer unemployment spells were more likely to enter it. Although layoffs and redundancy
31.
32.
33.
34.
35.
36.
111
and Staber (1991) and Meager (1994) for evidence from other
countries, and Storey (1991, 1994a) for a partial overview.
Hamilton proposed a positive relationship at low levels of unemployment,
when there are plentiful opportunities to start a new business. But at higher
unemployment rates (in excess of 20 per cent), the supply of new business
opportunities and entrepreneurs to exploit them decline. Supporting evidence
of a concave quadratic relationship appears in Georgellis and Wall (2000).
See Robson (1991), Black, de Meza and Jeffreys (1996), Parker (1996) and
Cowling and Mitchell (1997). Cowling and Mitchell argued that the longterm unemployment rate has a positive effect, and the short-term unemployment rate a negative effect, on the aggregate self-employment rate. This is
because the short-term unemployed may return to paid-employment rapidly
whereas the long-term unemployed eventually become discouraged by fruitlessly seeking paid-employment, turning to self-employment as a last resort.
Meager (1992a, 1994) highlights a potential problem with regressing the
aggregate self-employment rate, n S, on the unemployment rate. n S is commonly defined as the number of self-employed people as a proportion of the
total workforce. The latter includes the number of unemployed people, so imparting bias to estimates of the self-employmentunemployment rate relationship. In principle it is possible to bypass this problem by defining the workforce
to exclude the unemployed. This implicitly treats the labour force participation decision separately from occupation choice. However, it does not address
Meagers other critique, which is that inflow data to self-employment allow
more accurate tests of the push and pull hypotheses than stock data.
This is reflected in scatter plots of self-employment and unemployment rates
for individual countries. As Meager (1992a) observed, no general pattern
emerges.
For example, Hamilton (1989) hypothesised a negatively sloped cross-section
schedule in (n S, nU ) space that shifts upwards north-easterly over time.
Clearly, however, it is possible to have north-westerly as well as the northeasterly shifts that Hamilton envisaged, rendering the time-series relationship
ambiguous a priori.
112
37. Georgellis and Wall (2000) discovered a greater role for economic variables to
explain regional variations in self-employment rates, especially average levels
of human capital. They also found that the North of Britain is an outlier in the
sense that, unlike any other region, unexplained fixed effects explain virtually
all of the variation in those data.
38. Long (1982a), Brock and Evans (1986), Boyd (1990: for blacks but not
Asians), Laferr`ere and McEntee (1995) and Lindh and Ohlsson (1996) found
significant positive effects from urban dummies, but Reynolds, Storey Westhead (1994) and Carrasco (1999) did not.
39. For self-employment studies reporting negative effects, see Evans and
Leighton (1989a), Black, de Meza and Jeffreys (1996), Parker (1996), Robson (1996, 1998b) and Cullen and Gordon (2002). For new-firm foundation
studies, contrast Audretsch and Acs (1994), who found a negative effect, with
Highfield and Smiley (1987) and Hudson (1989), who did not.
114
(12.3 per cent). And using 1990 US Census data, Fairlie and Meyer
(1996) found that non-rural male self-employment rates varied substantially across 60 ethnic and racial groups, both before and after controlling for age, education, immigrant status and length of time spent in the
USA. For example, only 4.4 per cent of black males worked for themselves, compared with 27.9 per cent of Korean-American men, while
European-Americans had self-employment rates close to the US average.
Members of ethnic groups from the Middle East and neighbouring countries such as Armenia, Israel and Turkey also had high self-employment
rates; but Hispanics (other than Cubans) had low self-employment rates.
Fairlie and Meyer (1996) also noted some diversity within the black
ethnic group, with black Africans and Caribbeans having slightly higher
self-employment rates than other black Americans (but still below the
US average). This and similar evidence from the UK cautions against
treating ethnic minorities as a single homogeneous group.
Third, self-employed minority workers tend to earn less on average than
their white self-employed counterparts. According to Borjas and Bronars
(1989), mean self-employment income among black males in 1980 was
about half that of self-employed white males, while the mean income of
male Hispanics was nearly 30 per cent less than that of whites (see also
Flota and Mora, 2001). In contrast, self-employed Asians receive very
similar returns to whites. Blacks also have lower average business receipts
than members of other minority groups (Borjas and Bronars, 1989).
Exploring the factors underlying these stylised facts is the aim of
section 4.1, which focuses on ethnic minority entrepreneurship. Both
theoretical models and empirical evidence are discussed. Section 4.2
treats female entrepreneurship, and section 4.3 discusses particular issues relating to immigration.
4.1
4.1.1
115
Discrimination
Employer discrimination
If employers have an exogenous taste for discriminating against members
of ethnic minorities, M, what are the implications for ethnic entrepreneurship, and entrepreneurial profits of minority members? Previous researchers have proposed two outcomes from employer discrimination
(Sowell, 1981; Moore, 1983b; and Metcalf, Modood and Virdee 1996):
1. By preventing members of minorities from obtaining jobs in paidemployment or by restricting them to relatively low-paid jobs, discrimination increases the attractiveness to them of entrepreneurship.
In other words, entrepreneurship can act as an escape route from
employer discrimination, implying greater participation in entrepreneurship for these individuals.
2. Discrimination reduces the minority employment wage below that
of non-minority members, i.e. it reduces w M/w NM, so the ratio of
minority to non-minority average entrepreneurial profits, M/ NM,
exceeds the ratio of minority to non-minority wages, w M/w NM (Moore,
1983b).
However, if we equate entrepreneurship with self-employment, point 2
is not borne out by the evidence (see Moore, 1983b; Borjas and Bronars,
1989; Fujii and Hawley, 1991; Clark and Drinkwater, 1998). One reason is that crowding of Ms into entrepreneurship competes down their
output price and hence their profits, M, until M/ NM = w M/w NM.
Alternatively, even if the distribution of ability within each ethnic group
is identical, there are circumstances under which employer discrimination might indirectly reduce M relative to NM. This could occur if entrepreneurs profits are an increasing function of entrepreneurial ability
x: j = (x j ) ( j = {M, NM}), with j / x > 0 j . To see this, let the
distribution function of x, G(x), be the same for each group. Recall that
w NM > w M because of employer discrimination. Denote the marginal
entrepreneur in each ethnic group, i.e. who is indifferent between paidemployment and entrepreneurship, by x NM and x M, respectively. These
individuals are defined by the equalities
w NM = (x NM) and
w M = (x M) .
Then it follows that w NM > w M (x NM) > (x M), i.e. the minority
marginal entrepreneur is less able, and less well remunerated, than the
non-minority marginal entrepreneur. There are also more M than NM
entrepreneurs in equilibrium, since 1 G(x M) > 1 G(x NM).
Another problem with the employer discrimination hypothesis is that
point 1 above is inconsistent with the facts about American and British
116
blacks, who have lower self-employment rates than whites. Although some
ethnic minorities (such as Korean-Americans or British Asians) have
above-average self-employment rates, this is an unsatisfactory defence
of the employer discrimination hypothesis because it fails to explain why
employers discriminate against some ethnic groups but not others.2
Discrimination in the capital markets
If lenders discriminate against ethnic minorities, then members of these
minorities may find it harder to borrow and become entrepreneurs. The
stylised facts are stark. Blanchflower and Oswald (1998) reported that
more than 60 per cent of black Americans are turned down for loans by
US banks, compared with just 30 per cent for whites. Knight and Dorsey
(1976), and more recently, Bates (1997), reported that blacks are granted
smaller loans for start-ups than whites even after controlling for characteristics such as education and financial assets. Similar outcomes have
been observed in the venture capital market (Bates and Bradford, 1992).
An implication is that blacks are both less likely to be able to start businesses and more likely to be under-capitalised and therefore vulnerable
to failure than whites. A striking finding from Bates (1991) analysis of
1982 CBO data is that, controlling for a range of human capital, physical
capital and demographic traits, blacks failure rates would have been no
different from those of whites if they had received the same amounts of
external finance.
The UK evidence paints a somewhat different picture. There, the main
financing difference appears not to be between whites and blacks, but
between Asians and Afro-Caribbeans. According to Jones McEroy and
Barrett (1994), Asians have a higher probability of obtaining a bank loan
than Afro-Caribbeans and whites, and leverage more funds from banks.
These facts cast doubt on the proposition that UK banks are guilty of
blanket discrimination, though it does beg the question about why AfroCaribbeans have greater difficulties in raising bank loans than whites do
(Bank of England, 1999).
One possible answer is statistical discrimination. This describes the situation where an ethnic group has different characteristics on average from
others, which are then used to adversely screen all members of that group.
For example, UK minority-owned businesses tend to establish themselves
in sectors such as retailing, transportation and catering, that have aboveaverage failure rates (Bank of England, 1999). Also, blacks tend to have
lower wealth levels on average and hence less collateral than whites do.
Even if banks do not discriminate on the basis of ethnicity, bank competition may generate bank lending rules that reward high-collateral and safesector start-ups with larger loans resulting in outcomes that resemble
117
118
(4.1)
119
(4.2)
Borjas and Bronars two key results then follow directly: (i) In equilibrium the mean income of M sellers will be lower than that of NM sellers.
Skilled Ms have greater incentives to enter paid-employment than skilled
NMs. (ii) NM sellers have a higher return to ability than M sellers. These
predictions contrast with those of the employer discrimination model
and accord with the third stylised fact listed in the introduction to this
chapter. Using a sample of 1980 US Census data, Borjas and Bronars
found some support for their predictions, observing significant positive
selection into self-employment among whites, significant negative selection among Hispanics and Asians (see also Flota and Mora, 2001), but
zero selection among blacks.
While Borjas and Bronars model appears useful for understanding
ethnic differences in self-employment rates, it seems less suitable for
explaining gender differences. As Aronson (1991) pointed out, women
are commonly employed in sales jobs, which would not be optimal if
profit maximising firms knew that consumers discriminated against them.
Another problem with the consumer discrimination hypothesis is that
black businesses are relatively common in industries patronised by white
customers (Meyer, 1990). One reason could be franchising, since franchisors often discourage attempts by franchisees to differentiate their
units (Kaufmann and Lafontaine, 1994) so reducing consumers ability
to discriminate. Indeed, Williams (2001) found that black entrepreneurs
were more likely than any other racial group to become franchisees.
Williams also estimated that blacks earned more as franchisees than they
would as independent business owners, a finding that is also consistent
with Borjas and Bronar discrimination model. If Williams findings are
120
Positive factors
Discrimination can be regarded as a factor that pushes members of ethnic minorities into the escape route of entrepreneurship. Another possibility is that pull factors make entrepreneurship positively attractive
to members of minority groups. The following pull factors have been
proposed:
1. Positive expected relative returns in entrepreneurship Positive rewards
in entrepreneurship, rather than discrimination in paid-employment,
may explain high rates of entrepreneurship among some ethnic groups
(Bearse, 1984). For example, using US and British data, respectively,
and implementing the structural probit model outlined in chapter 1.
subsection 1.6.2, Fairlie and Meyer (1996) and Clark and Drinkwater
(2000) found that relative income differences helped explain differences in self-employment rates across ethnic groups.
2. Ethnic enclaves Enclaves are geographical clusters of ethnic group
members who form self-supporting economic communities. Enclaves
can offer information networks, sources of credit, niche markets for
the output of ethnic entrepreneurs and a steady supply of workers,
possibly drawn from close-knit extended families (Light and Bonacich,
1988). For example, ethnic minority entrepreneurs may know more
about the tastes of ethnic consumers, in such protected markets
as clothing, foodstuffs, religious goods and services (Aldrich et al.,
1985). These factors, and the absence of consumer discrimination
by co-ethnics, presumably increase the opportunities and ease with
which minority group members can operate a business. Set against
this argument, however, is the possibility that the scope for expanding operations into broader markets is more difficult for enclave
producers. Also, enclaves can foster intense competition among ethnic entrepreneurs, so limiting entrepreneurial opportunities (Aldrich
and Waldinger, 1990) and reducing survival prospects (Bates and
Bradford, 1992). Furthermore, employment incomes may be relatively
high in enclaves since ethnic employers presumably do not discriminate against members of their own group. And opportunities for profitable entrepreneurship in enclaves may be limited if ethnic disposable
incomes and hence consumer demand are low.
The available evidence from a range of countries certainly points
to a concentration of self-employed immigrants and minorities in
particular industrial sectors. For example, US Census data from 1980
revealed that 27 per cent of self-employed immigrants were working
121
122
successful Asian-owned firms relied on social support networks in enclaves; and those with a predominantly minority clientele and located
in areas with large minority populations had significantly lower survival
and profitability rates than the average.
3. Culture Building on Webers (1930) Protestant Ethic thesis, it is possible that attitudes to entrepreneurship are determined by the religion
of particular ethnic groups (Rafiq, 1992). Some prominent figures
in Islam and the Sikh religion were businessmen; and some Hindu
castes specialise in business activities. In Britain, Clark and Drinkwater
(2000) found that, all else equal, Muslims, Hindus and Sikhs had significantly higher probabilities of being self-employed than Christians
from ethnic minorities were. Related to this, some Asian cultures
stress self-sufficiency, thrift and hard work, which may help to explain
high Britain Asian self-employment rates (Borooah and Hart, 1999).
However, most empirical studies have found religion variables to be
insignificant (Pickles and OFarrell, 1987; OFarrell and Pickles, 1989;
de Wit and Winden, 1989; de Wit, 1993), though there are exceptions
(Carroll and Mosakowski, 1987; Clark and Drinkwater, 2000).
Poor command of the host countrys language might increase the
likelihood of ethnic self-employment, by restricting employment opportunities in the formal employment market without affecting trading
opportunities among members of ones own language group (Bates,
1997). The evidence on the issue derived from probit models is mixed,
with some studies finding that poor English-language skills increase
self-employment participation (Boyd, 1990; among Asians but not
blacks; Fairlie and Meyer, 1996; Portes and Zhou, 1996; Clark and
Drinkwater, 2002), and others finding the opposite (Evans, 1989;
Flota and Mora, 2001; Lofstrom, 2002). Flota and Mora (2001)
claimed that poor English fluency was associated not only with lower
self-employment propensities, but also with lower self-employment incomes. Another possibility is that belonging to a minority group may
create a feeling of insecurity that encourages a drive for entrepreneurial
success (Kilby, 1983; Elkan, 1988).6
4. Role models Applying quantile regression techniques to 1984 SIPP
data, Hamilton (2000) found that black self-employment incomes are
similar to those of whites at the three lower quartiles but are significantly lower than whites incomes at the upper quartile. An absence
of black entrepreneurial superstars may contribute to the lower selfemployment rates of blacks generally as well as accounting for their
lower average self-employment incomes. A lack of black role models
within and outside the immediate family might also explain why Hout
and Rosen (2000) found intergenerational links in self-employment to
be strong for every American ethnic group except blacks.
4.1.3
123
Conclusion
The literature has identified both negative and positive factors that impinge on ethnic entrepreneurship. Most of the negative factors are based
on some kind of discrimination. As we saw, however, the role of discrimination has been questioned on both theoretical and empirical grounds.
In the USA, for example, Bates (1997) concluded that the substantial human and physical capital inputs by Asian-American entrepreneurs relative
to blacks help explain the formers substantially higher self-employment
rates.
Is it different personal characteristics, or is it different returns given
the same personal characteristics, that account for the observed differences in self-employment rates between ethnic groups? In an attempt to
answer this question, Borjas and Bronars (1989) estimated what average
minority self-employment rates would have been if the coefficients from
a self-employment probit regression based on a white subsample (i.e. imposing the same returns to characteristics) were applied to non-whites.
To make this precise, consider the probit regression equation (1.7), and
(suppressing the intercept purely for notational clarity) let NM denote
the estimated coefficients of that equation obtained using a purely nonminority data sample. Then if only M members characteristics were
different, the predicted probability of M self-employment would be
p M =
( Wi )
NM
i M
(4.3)
124
explain lower black entry rates (notably lower assets and a lower incidence of self-employed fathers), they did not help explain higher black
exit rates.8 According to Fairlie, education was not a significant factor
for either entry or exit. Fairlie concluded that the scope for policy intervention to increase black self-employment rates is limited. Even quadrupling current black asset levels was estimated to reduce the ethnic gap
in self-employment entry rates by only 13 per cent. Bates (1984) also
expressed doubts about the potential for government policies (such as
the SBAs Equal Opportunities Loan Programme and US Federal government procurement policies) to stimulate business ownership among
ethnic minorities.
4.2
Female entrepreneurship
4.2.1
125
126
The following stylised facts about labour supply patterns emerged from
Devines (1994a) study of American self-employed females. First, selfemployed females were likelier than female employees or males in either employment category to be part-time workers.11 Second, part-time
female self-employment was commonest among those who were married with a spouse present. Third, work hours of part-time and full-time
self-employed women were more dispersed than female employees work
hours. Devine concluded that self-employed females faced greater choice
than males did in terms of the hours of work they supplied. That may
partly explain Lee and Rendalls (2001) finding that white American
women had shorter spells in self-employment on average than men did,
despite having worked similar numbers of spells.
Education has also been identified as an important aspect of female
self-employment. Cowling and Taylor (2001) showed that on average
British self-employed females possessed more advanced educational qualifications than self-employed own-account (but not employer) males.
Advanced education also appears to be associated with female selfemployment in the USA.12 This finding might be explained by the concentration of female employees in clerical and administrative jobs which
require less advanced qualifications and that yield work experience that
is ill-suited to switching into self-employment (Boden, 1996).
A drawback of several of the above studies is that they ignore relative
earnings as a determinant of female self-employment. This has been partially dealt with by Devine (1994b), who used CPS data over 197587
to estimate the earnings function (1.1), in order to compare potential
female incomes by occupation. The predicted employment earnings of
self-employed females exceeded those of females who were employees.13
Devine also reported that female self-employment participation rates did
not vary systematically by job skill level. This is inconsistent with the
hypothesis that skilled women choose self-employment to avoid a glass
ceiling of limited earnings in self-employment; and also with the notion that women use employment skills as a launching pad for entry into
self-employment.
To the authors knowledge there has not yet been an application of
the structural probit model (described in chapter 1, subsection 1.6.2) to
female self-employment. Such an exercise would be valuable provided
that a sufficiently large data sample could be obtained.
4.2.2
127
the US SBA (1986) estimated that the ratio of female to male selfemployment incomes remained roughly constant at around 0.50 between
1974 and 1984, at the same time as the ratio of female to male employment incomes increased from 0.46 to 0.53. These numbers include both
part-time and full-time workers. Using 1983 SIPP data, Haber, Lamas
and Lichtenstein (1987) estimated that the ratio of US median full-time
female to male self-employment incomes was only 0.30, compared to a
ratio of 0.60 in paid-employment. Self-employed females also suffer a
30 per cent median earnings disadvantage relative to female employees
(Becker, 1984; Devine, 1994a). Female self-employed workers do better on average in some other countries, with female/male earnings ratios
reaching 87 per cent in the case of Australia (OECD, 1986).
Aronson (1991) offered an interesting historical perspective on female
relative self-employment incomes. He cited evidence that, in the interwar and early post-war periods, self-employed females earned more than
female employees did although the comprehensiveness of these data
is limited. What is clear is that between 1955 and 1984 the relative
earnings position of self-employed females declined steadily relative to
their employee counterparts and also to self-employed males. It is less
clear whether this decline reflects greater part-time participation by selfemployed females or a relative worsening of the human capital of females
choosing self-employment. While the inclusion of incorporated selfemployed workers in sample data tends to close the income gap of male
self-employed relative to male employees, it makes relatively little difference to the female self-employedemployee income gap (Aronson, 1991).
That presumably reflects the small number of incorporated self-employed
females.
For the self-employed generally, it should be borne in mind that selfemployment incomes usually omit important additional dimensions of
job remuneration, such as health care coverage. Female self-employed
workers have relatively scant job-related health care coverage compared with female employees, male employees and male self-employees
(Devine, 1994a).
Why are female self-employment incomes relatively low? One reason is
that female self-employed workers have fewer years of experience than female employees or males (Aronson, 1991; Lee and Rendall, 2001). Also,
female self-employees tend to have more diverse backgrounds than their
male counterparts: women are more likely than men to set up a business
without having a track record of achievement, vocational training, or experience (Watkins and Watkins, 1984). Second, women have greater opportunities or preferences for potentially less remunerative home working,
as noted above. Third, females tend to operate a smaller scale of business,
128
utilising less capital and finance from banks and other lenders than males
do (Aronson, 1991). This might reflect a preference for smaller enterprises since these minimise the disruptions to a family that could result
from operating a larger enterprise. Of course, a lower capital base can
be expected to reduce future entrepreneurial incomes and increase the
probability of business failure. Carter, Williams and Reynolds (1997)
confirmed that female-owned businesses start on a smaller scale than
male-owned ones, and have higher discontinuance rates although they
stressed that this did not seem to be attributable to females being disadvantaged with respect to access to credit.14
A study by Hundley (2001a) sought to test these competing explanations against each other by applying an Oaxaca decomposition to
gender-specific earnings functions. To see how this works, write (1.1)
of chapter 1, subsection 1.5.3 in the form ln yi j = j Xi j + ui j , where the
j subscript denotes gender: j = f indexes females and j = m indexes
males. Consider a particular explanatory variable Xi j k . Letting an overbar
denote sample means and a hat denote a regression estimate, we can write
ln ym ln y f = m Xmk X f k + m f X f k ,
(4.4)
where y denotes annual earnings. The first term on the RHS of (4.4) is
the part of the average earnings difference attributable to characteristic
Xi j k . The other term is the part of the earnings difference that is unexplained by Xi j k .15 Hundley (2001a) found that, in terms of (4.4), the
most important explanatory variables were housework, work hours and
the number of young children, which together accounted for between
30 per cent and 50 per cent of the American annual self-employment
earnings gender differential. This suggests that women earn less than
men do because they spend less time managing and developing their
businesses. The next most important factor found by Hundley (2001a)
was industrial sector, which accounted for between 9 and 14 per cent
of the gender self-employment earnings differential. This captures the
concentration of women in the relatively unrewarding personal services
sector, and their under-representation in the more remunerative professional services and construction industries. Physical capital explained
only between 3 and 7 per cent of the differential, and other variables
(including experience) were even less important.
It is not just the case that female self-employees under-perform relative
to males in terms of their income. The same appears to be true of their
output, employment and turnover, according to overviews of US and UK
evidence conducted by Brusch (1992) and Rosa, Carter and Hamilton
(1996). As Du Rietz and Henrekson (2000) show, controlling for other
factors such as industrial sector attenuates, but does not eliminate, this
finding.
129
Conclusion
Despite its intrinsic interest and importance, the subject of female entrepreneurship has arguably not commanded the degree of research effort
that it deserves. Little is known about precisely why there is less female
than male entrepreneurship, why it is growing in popularity and why
self-employed females earn so much less on average than either females
in paid-employment or males in self- and paid-employment. Aronson
(1991) concluded that female self-employed and employed workers have
similar characteristics, and conjectured that they differ in their attitudes
to independence and in their taste for leisure relative to income. This
may partly explain the evidence that being married and having children
are such important determinants of female self-employment. However,
because tastes and attitudes are difficult if not impossible to observe and
quantify, it looks as though sharp tests of this conjecture will be hard to
devise.
4.3
It has been suggested that immigrants are likelier than native-born workers (natives henceforth) to be entrepreneurs, for the following reasons.
1. On average, immigrants are better educated and motivated than natives.
2. Immigrants have access to ethnic resources and social capital (Light,
1984), including a tradition of trading, access to low-paid and trusted
workers from the same ethnic group and access to a ready market of
niche products within an ethnic enclave.
3. Some immigrants are sojourners, who wish to immigrate temporarily
in order to accumulate wealth before returning to their homeland.
Entrepreneurship may be the most effective means to this end.
4. Immigrants turn to entrepreneurship because of blocked mobility in
paid-employment, owing to language difficulties, discrimination, or
possession of non-validated foreign qualifications.
5. Immigrants are self-selected risk takers by virtue of their willingness
to leave their homeland to make their way in a foreign country.
130
6. Among illegal immigrants, entrepreneurship in the form of selfemployment may be a means of escaping detection by the authorities.
7. Immigrants enter industries and occupations that have high rates of
entrepreneurship.
Empirical studies, which invariably measure entrepreneurship as
self-employment, have generated diverse findings about the role of
immigration. Borjas (1986) and Lofstrom (2002) claimed to find higher
self-employment rates among immigrants than natives in the USA, while
Brock and Evans (1986) found no such pattern. All of these studies used
US Census data. Part of the problem may be one of classification: Light
(1984) emphasised the diversity of self-employment experience among
immigrants by home country, which he attributed to different traditions
of commerce. This theme was taken up by Yuengert (1995), whose analysis of 1980 US Census data indicated that immigrants from countries with
relatively high self-employment rates are likelier to become self-employed
in the US.16
The roles of some of the factors listed above have also been challenged.
Regarding 2 above, Bates (1997) showed that most immigrant business
owners obtained most of their finance from their personal wealth and from
mainstream lenders, rather than from social resources. Immigrant businesses depending on the latter tended to be marginal and more prone to
failure. Regarding 3, it does not necessarily follow that entrepreneurship
is a better way of getting rich than paid-employment. While some studies
have claimed that immigrants do better in self-employment than in paidemployment (Borjas, 1986; Lofstrom, 2002), the income experiences of
immigrants can vary considerably, and sometimes entail disadvantage
(Borjas and Bronars, 1989; Portes and Zhou, 1996). An important aspect to this debate appears to be duration of residence in the host country.
Both Brock and Evans (1986) and Lofstrom (2002) found that longer selfemployment spells in the host country by immigrants eventually reverse
initial earnings disadvantage relative to natives in contrast to immigrant employees whose relative earnings disadvantage tends to persist
throughout their lifetimes.
Another problem for the sojourner theory is that many immigrants ultimately choose to remain in the host country, whatever their original
intentions were. Fairlie and Meyer (1996) found that immigrants who
had been in the USA for over thirty years had higher self-employment
rates than immigrants who had been in the USA for less than ten years
and who were presumably more likely to be sojourners (see also Lofstrom,
2002). Immigrant self-employment rates that increase with length of residence might reflect not only the positive income-duration relationship
mentioned above, but also other factors. These might include (i) greater
131
132
living in the USA. Second, the cross-cohort effect (the second term) usually indicated a greater propensity for more recent immigrant cohorts to
choose self-employment relative to earlier cohorts. This is reflected in
the higher self-employment rates among more recent immigrants, which
is consistent with the notion that more recent immigrants to the USA
have been of lower average quality, at least in terms of their employment
opportunities in the formal labour market.17
An advantage of Borjas decomposition technique is that it separates two important and distinct aspects of immigrant self-employment
propensities. But it has yet to be widely adopted by researchers in the field.
N OT E S
133
8. But see Bates (1997), who had greater success in explaining high black business exit rates, especially in terms of low levels of capital inputs.
9. As well as Devine (1994a, 1994b), see also Robinson and Sexton (1994),
Carr (1996) and Cowling and Taylor (2001). Some rare contrary evidence
that marital status is unimportant comes from a study by Caputo and Dolinsky
(1998), who controlled for many household level variables see below. On
the importance of the presence of children, see Macpherson (1988), Evans
and Leighton (1989a), Connelly (1992), Boden (1996), Carr (1996), Caputo
and Dolinsky (1998) and Wellington (2001).
10. See also Macpherson (1988), who reported a significant positive effect on
the probability of self-employment among married American women from
husbands incomes.
11. Calculations made from the BHPS data-set by the present author revealed
that females comprise only 16 per cent of the full-time, but 70 per cent of the
part-time self-employed workforce in Britain.
12. See Macpherson (1988), Evans and Leighton (1989a), Devine (1994a), Bates
(1995) and Carr (1996).
13. See also Macpherson (1988), who estimated (1.4) and reported negative
selectivity for female employees, implying that their average earnings were less
than what self-employed females could have obtained in paid-employment.
14. For contrary evidence that gender has an insignificant effect on business survival rates, see Kalleberg and Leicht (1991) and Bruderl
and Preisendorfer
(1998).
15. Note that we can alternatively write an analogous expression using f in the
first term of the RHS of (4.4). Since the choice is arbitrary, results based on
this decomposition method should be quoted for both calculations.
16. Yuengert estimated that 55 per cent of the immigrantnative self-employment
rate differential was attributable to immigrants having above-average homecountry self-employment rates than the USA. However, other researchers
have obtained contrary evidence. Evans (1989) found that immigrant
Australian business owners who were employers were significantly more likely
to have obtained labour market experience in the host country, and significantly less likely to have obtained it their home country. See also Fairlie and
Meyer (1996).
17. It has been suggested that shifts in US immigration policy that have prioritised
family issues have been responsible for a decline in immigrant quality, at least
when measured in terms of employment earnings.
Part II
138
The present chapter investigates these issues. Along the way, the role
of collateral, loan sizes, lenderborrower relationships and group lending
will also be discussed. We will leave aside topics such as what lenders and
borrowers think about each other, what induces entrepreneurs to apply
for loans and how entrepreneurs can write business plans to improve
their chances of successfully obtaining a loan. These issues are covered
in any number of texts within the Business and Management literature.
For notational brevity, lenders will be referred to simply as banks henceforth, and any new entrepreneurial investments, whether undertaken by
incumbent entrepreneurs or new entrants, will be called ventures.
This chapter emphasises the importance of asymmetric information
for the debt finance of new ventures. Information is often asymmetric because while entrepreneurs may have accurate information about
the quality of their risky proposed ventures and their ability and commitment to expedite them, banks often cannot perfectly distinguish the
quality of loan applications from each other. Reasons include the lack of
a track record for new ventures and prohibitive costs of acquiring reliable
information about them. There is no equivalent institution to a credit
rating agency for entrepreneurs; banks have to rely on their own imperfect screening devices. It will be assumed below that although banks can
screen entrepreneurs into groups defined by some observable characteristics, there is invariably also some residual imperfect information that
forces them to pool, at least initially, heterogeneous risk types together
within each group.
There is now an extensive economic literature on the efficiency of debt
financed ventures in general, and on credit rationing of entrepreneurs in
particular. Credit rationing has also received considerable attention in
policy circles, at least since the publication of influential reports by the
Federal Reserve System (1958) in the USA, and the Bolton and Wilson
reports (HMSO 1971, 1979) in the UK. These reports contended that
there was a general shortage of financial capital to fund new start-ups
and expand existing small businesses. The reports prompted the creation
of government-backed loan guarantee schemes for small firms, described
and evaluated in chapter 10, subsection 10.1.1. It is hard to assess the
extent to which the views of these reports reflected rather old-fashioned
conditions in banking and credit prior to the financial de-regulation of
the 1980s and 1990s. For example, a subsequent UK government report
(HMSO, 1991) concluded that small firms in Great Britain currently
face few difficulties in raising finance for their innovation and investment
proposals in the private sector (1991, p. 17). In contrast, the SBA (1996)
reiterated its concern that private capital markets still do not provide
adequate start-up finance.
139
140
Quantity
Supply
LD
Lm
LS
Demand
0
Dcr
Dm
Debt repayment, D
141
142
result that is robust to the case where banks as well as entrepreneurs are
risk averse (Olekalns and Sibly, 1992). However, as in other implicit
contract models there is always an incentive for one party to break the
contract, ruling out implicit contracts in competitive equilibrium.
4. Uncertainty (Clemenz, 1986, sec. 5.3). If venture returns are an increasing function of loan size then entrepreneurs profit is a convex function of loan size, since debt repayments are fixed and entrepreneurs
losses are bounded in bad states of nature. Greater uncertainty increases the requested loan size, as entrepreneurs seek to gain from the upside
of managing larger ventures without taking account of the increase
in downside risk borne by the banks. Anticipating this, banks limit
their losses by capping loan sizes (see also de Meza and Webb, 1992;
Bernhardt, 2000).
5. Type I credit rationing can facilitate efficient contracting under
asymmetric information (Besanko and Thakor, 1987b; Milde and
Riley, 1988). This idea is explained in subsection 5.1.3.
6. Monitoring costs (Gray and Wu, 1995). The logic here is the same as
for the Barro (1976) model described above.
There are several reasons why Type I rationing has received less attention in the literature and among policy makers than Type II rationing.
First, Type I rationing arguably does not capture the sharpest form of
credit rationing. That is given by Type II rationing, where loans are refused altogether. Second, in most models of Type I rationing all borrowers
obtain an efficient amount of funds and can still set up in business so
it is not clear that it is in any sense a problem to be addressed. Third,
the Type I rationing outcome is not robust. It is straightforward to create
models in which borrowers receive larger loans than they would like the
opposite of Type I rationing. This could occur, for example, if banks
administrative costs depend on the number of loans made rather than
the size of loans. Then cost minimisation under competitive conditions
obliges banks to make a few large loans rather than many small ones,
yielding the required result.
5.1.2
143
processing costs that might occur, for example, if applicants can approach more than one bank (Thakor and Calloway, 1983; Thakor, 1996).
Third, banks might identify particular loan applicants as inherently dishonest and almost certain to take the money and run. Banks would
then deny credit outright to these borrowers. Fourth, starry-eyed entrepreneurs might be over-optimistic about the prospects of their venture
(see chapter 3, subsection 3.2.3), and claim to be rationed by objective
banks that refuse a loan because they would not expect to break even on
these ventures at any interest rate.5 But these last two outcomes resemble
redlining more than credit rationing.
More interesting, and arguably more plausible, models of Type II credit
rationing are based on asymmetric information about the value of new
ventures. These models assume that individuals with new investment
ventures are heterogeneous in a manner which (a) impacts on banks expected returns, and (b) is private information to themselves and hidden
from banks. Individuals who are good risks from the banks viewpoint
cannot credibly signal their type because bad risks always possess the
incentive to untruthfully emulate them. As stated in the introduction
to the chapter, it is assumed below that the imperfect information is
residual in the sense that bank screening has already been performed.
It is important to be clear about this point, since its oversight has sometimes generated confusion (see, e.g., Stiglitz and Weiss, 1987, response to
Riley, 1987).
It is helpful to set out the assumptions used in most of these models.
Exceptions will be noted in the text below as and when they arise.
A1. Entrepreneurs are heterogeneous; banks do not observe individual
entrepreneurs types but do observe the frequency distribution of types.
A2. All banks and entrepreneurs are risk neutral, i.e. each maximises
expected profits.6
A3. All banks are identical and competitive, making zero profits. This is a
convenient simplification because it ensures that there is neither entry
into nor exit from the capital market. Notice that this assumption does
not necessitate a countable infinity of banks: Bertrand duopolists who
compete on price (i.e. the interest rate) also generate the competitive
outcome.
A4. Entrepreneurs undertake only one venture, into which they plough
all their wealth B, and which requires a single unit of capital that is
borrowed from a bank.
A5. There is a single period and a stochastic venture return R, which can
take one of two outcomes at the end of the period: R s in the success
state, or R f in the failure state. R s > D > R f 0, where D = 1 + r is
the mandated debt repayment, and r is the risky interest rate.
144
A6. Banks obtain funds from depositors, who are rewarded with a safe
(and endogenously determined) gross deposit rate, , where 1 < <
D. The supply of deposits (from outside investors) is an increasing
function of . Banks therefore compete in both the deposit and loans
markets.
A7. There is a standard debt contract, which specifies a fixed repayment
(henceforth called the gross interest rate, or simply the interest rate) of
D in non-bankruptcy states and requires the entrepreneur to declare
bankruptcy if this payment cannot be met. Banks seize R f in its entirety
in the bankruptcy state. Banks observe venture outcomes perfectly if
they monitor ex post returns. Banks optimally monitor all and only
defaulters, so there is no incentive for entrepreneurs to default (take
the money and run) unless the outcome is R f .7
A8. Entrepreneurs get:8
max{R D, B} .
(5.1)
A9. Individuals can choose between entrepreneurship (in which they obtain the uncertain return (5.1)), and safe investment.
A10. All prices are perfectly flexible and all agents optimise.
= 0.
max{R D, B} d F(R, )
(5.2)
145
d F(R, )
d
= DB
> 0.
(5.3)
dD
(D, )/
Thus as the interest rate is increased, the marginal venture becomes
riskier, generating adverse selection. That is, a higher interest rate causes
the entrepreneurial pool to be dominated by risky ventures.9 The expected return to a bank is therefore a decreasing function of , since the
bank gets R f = 0 and hence makes a loss on a venture if it fails; and the
incidence of failures increases as increases. This can be seen by writing
banks expected portfolio rate of return from lending at D as
(, D) dG()
(D)
(D) =
,
(5.4)
1 G()
where (, D) = D[1 F(D B, )] < D is the expected rate of return
D) >
to a venture characterised by (D, ) given R f = 0.10 Write := (,
(D) and differentiate (5.4) to obtain
g()
d
d
[1 F(D B, )] dG()
=
+
( )
. (5.5)
dD
dD
1 G()
1 G()
D has two effects on banks expected portfolio rate of return. The second term of (5.5) is positive, capturing the positive effect of a higher
interest rate on bank expected returns. But the first term is negative (by
(5.3)), capturing an adverse selection effect. That is, a greater interest repayment increases the risk of banks portfolios, leading to lower expected
bank returns. If the first term outweighs the second, banks expected returns may eventually become a decreasing function of the interest rate
D, as the pool of entrepreneurial ventures becomes dominated by risky
types. This is illustrated in figure 5.2(a), where Dcr , termed the bank
optimal interest rate, is the rate that maximises bank expected profits
and which therefore holds under competition.11 In this case, by assumption A6 the supply of funds also becomes a decreasing function of D.
This is illustrated in figure 5.2(b), which shows how credit rationing can
occur if there is a high demand for funds, and if Dcr < Dm , where Dm
is the market-clearing interest rate. Here banks deny credit to L1 L
146
(a)
0
Dcr
Number of loans, L
L1
High demand
Supply
(b)
L2
Low demand
0
D2
Dcr Dm
147
all offer the same expected return, yet which differ in terms of their risk.
Then moral hazard may occur: entrepreneurs respond to an increase in
the interest rate by choosing riskier ventures. Then, as in the adverse
selection problem, banks expected return function may begin to decrease in D, yielding a bank-optimal interest rate Dcr < Dm . As before,
banks may optimally ration credit rather than increase the interest rate to
eliminate an excess demand for loanable funds.
Credit rationing is not the only possible market failure in SWs model.
De Meza and Webb (1987, Proposition 5(A)) also showed that, irrespective of whether or not credit rationing occurs, there is bound to be
under-investment in entrepreneurial ventures in SWs model as long as
the supply of deposits is non-decreasing in (as assumed in assumption
A6). Thus there will be too few entrepreneurs for the social good, a problem exacerbated if credit rationing exists.12 A subsidy on interest income
can be recommended because it would increase both the equilibrium
number of entrepreneurs and social efficiency.
A second source of possible market failure in SWs model is redlining.13
To see this, suppose for expositional clarity that banks can distinguish
between three distinct groups of entrepreneurs. The groups are indexed
by , where can be good (g), bad (b) and OK (o). Each group has
an interior bank optimal interest rate, denoted by D , and an expected
return function (D). Let denote the deposit rate, which must be
unique in a competitive deposit market. As figure 5.3 shows, group g
will be fully served, and so will some members of the marginal group o;
but a group b generating returns of b (Db ) < cannot make a sufficient return to enable banks to compensate depositors at any interest rate.
Hence no member of group b will obtain funds, even though these ventures
may have above-average expected social returns. This group is redlined.
The only solution to redlining is to somehow induce an outward shift
in the supply of funds schedule, since that reduces . One possibility is universal government lending (Ordover and Weiss, 1981). However, it does not necessarily follow that such a policy would be welfareenhancing.
Although it has had an immense impact on the literature, SWs model
is not immune from criticism. One problem is that SW assumed, rather
than derived, debt to be optimal form of finance. Subsequent authors
(Cho, 1986; de Meza and Webb, 1987) showed that equity is actually the
optimal form of finance in the SW model. Furthermore, if all ventures are
financed by equity, SWs competitive equilibrium is first best, without any
credit rationing; and banks optimally randomise rather than fix interest
rates as SW assumed (de Meza, 2002). It is therefore necessary to appeal
to some factor outside the model that favours debt over equity finance if
SWs results are to remain relevant in a strict sense. That could entail,
148
g(D)
o(D)
b(D)
Dg
Do Db
149
returns, so Fe := F/e < 0. Entrepreneurs repay D if R > D, otherwise they default and the bank seizes the outcome of R. Bank expected
profits per loan at interest rate D (given effort e) is
D
B
(D) = D[1 F(D, e)] +
R d F(R, e),
(5.6)
0
from which it can be easily shown that de /d D < 0. Thus if the interest rate rises sufficiently, borrowers reduce effort. By (5.6), this may
reduce banks expected profits such that an interior bank-optimal interest rate Dcr < Dm may emerge.
2. Free ex post observation of venture returns by entrepreneurs creates a
hidden information moral hazard problem (Williamson, 1986, 1987).
Williamson assumed a continuum of venture return outcomes, R
[0, Rmax ]. Unlike SWs model, entrepreneurs are assumed to enjoy no
information advantage over banks about possible venture outcomes
ex ante: both agents know only the density and distribution functions
of returns f (R) and F(R). But unlike banks, entrepreneurs enjoy the
advantage of costlessly observing the ex post outcome of R. In the usual
way, banks optimally monitor ex post all and only ventures that declare
default. Monitoring is assumed to cost c > 0 per loan but is perfectly
effective. Bank expected profits are:
D
B (D) =
R d F(R) + D[1 F(D)] c F(D) .
(5.7)
0
150
The models outlined in the previous subsection are far from the only
ones that treat the relationship between entrepreneurs and banks. It is a
straightforward matter to propose plausible alternatives that generate only
market-clearing outcomes (e.g. de Meza and Webb, 1987). Also, there are
grounds for questioning how widespread credit rationing can be in practice when sources of finance other than debt contracts (e.g. trade credit,
equity finance and leasing) are available. The argument in this subsection
is that the theoretical case for credit rationing is not unassailable.
Below we describe a direct attack on the credit rationing hypothesis
based on the idea that rationing can be eliminated by writing more sophisticated financial contracts that reveal the hidden information on which
it depends. The key concept here is that agents have incentives to devise
contracts that break equilibria in which good and bad risks are pooled
together (pooling equilibria), replacing them with equilibria in which
good credit risks separate themselves from bad risks and thereby obtain a
lower interest rate (separating equilibria). For expositional ease, much of
the discussion will work with just two entrepreneurial types, a good type
g and a bad type b. The precise aspects that make them good or bad
151
Debt repayment, D
Db
b
b
Dg
g
Jb
Jg
BADg
Another bad, BAD
Figure 5.4 The use of two-term contracts to separate hidden types
152
the bank D and hence are more willing to endure more of BAD (e.g.
risking more collateral) in return for a lower D. Conversely, bs are less
willing to incur the cost of more BAD in return for a lower D because
they are more likely to default and thereby avoid repaying D.15 Crucially,
if Jb and Jg cross only once (the so-called single-crossing property),
then contracts b = (Db , 0) and g = (Dg , BADg ) separate types and are
consistent with banks iso-profit lines b and g . That is, g would prefer
a contract (D, BAD), just to the right of g along g , in preference to
b ; but b would prefer b to that contract. Hence if banks offer these two
contracts and under competition they must offer these contracts16
then each borrower type will self-select into the one that maximises their
utility, so revealing their type. This equilibrium is incentive-compatible:
each type does best under the contract that reveals their type. Masquerading as a different type will result in a lower payoff and so will not be
chosen.
What this shows is that, in principle a richer contract than one based
on interest rates alone can separate types. Type separation removes
all information asymmetries and hence the possibility that asymmetric
information-induced credit rationing can occur. This analysis readily generalises to more than two types. For example, with three types, three
different (D, BAD) contracts can be offered that accomplish separation.
However, with two or more dimensions of unobserved borrower heterogeneity, more than two contract terms are needed to separate types.
For example, with two dimensions of heterogeneity (e.g. different entrepreneurial abilities and different venture risks), contracts might need
to specify an interest rate, collateral, and a suboptimal loan size, say. But
the principle remains essentially unchanged. In the limit, one can imagine
banks enriching the menu of contracts with as many contract terms as
it takes to reveal all the hidden information. In practice, of course, the
environment may be too complicated for banks to effectively sort out the
heterogeneous types or they may run out of effective instruments. If so,
some asymmetric information will remain, so the pooling of at least some
types with the possibility of credit rationing is restored. But clearly, banks
and the ablest entrepreneurs have incentives to search for new contract
terms to reduce the occurrence of pooling, the former because of the
dictates of competition, and the latter out of self-interest.
Several examples of BADs have been suggested in the literature:
r Collateral.17 Collateral is an asset belonging to a borrower that can be
seized by a bank if the borrower defaults. Unlike large established firms
that can pledge company assets (inside collateral), most entrepreneurs
can pledge only their own assets (outside collateral), typically their
house. Most models of debt finance assume that banks automatically
153
154
interest rate D1 . This is because unlike bs, the gs are genuinely confident
about their chances of succeeding in the next period and so obtaining
the low repayment D2 .
r Joint liability under group lending (Ghatak and Guinnane, 1999; Ghatak,
2000; Laffont and NGuessan, 2000). Banks lend to groups of individuals who are made jointly liable for repayment. All group members are
treated as being in default if any one member of the group does not
repay their loan: the BAD is the default penalty levied on the group.
Types match together in pairs because although both types prefer to
match with gs, the joint benefits of so doing are greater for gs because
they are more likely to succeed. Unlike bad types b, good types g are
willing to accept a high BAD in return for low D. Thus joint liability acts
like collateral even when borrowers lack formal financial collateral.20
r A sub-optimal loan size (Bester, 1985b; Besanko and Thakor, 1987b;
Milde and Riley, 1988; Innes, 1991, 1992; Schmidt-Mohr, 1997).
Good types are more willing to waste resources by requesting inefficiently large (or small) loan sizes in order to signal their type.
5.1.4
Proponents of credit rationing have responded to the objection that financial contracting can eliminate the pooling equilibria on which credit
rationing depends by making the following observations:
1. Screening cannot work if extra contract terms are unavailable. For
example, specifying BAD as collateral will be ineffective if borrowers
have insufficient collateralisable wealth. Then pooling and credit rationing can emerge again. This may be an important point because it
is known, for example that lack of collateral is one of the major reasons
that banks refer borrowers to the UKs loan guarantee scheme.21
2. BAD contract terms might not be monotonically related to preferences, violating the single-crossing property underlying figure 5.4.
Examples are plentiful. A simple one is if borrowers differ in their
initial wealth and the richest are the least risk averse, since then both
those with the safest (i.e. the rich) and those with the riskiest (i.e. the
poor) ventures will offer collateral, muddying the signal (Stiglitz and
Weiss, 1981; see also Stiglitz and Weiss, 1992, for another example).
Collateral cannot effectively separate different types and the possibility
of credit rationing emerges again.
3. If there is imperfect competition on the supply side of the market, banks
can maximise surplus by means of pooling, rather than separating,
contracts (Besanko and Thakor, 1987a).
4. If the number of high-risk types b is not too numerous, the benefits
of screening different types might not compensate for the deadweight
155
156
suggests that actual lending rates are not explained by loan success (Cressy
and Tovanen, 1997). Also, banks do not appear to charge very different
interest rates to even observably heterogeneous ventures.24 This might
be indicative of pooling in credit markets, in contrast to the separation
implied by efficient contracting. Strictly speaking, however, that conclusion does not follow unless every loan term, not just the interest rate, is
unrelated to loan success.25
It is certainly the case that credit rationing models are sensitive to
changes in their assumptions. Some researchers apparently believe that
this casts doubt on the relevance of the phenomenon (e.g. Hillier and
Ibrahimo, 1993). On the other hand, as Clemenz (1986) has argued, it is
very unlikely that necessary conditions for credit rationing can be found
in any model that remains sufficiently general to be interesting. Furthermore, the number of possible mechanisms by which credit rationing can
arise can perhaps be regarded as a strength not a weakness of the credit
rationing hypothesis, because it expands the set of circumstances under
which such rationing may occur. Elsewhere (Parker, 2002b), we concluded that the present state of the literature on credit rationing demonstrates the following points. (1) The possibility of credit rationing cannot
be generally ruled out. (2) Credit rationing can emerge in a wide variety
of lending environments. And (3) credit rationing models can invariably
be generalised to include features that remove it. Further theoretical refinements of existing models are unlikely to change any of these points.
Instead, the need is for empirical research to address directly the question
of whether credit rationing exists, and if so, to what extent. This issue will
be taken up in chapter 7.
5.2
Over-investment
157
(5.8)
i.e. otherwise they invest their assets B safely, ending with B. The
marginal entrepreneur, for whom (5.8) holds with equality, is denoted
x)
By inspection, a total of 1 G(
higher-ability individuals choose
by x.
entrepreneurship. Importantly, the marginal entrepreneur x is of low ability relative to other entrepreneurs. Denote the average success probability
and p D > p(x)D.
158
159
Conclusion
Debt finance for new start-ups has an important bearing on entrepreneurship and policy towards it. From an entrepreneurs perspective, the availability and price of loans, and other contract terms such as collateral
and the size of loans, are often of primary importance. The theoretical
literature reviewed in this chapter showed that when entrepreneurs possess better information about their proposed ventures than banks do, it
is possible for efficient contracting between banks and entrepreneurs to
break down. Either too much or too little finance and too few or too
many entrepreneurial ventures can occur from the standpoint of social
efficiency.
The view of this author is that de Meza and Webbs (1987) model is
an especially important contribution to the literature on financing new
entrepreneurial ventures. That model challenges the widespread assumption that financing problems necessarily lead to too few entrepreneurs.
De Meza and Webb showed that it is quite possible for there to be too
many entrepreneurs in equilibrium, and that a suitable government policy for encouraging entrepreneurship might be to deter the least able from
borrowing in the credit market. The importance of this point stems not
from any claim that this outcome is bound to occur, but instead from its
warning that policy makers should not automatically equate credit market
imperfections with insufficient entrepreneurship, and should not immediately reach for instruments designed to draw marginal individuals into it.
The exposition of the theoretical models in this chapter included discussion of appropriate policy responses where they exist. These responses
160
were diverse, reflecting the diversity of the models. One should certainly
not take the policy recommendations too seriously. Many of the models
generating them are rather fragile, in the sense that altering some of their
assumptions can easily reverse the predicted forms of market failure and
hence the policy conclusions. Also, the models are partial equilibrium
in nature, and do not take into account broader effects that should be
analysed in a general equilibrium setting (Hillier and Ibrahimo, 1993).
However, these caveats have not prevented some policy makers from eagerly seizing some of these results, and using them to justify particular
forms of intervention such as loan guarantee schemes (see chapter 10,
section 10.1).
There would be a better basis for policy recommendations if one could
sort through the various models and identify the ones with the greatest
empirical relevance. As noted in subsection 5.1.4, empirical investigations
along these lines would be valuable but probably fraught with difficulties.
Unsurprisingly, therefore, the literature to date has not progressed very far
in this direction. Attempting to reject models on the basis of their indirect
predictions is also unlikely to be informative, for the simple reason that
models can often be generalised in to better fit the stylised facts when
they conflict with the original model.33 This problem has also bedevilled
efforts to measure the extent of Type I and Type II credit rationing a
topic we explore in chapter 7.
N OT E S
1. We do not consider other implications of credit rationing, for example for the
performance of the macro economy (see Blinder, 1989; Jaffee and Stiglitz,
1990, sec. 5; and Hillier and Ibrahimo, 1993, sec. 6).
2. As Jaffee and Stiglitz (1990) point out, the inability of individuals to borrow
at the interest rate they think is appropriate is not a valid definition of credit
rationing. Nor is the situation where borrowers can only obtain a small loan
at their desired interest rate, with them having to pay more for a larger loan.
Note that Definitions 8 and 9 are distinct because, unlike redlined ventures,
rationed ventures are sufficiently productive to be capable of generating high
enough returns for banks to at least break even.
3. Allen (1983) endogenised the default penalty by treating it as the present value
of future borrowing opportunities, which are withdrawn from entrepreneurs
who default. Type I rationing emerges again. Smith (1983) showed that the
optimal policy in the JaffeeRussell model is for the government to lend as
much as is demanded at some appropriate interest rate.
4. For other criticisms of the JaffeeRussell model, and a reply by its authors, see
the exchange in the November 1984 issue of the Quarterly Journal of Economics.
5. Hillier (1998) clarified the nature of the requisite over-optimism, which is that
entrepreneurs must over-estimate the payoffs in the successful state, rather
than the probability of success itself.
161
F(D C, )
d
=
> 0,
dC
(C, | D)/
10.
11.
12.
13.
14.
162
15. For a formal proof in the context of collateral, see Bester (1985a).
16. The logic is simple. In a competitive equilibrium, a pooling contract, p say,
must make zero expected profits. But this involves gs cross-subsidising bs.
Hence gs will prefer g to p , and any bank not offering g will lose gs to
rivals that do. With the departure of gs, the p contract becomes lossmaking,
and the only contract that can be offered to bs is b on which (like g ) banks
break even.
17. See Bester (1985a, 1987), Chan and Kanatos (1985), Clemenz (1986) and
Besanko and Thakor (1987a). Coco (2000) surveys the literature.
18. On the latter, the value to the bank of bankrupt ventures assets may be so
low that banks do better re-negotiating debt rather than initiating bankruptcy
proceedings. Knowing this, entrepreneurs have an incentive to default even
when they are successful. But, crucially, banks can remove this incentive if
they can seize defaulters collateral. Then the benefits of debt re-negotiation
can be realised by both entrepreneurs and banks.
19. In practice, multi-period lending contracts involve bankborrower relationships. Evidence from Petersen and Rajan (1994), Harhoff and Korting (1998)
and Berger and Udell (1995) shows that established borrowers benefit from
lower interest rates and lower collateral requirements than new borrowers.
This may reflect learning about the entrepreneur by the bank, or could be the
outcome of an effort inducement device (Boot and Thakor, 1994).
However, an issue that is sometimes overlooked in this literature (and which
also pertains to other finite repeated games) is a dynamic inconsistency problem. Suppose an entrepreneur needs a stream of finance over several periods.
If the borrowing relationship has a clear end, borrowers have an incentive to
default in the final period. Anticipating that, banks will not lend in the final
period, giving borrowers the incentive to default in the penultimate period.
By backward induction, this continues until the mechanism unravels altogether unless there is sufficient uncertainty about the end date, or if there
is well-established progression from one loan tranche to the next.
20. In fact, the result does not depend on assortative matching of types in groups.
Armendariz de Aghion and Gollier (2000) showed that group lending still
works when entrepreneurs are uninformed about each others types and pair
randomly.
21. Some 71 per cent of the respondents to a survey by KPMG (1999) cited lack
of security as the main reason for using the scheme.
22. In a different vein, Stiglitz and Weiss (1983) proposed a multi-period model
in which banks threaten to ration credit in later periods unless borrowers
succeed in the first period. This induces good behaviour by borrowers and
low default rates. But to be credible, banks must be seen to carry out their
threat, so some credit must be rationed.
23. See, e.g., Leeth and Scott (1989) and Berger and Udell (1990, 1992, 1995).
For example, Berger and Udell (1990) analysed data on a million US commercial loans over 197788. They measured loan risk in terms of above-average
risk premia ex ante, and venture risk in terms of poor ex post performance.
Both risk measures were positively and significantly associated with greater
collateral. These findings are consistent with the collateral as incentive device
24.
25.
26.
27.
28.
29.
30.
31.
163
model of Boot, Thakor and Udell (1991); with de Meza and Southeys (1996)
model of over-optimistic entrepreneurs; with Cocos (1999) model where the
most risk-averse types choose safe ventures and are less willing to post collateral; and with Besters (1994) model of debt re-negotiation.
According to the Bank of England (1993), 80 (resp., 96) per cent of bank
margins to small firms with turnover of less than 1 million in 19912 (resp.,
between 1 and 10 million) were between 0 and 4 percentage points (see
also Keasy and Watson, 1995; Cowling, 1998). US evidence points to similar
margins (Berger and Udell, 1992).
Black and de Meza (1990) showed that under pooling contracts the more
able entrepreneurs operate safe ventures, depriving the less able in the risky
venture of cross-subsidies and so leaving them potentially inactive. With only
low-risk ventures funded in equilibrium, limited interest spreads emerge for
this reason rather than because of pooling.
More generally, DWs results hold if entrepreneurs returns can be ranked
in terms of first-order stochastic dominance, rather than second-order stochastic
dominance as in SW (recall Definitions 4 and 6 in chapter 2, subsection 2.2.1).
See also Leland and Pyle (1977), who showed that an entrepreneurs willingness to invest in his own venture is a favourable signal of venture quality
although the signal reduces the welfare of risk-averse borrowers who have to
take larger stakes in their own firm than they would wish under the first-best
case of perfect information.
Proof: If there was an excess demand for funds, all banks could make profits
by increasing D, since from (5.9), bank gross expected returns are unambiguously increasing in D (noting from (5.8) that the average probability of
success must be an increasing function of D). There is no interior bankoptimal interest rate: increasing D to the market-clearing rate of Dm can always remove any excess demand for funds. Likewise, banks would be forced
by competitive pressures to reduce D to Dm if there was an excess supply of
funds.
164
32. Another model with heterogeneous outside options is Chan and Thakor
(1987). That model does not generate multiple sources of inefficiency, merely
pricing out of the market the entrepreneurial types that have exclusive rights
to a valuable outside option.
33. For example, de Meza and Webbs (1987) model predicts a negative relationship between personal wealth and entrepreneurship (see (5.8)) in conflict
with most evidence on the issue (see, e.g., chapter 7). But a subsequent paper
published in 1999 by these two authors generalised the model by incorporating moral hazard, with the result that a positive relationship between wealth
and entrepreneurship emerges.
Chapter 5 concentrated on issues relating to debt finance of entrepreneurial ventures. This broadly reflects the emphasis in the literature. Yet
many start-ups obtain external finance through informal sources, such as
loans from family and friends and credit co-operatives. A smaller number
utilise equity finance (venture capital). Part of the interest in studying
alternative sources of finance is that they might be able to fill any gaps
created by credit rationing.
The structure of the chapter is as follows. Section 6.1 explains the
economics of informal sources of finance, and section 6.2 treats aspects
of equity finance that relate to typical entrepreneurial ventures. We will
cite only selectively and sparingly from the extensive corporate finance
literature on risk capital, most of which pertains to large firms. Section
6.3 concludes.
6.1
6.1.1
Family finance
In his analysis of the 1992 CBO database, Bates (1997) showed that families are the most frequently used source of business loans in the USA after
financial institutions (mainly banks). Bates reported that 26.8 per cent
of non-minority-owned businesses used family finance, compared with
65.9 per cent who used loans from banks. Among some minority groups,
however, family finance was used more extensively than bank finance. For
immigrant Korean and Chinese business owners, family finance was used
by 41.2 per cent, whereas bank finance was used by 37.4 per cent (see
also Yoon, 1991). For all groups, family loans were of a smaller average
size than bank loans, although family loans remained an important source
of funds by value, being worth an average of $35,446 for non-minority
owners compared with $56,784 for bank loans.
UK evidence tells a similar story. According to Curran and Blackburn
(1993) and Metcalf, Modood and Virdee (1996), family loans account for
165
166
between 15 and 20 per cent of start-up finance among ethnic-owned businesses in the UK, making it the largest source of funds after bank loans
(see also Basu, 1998; Basu and Parker, 2001). Data from other countries
tell a broadly similar story. Knight (1985) reported that the following
sources of funds were used by high-tech Canadian firms at the pre-startup stage: personal savings: 60 per cent, family/ friends: 13 per cent, bank
loans: 12 per cent and trade credit: 6 per cent. The importance of families
and friends for supplying start-up finance appears to be even stronger in
developing countries.1
What motivates lending within families? Family members may have private information about borrowers that is unavailable to banks (Casson,
2003); and they may able to monitor and exert peer pressure on the borrower. For their part, family lenders may be trusted to behave sensitively
if the entrepreneur encounters difficult borrowing conditions. Family
lenders can also serve as loan guarantors to outside lenders (Jones et al.,
1994).2 Also, if the borrower stands to inherit the family lenders estate,
then a family loan effectively becomes a mortgage on his own inheritance. In contrast, banks are usually unwilling to accept the prospect of
inheritance as security for a loan (Casson, 2003).
Basu and Parker (2001) explored some of the theoretical issues by
analysing a simple two-period model in which there are two family
members one borrower and one lender and an entrepreneurial venture
requiring external finance. Their model recognises some of the stylised
facts that most family loans tend to be interest-free (Light, 1972; Basu
and Parker, 2001). Basu and Parker (2001) showed that family members
are generally prepared to supply funds not only if they are altruistic towards the entrepreneur, but also if they are selfish. The selfish motive for
lending at a zero interest rate arises if the loan entitles the lender to a
sufficiently valuable option to call in the favour, and turn entrepreneur
themselves at a later date. Using a sample of relatively affluent Asian immigrant entrepreneurs, Basu and Parker (2001) claimed to find evidence
of both altruistic and selfish family lending motives. Also, they estimated
that greater use of family finance was positively associated with an entrepreneurs age, the number of hours worked in their business and the
employment of a spouse in the venture. Unsurprisingly, family finance
was found to be a gross substitute for bank loans.
Other evidence suggests that family finance is not associated with successful enterprise, being correlated with low profitability and high failure
rates in entrepreneurship (Yoon, 1991; Bates, 1997; Basu, 1998). The
case for government intervention is in any case not clear-cut. And apart
from the Dutch government, which offers tax exemptions for family finance, we know of few other policy initiatives in this area.
6.1.2
167
Micro-finance schemes
The term micro-finance usually refers to small, often non-profit making, lending schemes, which are targeted at individuals who are unable to obtain funds from conventional banks, usually because they
are too poor to post collateral. Many such schemes are currently in
operation around the world, mainly concentrated in developing countries with under-developed financial sectors. They include the Grameen
Bank in Bangladesh, BancoSol in Bolivia and Bank Rayat in Indonesia.3
Perhaps the most famous is the Grameen scheme, founded in 1976
by Muhammad Yunus, an economics professor. This scheme, which
provides financing for non-agricultural self-employment activities, had
served over 2 million borrowers by the end of 1994, of which 94 per cent
were women.
Despite their differences, micro-finance schemes tend to share some
common features, including direct monitoring of borrowers, stipulation
of regular repayment schedules and the use of non-refinancing threats to
generate high repayment rates from borrowers who would not otherwise
receive credit (de Aghion and Morduch, 2000). Most of the economics
literature on the subject has focused on group lending schemes (GLSs)
with joint liability, whereby individuals form into groups and are jointly
liable for penalties if one member of the group defaults. The nature of
the penalty might be the denial of future credit to all group members
if one member defaults (as in the Grameen scheme), or group liability
for loans if a member defaults (as in the Bangladesh Rural Advancement
Committee scheme).
The advantage of joint liability contracts is that they give entrepreneurs
incentives to exploit local information and exert pressure to discipline
members in a manner consistent with the interests of lenders (and, by
releasing funds, thereby also the entrepreneurs). The particular mechanisms involved include:
1. Mitigation of moral hazard. Group members may be able to monitor
each other in a manner unavailable to banks. For example, members
may know or live near each other, and share information. Under joint
liability each members payoff depends on whether other members
ventures succeed, so all members have an incentive to monitor other
members behaviour, and to take remedial action against members
who misuse their funds (Stiglitz, 1990). For example, group members
might threaten others with social ostracism if they shirk in a manner
that invites default, or if they invest in excessively risky ventures.
2. Cheap state verification and repayment enforcement. Group members may
be in a better position than banks to learn about partners venture
168
outcomes. Then joint liability can encourage them to exert peer pressure to deter partners from defaulting opportunistically in good states.
Also, if group members have lower auditing costs than banks, a GLS
may economise on state verification costs. Only if the whole group defaults will banks incur audit costs, so this arrangement reduces average
auditing costs and enhances efficiency. Indeed, if bank audit costs are
too high for banks to be able to offer any individual loan contract, a
GLS could facilitate lending where none was possible before.
3. Mitigation of adverse selection. Rather than changing borrowers behaviour, as above, joint liability can favourably alter the pool of borrowers. The way that this peer selection effect can promote efficient
contracting was briefly discussed in chapter 5, subsection 5.1.3.
Some evidence confirms the usefulness of these three mechanisms.
Wydick (1999) found from Guatemalan data that peer monitoring and
a groups willingness to apply pressure on delinquent members were the
salient factors explaining borrowing group performance. And using Costa
Rican data, Wenner (1995) reported that repayment rates were highest
among groups who actively screened their members via local reputations.
Micro-finance schemes promise several benefits. First, for the reasons
outlined above, they can lead to improved repayment rates. The available
evidence supports this claim.4 Competitive (or non-profit making) banks
can then recycle the benefit of higher repayment rates to borrowers in
the form of lower interest rates and/or larger loan sizes. This may in turn
further decrease the severity of asymmetric information problems such as
adverse selection, as well as increasing borrower welfare directly. Second,
ventures can be undertaken that would otherwise not be undertaken.
This can be especially valuable in poor regions, where self-sufficient
entrepreneurship promotes development and alleviates poverty the socalled micro-finance promise. Third, micro-finance schemes can carry
in their train valuable social development programmes such as vocational
training, civic information and information sharing to members. These
have been found to add substantial value to participants venture profitability rates (McKernan, 2002).
However, micro-finance schemes can also suffer from drawbacks. First,
they can encourage excessive welfare-reducing monitoring by group
members (Armehdariz de Aghion, 1999); and the joint liability clause
might encourage excessively cautious investment behaviour. Second,
there is no guarantee that a scheme will break even, and subsidies may
become necessary. Indeed, as Ghatak (2000) warned, joint liability contracts might drive out more conventional single-liability contracts, undermining the viability of conventional loan markets. Third, the transfer
of risk from banks to borrowers presumably reduces borrower welfare.
169
In some theoretical models, it can be shown that the benefits of microfinance schemes outweigh the costs (e.g. Stiglitz, 1990). But this is not
a general property and cannot be assumed to hold universally, notwithstanding some recent evidence of substantial benefits from Bangladeshi
micro-finance schemes. On the latter, McKernan (2002) found that participation in such schemes increased monthly self-employment profits by
175 per cent on average. Pitt and Khandker (1998) discovered substantial gender differences in Bangladesh, with micro-finance credit having
a significantly greater effect on households in which women rather than
men were the scheme participants. Pitt and Khandker suggested that this
might be indicative of how access to credit unleashes womens productive skills that, unlike mens, are held in check by cultural and religious
restrictions proscribing formal waged work.
6.1.3
170
171
Trade credit
Another potentially valuable source of inside local information is trade
credit. Trade credit comprises loans between firms that are used to purchase materials and goods in process. According to Acs, Carlsson and
Karlsson (1999, table 1.5), the value of trade credit in the USA in 1995
was $233 billion, compared with $98 billion for bank loans.
Trade credit might be capable of mitigating credit rationing (Bopaiah,
1998). Its use can also convey a favourable signal of creditworthiness to
banks, allowing entrepreneurs to leverage credit that might not otherwise
have been forthcoming (Biais and Gollier, 1997).
6.2
Equity finance
6.2.1
Introduction
6.2.2
The USA has the largest formal VC market in the world. In 2001, for
example, over $40 billion of VC funds were invested there, compared with
only $12 billion in Europe (Bottazzi and da Rin, 2002). The US figure was
172
down from its peak of $106 billion in 2000 a figure that demonstrates the
volatile pro-cyclicality of VC markets. The European market has grown
dramatically since 1995, and is showing signs of convergence with the
US market. Of particular interest is the growing importance of earlystage VC investments, which are arguably those most closely identified
with individual entrepreneurship. Since the early 1990s about one-third
of US VC investment has been in early-stage projects. In Europe in the
early 1990s the fraction was one-tenth, but by 2001 it had also reached
one-third (Bottazzi and da Rin, 2002).
Evidence on the size of the informal equity sector is less widely available. In the USA and UK it is thought to be about twice that of the formal
equity sector, even though the individual deals are on a smaller scale. According to Mason and Harrison (2000), the UKs informal market for
start-up and early-stage venture financing is broadly similar to the size
of the formal market.8 Wetzel (1987) estimated that there are around
250,000 business angels in the USA, of which around 100,000 are active in any given year. He also estimated that business angels finance
over ten times as many ventures as professional VC firms. Wetzel emphasised a general problem of poor information about investment and
investment opportunities that can cause poor matches between VCs and
entrepreneurs and potentially inefficient investment. Business angels appear to have similar characteristics in the USA and UK, although UK
investors tend to be less wealthy, investing about half of the sums of their
US counterparts. UK business angels are also more likely to invest independently rather than in consortia, although similar to the USA eight
times as many businesses raise finance from business angels than from
institutional VC funds (Mason and Harrison, 2000).
EF accounts for only a small proportion of external finance for entrepreneurs in most countries. For example, Bates and Bradford (1992)
reported that only 2.8 per cent of US small business start-ups obtained
EF. Its receipt was found to be positively associated with owner education, age, the amount of self-finance, and a track record in business. A
similar picture applies in the UK, where EF accounted for 1.3 per cent
of total start-up finance by the end of the 1990s, down from 3 per cent
at the start of the decade despite the strong growth performance of the
companies that used it (Bank of England, 2001). Indeed, several recent
US studies claim to have detected various beneficial effects from venture capital. VCs screening, monitoring and mentoring services lead to
faster professionalisation (Hellmann and Puri, 2002), stronger innovation
(Hellmann and Puri, 2000; Kortum and Lerner, 2000), higher growth
(Jain and Kini, 1995) and possibly also employment creation (Belke, Fehr
and Foster, 2002).
6.2.3
173
174
It is sometimes claimed that there is a funding or equity gap for EF. The
term equity gap should be distinguished from equity rationing. The
former is commonly used to refer to a mismatch between entrepreneurs
and VCs or business angelsfor example, because fixed costs make VCs
unwilling to supply the relatively small sums required by entrepreneurs.
The latter refers to the problem, analogous to credit rationing, where
there is a persistent excess demand for funds which even competitive
VCs that face low costs are unwilling to satisfy.
It is reasonably straightforward to propose models of equity rationing
that mirror the credit rationing models described in chapter 5. For example, Hellmann and Stiglitz (2000) modelled debt and equity providers
who compete with each other to finance heterogeneous entrepreneurs
who possess private information about both their project risks and returns. Hellmann and Stiglitz unified both the StiglitzWeiss (SW) and
de Meza and Webb (DW) models outlined in chapter 5. Returns in the
successful state are given by = , where the probability of success is
(1/ ), where measures risk. Suppose payoffs are zero in the failure state.
Then expected returns are (1/ ) = . Entrepreneurs possess heterogeneous and values, known only to themselves. It is easy to show that
both high- and high- individuals prefer debt finance to EF. Hellmann
and Stiglitz (2000) assumed that lenders specialise in either debt finance
or EF, and that entrepreneurs cannot use a mixture of both. They then
showed that credit and equity rationing may occur individually or simultaneously. The usual culprit of lender return functions that decrease in
their own price (chapter 5) accounts for the possibility of rationing in
each individual market. As in SW, the mechanism is that lenders do not
175
increase the price of funds to clear the market because good types may
exit the market such that lenders expected profits fall. Hellmann and
Stiglitz (2000) also obtained the surprising result that competition between the two markets may itself generate the adverse selection that leads
to rationing outcomes. The reason is that if many low-risk entrepreneurs
switch between the debt and equity markets, competition induces lenders
in one or both markets to reduce the price of funds below market-clearing
levels in order to attract them so rationing ensues. However, if only EF
was offered, then credit rationing would disappear.
Hellmann and Stiglitz did not endogenise optimal contracts in their
model, merely assuming coexistence of banks and VCs. Bracoud and
Hillier (2000) studied the problem of optimal contracts in a generalisation of Hellman and Stiglitzs model, in which expected returns may
vary among entrepreneurs. They showed that a variety of different optimal contracts is possible, depending on the form of the joint distribution of (, ). A result of particular interest occurs in a two-type set-up,
= {b, g}, with probabilities of success pg and pb < pg , returns if
successful of Rgs < Rbs and expected returns Eb (R) > Eg (R). Bracoud and
Hillier (2000) showed that gs will self-select into equity and bs into debt
contracts, and that the equilibrium is first-best efficient. But this result
disappears if Eb (R) < Eg (R). Then the optimal contract pools the types
together and whether it is in the form of equity or debt depends on the
deposit rate, .
Greenwald, Stiglitz and Weiss (1984) developed a model in which the
least able entrepreneurs prefer EF and the ablest prefer debt finance (see
above). Greenwald et al showed that the adverse signal transmitted by
choosing EF can increase the cost of capital sufficiently to deter creditrationed borrowers from availing themselves of EF altogether. This reinforces the potential importance of the SW credit rationing result, since
it rebuts the argument that entrepreneurs who are rationed in the debt
market can obtain funds elsewhere, e.g., in the form of EF.
Parallel to chapter 5, under-investment is also possible when EF contracts are used. There is a special result of interest despite its apparently
limited applicability to small entrepreneurial ventures. Myers and Majluf
(1984) analysed the problem of issuing new equity when a valuable investment opportunity appears. Managers of existing enterprises have more
information about both the companys assets in place and the value of
the new investment opportunity. Suppose that EF is used to finance the
new investment; that managers act in the interests of their existing shareholders; and that shareholders do not actively rebalance their portfolios
in response to what they learn from the firms actions. Then Myers and
176
Majluf showed that a new share issue could reduce the share price by so
much that managers might optimally pass up the new profitable opportunity, causing under-investment. In contrast, the use of internal funds
or risk-free debt finance removes any under-investment, and does not reduce the share price so is preferred to EF by managers. However, these
results are sensitive to the objectives of managers of the enterprise and
the behaviour of shareholders (see also Noe, 1988).
In short, the theoretical literature on equity rationing is inconclusive.
On the empirical front, there is little hard evidence of equity rationing.
For example, Dixon (1991) reported that 63 per cent of respondents in
his UK VC survey claimed they had more available funds than attractive
projects in which to invest. This is suggestive of an equity gap rather than
equity rationing.
6.2.5
Policy recommendations
177
Conclusion
Debt finance is not the only way that capital flows from lenders to entrepreneurs. Many other sources of finance are also available. We reviewed
several of them in this chapter, grouped under the headings of informal
sources of finance and equity finance.
Our treatment of alternative sources of finance has not been exhaustive
or complete. For example, we did not discuss explicitly the role of credit
cards, leasing arrangements or franchising despite the possibility that
these might have helped eliminate funding gaps caused by limited bank
credit (Horvitz, 1984). Leasing can be more economical and less risky
for small firms than debt finance, conferring tax advantages and being
cheaper than buying capital that will not be utilised intensively (Bowlin,
1984). Likewise, franchisors have been able to finance expansion by requiring franchisees to furnish some or all of the necessary capital (Dant,
1995).
What emerges from our discussion of alternative sources of funding is
the wide variety of different financing arrangements that are available to
budding entrepreneurs. Academics and policy makers who express concern about credit rationing sometimes appear to overlook this. Even in
countries where financial markets are poorly developed, and where aspiring entrepreneurs lack even nugatory amounts of collateral, micro-finance
schemes have demonstrated the scope to expand financing activities, and
to thereby facilitate new-venture creation.
However, it is premature to conclude that the existence of a rich array
of financing instruments means that all entrepreneurs can and do avail
themselves of them in practice. Data are needed to shed light on the
178
1. See, e.g., Bell (1990) and Kochar (1997) for India, and Goedhuys and
Sleuwaegen (2000) for Cote
dIvoire.
2. Note that family ownership per se can also confer other advantages, including
improved access to bank finance (see Bopaiah, 1998).
3. See Huppi and Feder (1990) and Morduch (1999) for reviews of the structure,
rationale, costs and effects of various micro-finance schemes. These schemes
are also being replicated in poorer rural and inner city areas of developed countries, e.g., Micro-Business International in the USA, the Calmedow Foundation in Canada and the ADIE Credit Project for Self-employment in France
(Rahman, 1993).
4. According to Morduch (1999, table 3) the overdue rate on Grameen loans
averaged 7.8 per cent over 198596, compared with much higher overdue
rates, some exceeding 50 per cent, for conventional bank loans in comparable
regions.
5. See Guinnane (1994) and Ghatak and Guinnane (1999, sec. 3.1) on the origins
of credit co-operatives in Germany in the nineteenth century. Key features of
the German system included screening of members (not all were admitted)
and project proposals (not all were financed).
6. According to Hughes (1992), there is also a public good character to MGSs,
because the founding firms pay the greatest cost in setting up the loan guarantee, which later members can benefit from at lower cost. However, this does not
necessarily provide a case for public support as Hughes suggests, because there
is nothing to prevent incumbents devising ways of forcing future members to
share the costs.
7. VC involvement can take the form of advice and assistance, based on the
VCs own experience and contacts, and access to investment bankers, lawyers,
accountants and consultants. Some VCs take a seat on the board of directors,
and retain control rights, including the ability to appoint managers and remove
members of the entrepreneurial team.
8. Descriptions of the characteristics and investment practices of business angels
appear in Wetzel (1987) and Gaston (1989) for the USA, and Mason and
Harrison (1994, 2000) for the UK.
9. However, subsequent econometric evidence from Gompers and Lerner (1998)
detected a significant negative impact on VC commitments from CGT rates,
which those authors argued constituted evidence of demand-side effects.
Chapter 5 set out the theoretical arguments for and against credit rationing, where rationing may be of loan sizes (Type I rationing) or the
number of loans (Type II rationing). That chapter concluded that theory alone cannot determine whether credit rationing exists and how
widespread it might be in practice. Empirical evidence on these issues
comprises the content of the present chapter.
The chapter is divided into three parts. Section 7.1 chronicles tests of
Type I credit rationing. After introducing the influential paper by Evans
and Jovanovic (1989), we survey the empirical literature. Most of its
contributions are predicated on econometric estimates of a relationship
between self-employment participation and personal wealth. Section 7.2
provides a critique of this methodology. Section 7.3 treats the empirical
literature on Type II credit rationing. As in chapter 5, we concentrate
on tests of equilibrium credit rationing, not temporary or disequilibrium credit rationing, arising from a temporary excess demand for credit
while banks adjust their interest rates.1 Reflecting the emphasis in published research to date, the evidence discussed below focuses on developed economies. The causes and effects of credit rationing in developing
countries tend to be highly country-specific: see, e.g., Levy (1993) and
Kochar (1997).
At the outset we reiterate a point made in chapter 1: that claims by
survey respondents should be treated with great caution. In the present
context, these are claims that they face credit rationing. For example, according to Blanchflower and Oswald (1998) and Blanchflower, Oswald
and Stutzer (2001), half of employee survey respondents claiming to have
seriously considered becoming self-employed in the past blamed insufficient capital as the reason for not making the switch. However, this
does not necessarily mean that loans were unavailable to these respondents. Another survey approach asks business owners whether they regard
themselves as credit rationed (see, e.g., Cosh and Hughes, 1994; Moore,
1994; Guiso, 1998). However, this approach is prone to self-serving bias
whereby entrepreneurs might blame banks for inherent shortcomings
179
180
7.1.1
An influential paper by Evans and Jovanovic (1989) (hereafter, EJ) stimulated a wave of empirical research on Type I credit rationing. EJ assumed that entrepreneurs can borrow only up to a multiple 1 of
their initial assets, B, where is common to all individuals. Therefore
entrepreneurs can operate only capital k (0, B). This corresponds to
the case of Type I credit rationing, since banks are willing to extend loans
to everyone with some assets, up to some given asset-determined limit,
irrespective of the interest rate entrepreneurs are prepared to pay.
EJ assumed that borrowing and production take place in a single period. Entrepreneurs incomes y depend on k via the production function
y = xk , where x is managerial ability and (0, 1) is a parameter. A
constrained borrower enters entrepreneurship iff their earnings net of
capital repayments D = (1 + r ) B (where r > 0 is the nominal interest
rate) exceeds their earnings in paid employment, w. This occurs iff
x( B) (1 + r ) B > w .
(7.1)
181
on 1,500 white males over 197881 who were wage earners in 1976; and
reported a positive and significant probit coefficient (p-value = 0.02) on
initial assets. This supports prediction 1. Also, log self-employment incomes were also found to be significantly and positively related to log
initial assets, supporting prediction 2.
EJ went on to estimate a structural model of occupational choice,
borrowing constraints and a managerial abilityassets relationship. They
estimated to be 1.44, and significantly greater than 1; a subsequent estimate by Xu (1998) based on more accurate data found = 2.01. Also,
EJ estimated that 94 per cent of individuals likely to start a business faced
Type I credit rationing. They claimed that this prevented 1.3 per cent of
Americans from trying entrepreneurship. These are large effects, which
have encouraged subsequent researchers to explore their robustness.
7.1.2
Following EJ, many researchers have used cross-sectional or longitudinal data to estimate a probit self-employment equation, including some
measure of individuals assets or asset windfalls among the explanatory
variables. Others have used time-series data to estimate the effects of
aggregate wealth on the average self-employment rate. Many of these
studies have detected significant positive effects of personal wealth on
self-employment propensities and rates (we will discuss below results
relating to asset windfalls),2 while a handful have detected insignificant
effects (e.g., Taylor, 2001; Uusitalo, 2001). Taken at face value, these
results appear to support EJs claims about the importance of Type I
credit rationing.
These results raise a number of questions. First, should researchers
study the effects of wealth on the probability that individuals are selfemployed, or the probability that they become self-employed? Arguably,
the most precise effects are obtained by focusing on the latter since established entrepreneurs could not by definition have faced Type I credit
rationing that was severe enough to have prevented their participation
in entrepreneurship. Second, studying entry into self-employment avoids
the charge of reverse causality, whereby the self-employed are wealthy
because of previous success in self-employment. Indeed, it is now widely
accepted that endogeneity problems render personal wealth variables of
limited value in empirical investigations of Type I credit rationing.
In recognition of this point, several researchers have explored the role
of financial variables that are arguably less prone to endogeneity. These
include asset windfalls of some kind, such as inheritances, gifts, or lottery wins, that are presumably exogenous to the self-employment entry
182
decision and that can potentially overcome any Type I credit rationing.
Empirical studies have generally found positive, significant and substantial effects of windfalls on self-employment status and entry probabilities, with diminishing returns from higher windfall values.3 We cite some
typical findings to give a flavour of the results. Blanchflower and Oswald
(1998) reported that a Briton who received 5,000 in 1981 prices was
twice as likely to be self-employed in 1981 as an otherwise comparable person who had received nothing. Holtz-Eakin, Joulfaiah and Rosen
(1994a) reported that a $100,000 inheritance would increase the probability of a transition from paid employment to self-employment in the
USA by 3.3 percentage points. Lindh and Ohlsson (1996) estimated that
the probability of self-employment in Sweden would increase by 54 per
cent if lottery winnings were received, and by 27 per cent on receipt of
an average-sized inheritance.
Findings of a positive and significant role for windfalls appear to be
robust to some obvious sources of bias. These include self-employed
people being more willing to gamble on lotteries (the opposite appears to
be the case according to Lindh and Ohlsson, 1996 and Uusitalo, 2001); to
inheritances being anticipated or being in the form of family businesses;
and to industry differences due to different required capital intensities
(Bates, 1995). In fact, true effects from windfalls may be under-stated
to the extent that researchers cannot always measure delayed entries into
self-employment following the receipt of a windfall. Entry decisions may
take several years to play out.
7.1.3
183
Holtz-Eakin (1994b) found that inheritances increase the probability that self-employed Americans remain in self-employment. Similar
results have been obtained by other researchers using measures of personal wealth rather than windfalls (Bates, 1990; Black, de Meza and
Jeffreys, 1996; Taylor, 1999; Quadrini, 1999; Bruce, Holz-Eakin and
Quinn, 2000), though Taylor (2001) found no effect of inheritances on
UK self-employment survival probabilities.
Human capital potentially complicates the argument. On one hand,
greater human capital might increase the productivity of physical capital, increasing the desired capital stock and hence the severity of Type I
rationing. On the other hand, if education and wealth are correlated,
then any rationing constraint might be eased. Cressy (1996) claimed that
failing to control for human capital endows personal (housing) wealth
with spurious explanatory power in UK business survival regressions.
However, US evidence does not support the general contention that financial inputs are unimportant for explaining survival once human capital
is controlled for.
7.1.4
Critique
While some of the evidence outlined in the previous section is consistent with Type I credit rationing in principle, other explanations are also
possible:
r Inherently acquisitive individuals both build up assets and prefer entrepreneurship to paid-employment, whether or not capital constraints
184
exist. More generally, the wealthy (or those who receive gifts or inheritances) may for unmeasured reasons be intrinsically more likely
to be entrepreneurs and to remain in entrepreneurship. Alternatively,
entrepreneurship allows wealthier individuals to consume leisure more
easily.
r Inheritances are left to those working hard at developing new businesses.
Blanchflower and Oswald (1998) claim that there is little evidence that
bequests more generally are related to recipients incomes; but separate evidence exists of strategic bequest behaviour, whereby bequests
are contingent on recipients behaviour and characteristics (Bernheim,
Shleifer and Summers, 1985).
r A positive relationship between the number of entrepreneurs and personal wealth can also be consistent with over-investment, rather than
Type I credit rationing (de Meza and Webb, 1999).
r A positive association between start-ups and wealth (or windfalls such
as inheritances and lottery winnings) might simply reflect the effects of decreasing absolute risk aversion (DARA, see Definition 2 of
chapter 2, section 2.2), rather than borrowing constraints. Consider
again the Kihlstrom and Laffont (1979) model outlined in chapter 2,
subsection 2.2.4. Under DARA, an increase in the wealth of the
marginal risk-averse individual makes them more willing to enter risky
entrepreneurship, so increasing the aggregate rate of entrepreneurship
(Cressy, 2000).
r Entrepreneurs prefer self-finance to external finance, perhaps because
they regard the terms of the latter to be unreasonable. Consequently,
these individuals wait until they have saved (or inherited) enough wealth
to enter entrepreneurship without borrowing. Yet all the while banks
may have been willing to lend all of the required funds to every loan
applicant.
r On a related point, individuals propose ventures for financing that banks
perceive to be unprofitable at the proposed scale of operation. Hence
banks rationally deny as much credit as potential entrepreneurs request.
The latter then delay entry until they have sufficient wealth.
r When wealth is plentiful, there is greater entry into entrepreneurship
and the resulting competition discourages those with sufficient wealth
yet poor investment projects implying a higher average survival rate
(Black, de Meza and Jeffreys, 1996).
r Distressed firms face higher interest rates and lower credit availability
(Harhoff and Korting,
185
(7.3)
186
187
(7.4)
188
(b) Less stickiness was observed during periods of credit crunch, contradicting the credit rationing hypothesis.
2. The proportions test
(a) Doubling the nominal safe interest rate increased the probability
of observing a CL in the sample by 1.7 per cent, supporting the
Type II credit rationing hypothesis. However, opposite results were
obtained when was measured in real terms, so contradicting it.
(b) In times of credit crunch or low loan-growth rates, the proportion
of CLs was observed to decrease. The opposite would be expected
to occur under credit rationing.
On the basis of this evidence, Berger and Udell (1992) concluded that
information-based equilibrium credit rationing, if it exists, may be relatively small and economically insignificant (1992, p. 1071). They went
on to suggest that, even if some borrowers are rationed, others take their
place and receive bank loans.
A direct upper bound estimate of the extent of Type II credit rationing
can be proposed: the number of loans rejected by banks for any reason.
If the loan rejection rate is very low, then credit rationing cannot be
important. Using US data on small-company borrowing over 19878,
Levenson and Willard (2000) estimated that only 2.14 per cent of small
firms ultimately failed to obtain the funding they sought. Of course, the
actual extent of credit rationing will be lower than this to the extent that
some of these loans were observably non-creditworthy and so deserved
to be rejected.8
In the light of these findings, claims of widespread credit rationing
based on structural models (e.g. Perez, 1998) must surely be treated with
scepticism. Other direct evidence sheds further light on the Type II
credit rationing phenomenon. Theories of rationing based on adverse selection suggest that bank managers deny credit in preference to raising
interest rates, even if rationed borrowers are willing to pay higher rates (see
chapter 5, section 5.1). National Economic Research Associates (NERA)
(1990) obtained direct evidence of reluctance among bank managers to
raise interest rates above the banks standard business rate for observably higher-risk projects. However, NERA found that this reluctance was
motivated not by concerns about adverse selection or moral hazard, but
by anxiety that public relations could be harmed by an image of the bank
as a usurer. It may be noted that the bank managers surveyed had no
obvious motive for responding with self-serving bias.
It might be thought that there is an even simpler way to establish the
existence of Type II credit rationing. This is to compare survival rates
of entrepreneurial ventures funded with government-backed loans that
would not have been granted without the government guarantee, with
189
survival rates of ventures that were financed purely privately. If the two
survival rates are similar, then it might seem possible to argue that the
government intervention has alleviated credit rationing. In fact, although
there is some evidence that Loan Guarantee Scheme (LGS)-backed startups do have similar survival rates as purely privately funded start-ups, this
conclusion does not necessarily follow. The primary role of a LGS is to
help fund entrepreneurs who lack collateral and/or a track record, and so
are observably risky to finance. Banks refusing to finance ventures that
they expect to be loss making cannot be construed as rationing credit.
The whole point of a loan guarantee is to insure banks against most of
the downside risk, turning some potentially loss making investments into
profitable lending opportunities. The evidence does suggest that these
are indeed the projects that banks typically put through LGSs (KPMG,
1999).
On the other hand, even if Type II credit rationing is empirically unimportant, the perception of it might discourage potential entrepreneurs
from approaching banks in the first place. Some supporting evidence for
this hypothesis comes from Levenson and Willard (2000), who estimated
that 4.2 per cent of the individuals in their US sample were discouraged
borrowers. Cowling (1998) provides a similar estimate for the UK.
Overall, the evidence cited above does not provide much support for the
notion that banks engage in Type II credit rationing. However, just as with
Type I rationing, more research is needed before a clear conclusion can be
reached. One interesting empirical avenue that might be worth pursuing is
a detailed analysis of the characteristics of rejected loan applications. This
could help tighten the upper-bound estimate of Type II credit rationing
suggested by Levenson and Willard (2000), and might even rule out the
phenomenon as having any empirical significance whatsoever.
N OT E S
190
5. Both of these explanations can account for Berger and Udells (1992) finding
that up to 7 per cent of US commercial loans over 197788 charged interest
rates at below the (safe) open-market rate.
6. An exception to this argument, noted by Berger and Udell (1992), could occur
in the event of an increase in the demand for non-CLs only. Then credit
rationing ensures that there will be no change in pc despite greater credit
market tightness.
7. Both these and all subsequent estimates quoted below were evaluated at sample
means. Similar results were obtained using the growth of loan volumes as an
inverse measure of credit market tightness.
8. Also, Levenson and Willard (2000) found the probability of loan denial to
be negatively related to firm size, so the extent of credit rationing by value
was even less than 2 per cent. UK evidence from Cosh and Hughes (1994)
tells a similar story to Levenson and Willard (2000). From a sample of firms
surveyed between 1987 and 1989, Cosh and Hughes (1994) reported that only
3.2 per cent of firms seeking external finance failed to obtain it.
Part III
Entrepreneurs as employers
8.1.1
194
The publication of the influential Birch Report in the USA (Birch, 1979)
stimulated a wave of research on the job creation performance of small
firms. While small firms themselves are not the primary focus of interest
in this book, many of them are owned and managed by entrepreneurs,
so it seems appropriate to review this literature briefly. Our emphasis
will be on facts about relative job creation performance, rather than on
the determinants of employment growth in small firms, an issue that is
treated in chapter 9.
195
Birch (1979) claimed that between 1969 and 1976, small firms employing fewer than twenty workers generated 66 per cent of all new US jobs,
and firms with fewer than 100 employees accounted for 82 per cent of net
job gains. The implication is that the small-firm sector is the primary engine of job creation. Subsequent researchers have confirmed these findings for the USA and other countries.2 Strikingly, Acs and Audretsch
(1993) highlighted a distinct and consistent shift away from employment
in large firms and towards small enterprises in the 1980s in every major
western economy.
Others have challenged these claims, however. An early rebuff came
from Armington and Odle (1982), whose study of employment changes
over 197880 revealed much smaller small-business job creation rates
than Birch (1979). But as Kirchhoff and Greene (1998) pointed out,
Armington and Odles findings might have merely reflected the unusually subdued macroeconomic conditions prevailing between 1978 and
1980. Weightier criticisms of Birchs thesis came in the late 1980s and
early 1990s. In particular, Davis and Haltiwanger (1992) and Davis,
Haltiwanger and Schuh (1996a, 1996b) argued that conventional wisdom about the job-creating powers of small businesses rests on statistical
fallacies and misleading interpretations of the data (Davis, Haltiwanger
and Schuh, 1996a, p. 57). These were said to include:
1. The size distribution fallacy, whereby static size distributions of numbers employed by employer size are used to draw inferences about
dynamic changes in employment shares. Measures such as the net
change in employment by small firms as a proportion of the net change
in total employment are biased when firms move between size categories. They can also be misleading if the denominator of this ratio is
very small over a particular period, exaggerating the scale of employment growth by small firms.
2. The regression fallacy, whereby transitory size shocks bias the relationship between employment growth and firm size. To see this, let Ht be
true employment size at time t, and Ht be observed size: Ht = Ht + vt ,
where vt is a measurement error with variance v2 . Suppose
Ht = Ht1
+ ut , where ut is a transitory shock that is independent of vt .
Then the true average conditional change in employment size is zero:
E(Ht |Ht1
) = 0.
196
197
created (Davis, Haltiwanger and Schuh, 1996a). Small firms also employ
more part-time workers, freelancers and home-workers. Furthermore,
their employees tend to be less well educated on average, receiving lower
wages, fewer fringe benefits, lower levels of training and working longer
hours with a greater risk of major injury5 while enjoying lower job tenure
than their counterparts in larger firms (Brown, Hamilton and Medoff,
1990). Brown, Hamilton and Medoff (1990) in particular reported a
substantial size-wage premium, with workers in large companies earning over 30 per cent more on average than their counterparts in small
firms. This finding appears to hold across industries and countries, too.
Of course, small firms might also offer compensating benefits, such as
a more flexible and informal working environment, greater employee involvement and more tangible commitment by the owners.
8.2
8.2.1
Hours of work
198
199
200
{t ,h St ,h Et }
subject to
and
1 t
U(t , h Et , h St ; t )
1+
t
1 = h Et + h St + l t
h Et , h St , l t 0
Bt+1 = (1 + r t )Bt + w t h Et + q (h St , x) t .
(8.1)
t
(8.2)
(8.3)
Ut = t =
Et ( t+1 )
1+
Uh Et = t w t + Et
,
Uh St = t q h St + St ,
where t is the marginal utility of wealth, and the two j t terms are
KuhnTucker multipliers required to ensure non-negative labour supplies. Assuming a particular separable form for the utility function, it
is possible to derive, as an interior solution, a labour supply equation
for each of the two occupations j = {S, E}, which has the semi-log
form
h j t = 0t + 1 ln w j t + 2 ln t ,
(8.4)
201
(8.5)
202
h as
() := w S U1 /h U2 /h
is convex or concave in . Differentiating twice with respect to yields
2 ()
3 U1 ()
= wS
,
2
y3
(8.6)
203
vt t + v h t (xh t + t )
vt + v h 2t
vt+1 = vt + v h 2t .
(8.7)
(8.8)
Evidently, if h t = 0 then t+1 = t and vt+1 = vt . Thus if the entrepreneur expends no effort, he obtains no new information about his
entrepreneurial ability.
If zt = 0, the individual takes an outside option (e.g. paid-employment)
that yields utility w t . Let Ut be the entrepreneurs discounted expected
utility given that he entered initially and chooses all future z and h values
optimally; Ut 0 for t > T. Et is the expectations operator conditioned
on the information available at time t, and = 1/(1 + ) (0, 1] is the
discount factor. In each time period after entry at t = 1, we have
Ut = max w t (1 zt ) + [Et (xh t + t ) c(h t )]zt + Et Ut+1
zt ,h t
t = 2, 3, . . . , T .
(8.9)
204
[ET1 UT ]
= 0,
h T1
(8.11)
where the derivative in this equation is obviously positive. Now for the
presumed pattern of continuation to be optimal, we must have T1
T . So even if T1 = T it must follow that h T1 > h T .
The logic behind Proposition 7 can be seen by comparing the period
T objective with that for T 1 (the latter is (8.10) in the proof ). Only
part of the payoff to supplying effort is the production of current output.
Greater effort also generates returns in the form of valuable information
about the future.10 As the entrepreneur approaches retirement, the value
of information about future returns in entrepreneurship declines to zero.
Consequently, this gives the entrepreneur less incentive to supply costly
effort as he ages.
For the reasons given earlier, a finding that entrepreneurs work fewer
hours as they age can be attributed to several factors, not just declining
information value from work. We now proceed to consider the specific
issue of retirement and entrepreneurship in further detail.
8.2.2
Retirement
It is now well established in the UK and USA that among older workers,
the self-employed are more likely to participate in the workforce than employees are.11 In both countries, around one-third of the workforce aged
over sixty-five is self-employed (Iams, 1987; Moralee, 1998; Bruce, HolzEakin and Quinn, 2000). This proportion appears to have been relatively
stable over time. Among the very oldest segment of the workforce, selfemployment rates are even higher (Fuchs, 1982). Several explanations of
these phenomena can be proposed:
1. Older workers are from cohorts in which self-employment was once
more common than it is now.
205
2 X2i
= 2 ln Bai +
+ ui 2
1
if zr i 0
zr i :=
0
if zr i < 0 ,
(8.12)
(8.13)
(8.14)
206
significantly less likely to retire than those who had recently switched
into self-employment. This may suggest that older employees who switch
into self-employment regard self-employment as a transition towards full
retirement. Strikingly, neither lifetime wealth nor poor health were significant determinants of retirement by the self-employed. This was despite
both the relatively high levels of lifetime wealth and the greater incidence
of poor health among the self-employed Retirement Survey respondents
(Parker, 2003b) and contrasts with previous findings about the impact of poor health on retirement among older American employed and
self-employed workers (Quinn, 1980; Fuchs, 1982).13
Some commentators have contended that self-employment among
older workers so-called third-age entrepreneurship may be an important phenomenon. The institutional backdrop is that government
policies in the USA and elsewhere since the 1980s have made continued work among older people an increasingly attractive option (Bruce,
Holz-Eakin and Quinn, 2000). In addition, tax-based savings incentives
appear to be eagerly exploited by the self-employed (Power and Rider,
2002).14 However, there is little evidence that third-age entrepreneurship is widespread. For example, questionnaire responses revealed that
at most only 15 per cent of fiftyseventy-five-year-old Britons expressed
any interest in self-employment (Curran and Blackburn, 2001). While
acknowledging the limitations of survey claims about future anticipated
behaviour, this figure is likely to be an upper-bound estimate of the true
level of interest because no respondents have to bear immediately the costs
of switching into entrepreneurship. Nor is it obvious that the importance
of self-employment among older people is set to increase dramatically in
the near future.
N OT E S
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
207
In this chapter we investigate the growth, innovative performance and survival of new entrepreneurial ventures. Section 9.1 outlines an integrated
theoretical model of firm entry, growth and exit by Jovanovic (1982). This
model provides a useful framework for understanding why some small
firms survive and grow, and why others die. It is also helpful for interpreting empirical results on these phenomena. Section 9.2 summarises
evidence about the growth of small firms and innovation. Section 9.3
presents facts about the survival and exit of new small firms, and their
determinants.
It is helpful to clarify at the outset what the chapter does not attempt
to do. We do not cover the literature on dynamic industrial organisation
that has developed since Jovanovic (1982) (see, e.g., Ericsson and Pakes,
1995). Nor do we analyse market entry by new firms, since many of
these are not wholly new firms, but existing firms that have diversified
into a new market, or that have re-positioned themselves from a different
industrial sector (Storey, 1991). Nor will we repeat results about factors
affecting market entry by entrepreneurs covered elsewhere in the book.
9.1
209
(9.1)
210
(9.3)
211
Firm output
Survival
Failure
~
Boundary output, q
Vw
Vw
time, t
Figure 9.1 Selection and survival in the Jovanovic (1982) model
of less than q := q [Pt | (a, t; P)], and will remain in the industry otherwise. Figure 9.1 illustrates two examples of realisations of firms outputs,
together with this boundary. Below q (the exit region) V(, a, t; P) < w
and above q (the continuation region) V(, a, t; P) > w.
Jovanovics model has the following implications for entrepreneurial
ability, venture growth, exit, industry concentration, profits, and output:
J.1 Entrepreneurs who run young firms have had less time to accumulate
information about their true abilities. Therefore the level and variability
of growth rates are largest among younger and smaller firms. Growth
rates are lower among mature surviving firms.
J.2 Firms that exit never return because they know that the output
price cannot rise above the level at which they left; and an exiting entrepreneur never obtains any more information to change his terminal
belief about his ability.
J.3 Results J.1 and J.2 imply that (cohort) industry concentration increases over time, since initially all firms of a given cohort were the
same size, at which industrial concentration was at a minimum.
212
213
9.2.1
(9.4)
214
where is the mean firm growth rate, assumed the same for all i ; and
where ui t+1 is a mean-zero stochastic disturbance term with a distribution
that is identical across firms i . Early studies found some empirical support
for lognormal firm-size distributions and firm-growth rates being roughly
independent of firm size (see, e.g., Hart and Prais, 1956; Simon and
Bonini, 1958).
Three assumptions underlying Gibrats Law appear questionable. One
is that the population of firms is fixed. In practice, of course, firms are
born and die, so this assumption is not tenable. A second is that each
firm faces a draw from a common distribution of random shocks. But
recent evidence suggests that the variance of firm growth rates is higher
for smaller firms (see below). Third, Gibrats Law assumes that mean
growth rates are the same for all firms. Again, recent evidence reviewed
below refutes this claim, showing that smaller firms tend to have higher
growth rates.
In the light of these problems several refinements to Gibrats Law have
been proposed (see Ijiri and Simon, 1977). Perhaps the most popular
generalisation allows for heterogeneous growth rates, giving rise to the
specification
ln q i t+1 = i + ln q i t + ui t+1 ,
(9.5)
where i is the firm i -specific growth rate, and < 1 permits Galtonian
regression to the mean in firm size: i.e. large firms have lower growth rates
than small firms do. Clearly Gibrats Law emerges as a special case of
(9.5) when the i are the same for all i and when = 1.
A third, even more general, specification permits a direct test of the
Jovanovic model described in chapter 9, section 9.1. This specification,
suggested by Brock and Evans (1986, ch. 6), takes the form
ln q i t+1 ln q i t = + 1 ln q i t + 2 [ln q i t ]2 + 3 ln ai t + 4 [ln ai t ]2
+5 ln q i t ln ai t + ui t+1 ,
(9.6)
where ai t is firm i s age at time t, and where and the s are parameters.
The inclusion of both firm age ai t as well as firm size q i t on the RHS of
(9.6) permits tests of prediction J.1 of the Jovanovic model. Of course, it
is also possible to include firm- and owner-specific factors as additional
explanatory variables in growth equations, in order to explore the effects
of a broader range of possible growth determinants. We now turn to the
empirical evidence on these issues.
9.2.2
215
216
Innovation
A feature of the growth of small firms that has not been mentioned so
far is innovation, deemed by Schumpeter to be a central aspect of entrepreneurship.
Before turning to the evidence, we note that there are several reasons
why small firms might possess an advantage over large firms at innovating.
They are said to include:
r Bureaucratic inertia in large firms, which is not conducive to innovation
(Link and Rees, 1990). Individuals located outside large firms might be
able to develop innovative ideas untramelled by conventional corporate
thinking (Pavitt, Robson and Townsend, 1987).
r Shorter lines of communication in small firms (Fielden, Davidson and
Makin, 2000).
r Greater responsiveness by small firms to changing demand and demography (Bannock, 1981).
r Greater ease of technology diffusion between small firms, especially
when involved in networks and clusters that generate opportunities for
cross-organisational learning (Morgan, 1997).
r Diminishing returns to R&D, which affect large firms more than small
firms (Acs and Audretsch, 1991).
r Larger firms having greater demands on limited entrepreneurial attention for managing existing projects, and so facing a higher opportunity
cost from innovating and thereby creating further demands on their
attention (Gifford, 1998).
r Small firms having greater incentives to innovate if that helps them to
overcome entry barriers and retaliatory conduct by incumbents (Acs
and Audretsch, 1989).
217
218
One way of trying to overcome these problems is to take a macro approach, regressing aggregate GDP growth rates (for example) on measures of entrepreneurial activity (Blanchflower, 2000; Reynolds et al.,
2001, 2002). However, this approach is almost certainly prone to severe problems of omitted variable bias, aggregation bias and endogeneity,
while its reduced form nature prevents the interpretation of any of the
estimated parameters.
Finally, we might ask whether free-market economies achieve the right
balance between investment in innovation-generating research and entrepreneurs who bring innovations to market. Michelacchi (2003) studied this issue using a model with free occupational choice where rents
to research and entrepreneurship are fixed exogenously by Nash bargaining. Michelacchi showed that, if rents to entrepreneurship are too
low, then an economy could end up wasting research, with insufficient
entrepreneurial skills to exploit the innovations produced by researchers.
This might justify government intervention to promote entrepreneurship,
though it should be noted that entrepreneurial over-investment is also
possible. However, it is unclear whether Michelacchis results are robust
to an extension of his model in which rents are endogenously determined
by the productivity of effort in each sector.
9.3
Exit
As explained above, the Jovanovic (1982) model makes several predictions about the types of firms that are likely to fail and leave the market,
as well as about those that are likely to grow and prosper. This section
focuses on the process of exit and its converse, survival. We first present,
in subsection 9.3.1, some stylised facts about the survival rates of new
ventures, the related issue of quits from self-employment, and the temporal distribution of new-firm failures. It is important to note at the outset
that the continuation of an individual in self-employment is not necessary equivalent to survival of a business because an individual can remain
self-employed while opening and closing successive businesses. Subsection 9.3.2 briefly describes two important econometric models of firm
survival; and subsection 9.3.3 summarises the body of empirical results
on firm-specific, owner-specific, and economy-wide factors associated
with survival.
9.3.1
It is now well known that new firms have low survival rates, and that
many people who set up in self-employment do not remain self-employed
219
220
9.3.2
Probit/logit models and hazard models are the most widely used techniques for quantifying the effects of individual- and firm-specific characteristics on the chances of survival in entrepreneurship.
Probit and logit models
Consider again the probit and logit models described in chapter 1, subsection 1.6.1. Those models regressed a binary variable zi on a vector
of explanatory variables, Wi , where i indexes an individual observation.
One can define zi as equal to one if individual i starts and remains in
self-employment after some time interval has elapsed and zero if i has
left self-employment by this time. Alternatively, in applications where i
indexes a particular firm from a sample of firms, zi can be defined as
equal to one if the firm is still in business and zero if the firm has left the
market. In both cases the marginal effects of an explanatory variable on
the probability of survival are calculated using (1.11).
Hazard models
Hazard models provide a direct way of identifying the factors that
determine how long (rather than whether) individuals remain in
221
self-employment, or how long firms remain in the market. For expositional clarity, consider for the moment the case of an individual remaining
in self-employment. At each discrete point in time t there is a probability
(or hazard) that individual i , who has been observed in self-employment
for ai periods up to t, leaves self-employment. The Cox proportional
hazard model is described by
Hi (t) = H0 (t). exp[ Xi (t)] ,
(9.7)
where H (t) is the so-called baseline hazard at t; Xi is a vector of characteristics for individual i ; and is a vector of parameters to be estimated.
This is called a single-risk hazard model, because there is only a single
risk: that of leaving self-employment.
The single-risk model can be estimated without placing restrictions on
the form of the baseline hazard in (9.7). The probability of an individual
i s spell being completed by time t + 1 given that i was still self-employed
at t is
0
t=1
+ (1 i )
di
ln[1 Li (t)]
(9.8)
t=1
Equation (9.8) is maximised with respect to and the s to obtain maximum likelihood estimates. The method is implemented on many standard
software packages. Note of course that a similar interpretation applies if
i indexes firms rather than self-employed individuals.
Failure may come from more than one source: for example, individuals may leave self-employment for either paid-employment or
unemployment. We might be interested to discover, for example, whether
self-employed individuals who exit into unemployment have different survival characteristics from those who exit into paid-employment. If so, a
competing-risks model is needed. Such a model posits a separate hazard function for each of the destinations, whose log-likelihoods are given
222
by (9.8) where i = 1 now denotes exit into the given destination, and
i = 0 applies for other outcomes. The sum of the log-likelihoods over
all possible destinations gives the total log-likelihood to be maximised,
though in many applications, each destination hazard is estimated as a
separate single-risk hazard where exit as a completed spell is defined only
with respect to the given destination.
As an example of the potential practical importance of the distinction between single and competing risk formulations, consider the British
study by Taylor (1999). In his competing-risk model, Taylor distinguished
between voluntary exit into paid-employment and involuntary exit in the
form of bankruptcy. This distinction turned out to be an important one,
because while greater personal wealth was associated with a lower male
bankruptcy rate in Britain, it had no effect either on voluntary exit or on
exit for any reason.
9.3.3
There is an enormous body of research on the individual- and firmspecific determinants of entrepreneurial survival and exit. Rather than
attempt to provide an exhaustive survey of every study, we summarise
below the key determinants of survival in self-employment (for individuals) and business (for firms) in developed countries.14
r Duration. The evidence from hazard and probit models tells a consistent story across different countries. The probability of departures from
self-employment decreases with duration in self-employment (Evans
and Leighton, 1989b; Carrasco, 1999; Taylor, 1999; Lin, Picot and
Compton, 2000), the age of the business, and the tenure of business
managers (Westhead and Cowling, 1995; Holmes and Schmitz, 1996;
Cressy, 1999; Taylor, 2001). These findings may reflect learning by
self-employed business owners about their abilities and the external
environment over time (see section 9.1).
r Human capital of the entrepreneur. The bulk of evidence points to a positive relationship between business survival and an entrepreneurs human capital.15 In particular, previous experience in self-employment
has been found to increase the probability of survival in a new spell
of self-employment or business ownership (Holmes and Schmitz,
1996; Quadrini, 1999; Taylor, 1999). This may be indicative of entrepreneurial learning. In contrast, experience acquired in a managerial capacity prior to owning a business seems to have an insignificant
impact on survival in self-employment (Bates, 1990; Boden and Nucci,
2000). Current occupational and business experience has stronger effects, with Taylor (1999) finding that professionals and skilled manual
223
224
important: having a self-employed spouse reduced the likelihood of exits from self-employment in Canada through the provision of a steady
stream of family income.
r Innovation. It might be thought that firms that choose to innovate
improve their survival prospects relative to small firms that do not.
However, the current body of evidence on this issue is mixed and inconclusive (e.g. contrast Audretsch, 1991; Agarwal, 1998, with Audretsch
and Mahmood, 1995). The ambiguity of these results may be attributable to the use of aggregate measures of small-firm innovative
activity in these studies. It might also be informative to disaggregate innovations by their type. For example, Cosh, Hughes and Wood (1999)
found that in Britain product innovations significantly increased the
probability that a small firm was acquired, while process innovations
significantly decreased the probability of small-firm failure.
r Marketing. The size of the market in which small firms sell their products presumably also has an impact on survival. A limited amount
of evidence suggests that the broader the market and product range,
the greater the probability that small firms survive. For example, Reid
(1991) estimated that that a 1 per cent increase in the product group
range increased the probability that small Scottish owner-managed enterprises would stay in business by 0.34 per cent, all else equal. This
result is consistent with diversification enhancing survival chances, for
instance by facilitating market re-positioning when changing market
conditions reveal profitable new niches (Holmes and Schmitz, 1990).
And in an analysis based on German data, Bruderl,
Preisendorfer
and
Ziegler (1992) reported that survival rates were higher for firms that
aimed their products at a national rather than a local market.
r Macroeconomic conditions
Unemployment. It is now fairly well established that businesses that
start up in conditions of high unemployment have worse survival
prospects than firms that start up in more favourable economic conditions. For example, Audretsch and Mahmood (1995) found that in
the USA new-firm hazard rates increase with the aggregate unemployment rate. And using a competing-risks hazard model estimated with
British BHPS data, Taylor (1999) found that self-employed individuals who started businesses in times of high national unemployment
were more likely to go bankrupt than otherwise comparable individuals who started up in more favourable national economic conditions.
Corroborative evidence has also been reported using time-series data
(Hudson, 1989).
At an individual level, experience of unemployment also appears
to worsen the survival prospects of businesses. For example, it has
225
been established that Spanish self-employed males who were unemployed prior to entering self-employment had hazard rates three
times greater than those who previously worked in paid-employment
(Carrasco, 1999; and see also Pfeiffer and Reize, 2000, for evidence
from Germany). Thus although the unemployed are more likely to
enter self-employment than others (see chapter 3, subsection 3.3.2),
many of them seem to be less suited to it in the long term, having
higher exit rates. The previously unemployed are more likely to have
rusty human capital, lower quality information about business opportunities and possibly also lower motivation.
Interest rates. Time-series studies have consistently found that
higher (nominal) interest rates increase the aggregate rate of
bankruptcies in the UK.21 The US evidence is less clear-cut (Hudson,
1989; Audretsch and Mahmood, 1995).22 One reason for a positive
relationship between bankruptcies and interest rates might be higher
debt-servicing costs causing insolvency. Another is that interest rates
tend to be high in inflationary conditions, inflation being associated
with business uncertainty.
r Industry organisation and ownership. Mata and Portugal (1994) estimated
a proportional hazard model with Portuguese data, and reported that
survival prospects were higher in firms with multiple plants and in industries with high growth rates, and lower in industries with a greater
incidence of entry. These findings have since been corroborated by
Audretsch and Mahmood (1994) and Mata, Portugal and Guimaraes
(1995).
Bates (1998) asked whether franchisees were more likely to survive
relative to non-franchisees. Reasons for supposing they are include
their adoption of a proven business format or product, and benefits
from advertising and management training provided by the franchiser.
Using US CBO data of new-restaurant starts in 1986 and 1987, Bates
found that franchisees did indeed have higher survival rates than nonfranchisees, but lower survival rates if franchises owned by large corporations were excluded from the sample. Similar findings for the UK
have been obtained by Stanworth et al. (1998).
This completes our overview of the salient factors associated with the
demise of new entrepreneurial ventures and the departure of individuals
from self-employment. For the most part, the discussion has abstracted
from factors associated with entry into business. However, on a more
aggregated level, it is of interest to ask whether entry and exit rates are
related dynamically. We conclude by taking a brief look at this question.
Table 9.1 sets out several possible linkages between the aggregate birth
rate of new small firms in a region at time t, denoted F Bt , and the
226
Competition
Marshall
n.a.
n.a.
n.a.
F Bt+
t
F Bt
F Dt+
t
F Dt
F Bt+
t
F Dt
F Dt+
t
F Bt
F Bi t =
m
1
t
F Bi,t
t +
t=1
m
F Di t =
t=1
m
1
t
F Di,t
t
t=1
1
t
Xi,t
t + ui t
2
t
F Bi,t
t +
t=1
m
m
m
(9.9)
2
t
F Di,t
t
t=1
2
t
Xi,t
t + v1t ,
(9.10)
t=1
227
Conclusion
228
229
N OT E S
1. See Brock and Evans (1986, pp. 603) for a relaxation of this assumption.
2. Reinvestment of profits may promote growth by enabling small firms to attain
the industrys minimum efficient scale (Audretsch, 1991) or to circumvent
borrowing constraints (Parker, 2000).
3. See Hall (1987), Reid (1993) and Hart and Oulton (1996). A very small
number of small firms enjoy dramatic growth rates (Reid, 1993; Storey, 1994a;
DTI, 1999). For example, the DTI (1999) estimated that only about 1 per cent
of new business start-ups in the UK eventually achieve a turnover in excess of
1million.
230
4. For example, using data on 8,300 small US firms over 197682, measuring
firm size in terms of employment, and controlling for industry and regional
factors, Brock and Evans (1986) reported the following estimates of (9.6):
1 = 2.25, 2 = 0.35, 3 = 3.02 and 5 = 0.98. All these estimates were
significantly different from zero, and were robust to sample-selection bias
caused by surviving firms having higher growth rates. However, a caveat is
that there may be a lag before growth occurs. According to Phillips and Kirchhoff (1989), only 10 per cent of new firms between 1976 and 1986 grew in
employment terms in the first four years, but over half had grown within eight
years.
5. See Evans (1987a, 1987b), Cooper, Woo and Dunkelberg (1989), Dunne,
Roberts and Sammelson (1989a), Audretsch (1991), Davis and Haltiwanger
(1992), Variyam and Kraybill (1992), Mata (1994), Barkham, Hart and
Hanvey (1996) and Goedhuys and Sleuwaegen (2000). Geroski (1995) and
Sutton (1997) review the literature.
6. See Cooper and Bruno (1977), Johnson and Rodger (1983), Roberts (1991),
Cooper, Gimeno-Gascon and Woo (1994) and Barkham, Hart and Hanvey
(1996). Multiple founders have a broader base of skills and experience and
may give each other psychological support.
7. For US evidence of insignificant effects from gender on gross business earnings growth rates, see Kalleberg and Leicht (1991). Cooper, Eimeno-Gascon
and Woo (1994) reported positive and significant effects on growth from
starting capital.
8. These included firm size, the owners education and multiple sources of funding.
9. See Scherer (1980, pp. 40738, 1991), Acs and Audretsch (1988), Audretsch
(1991), Cohen and Klepper (1996) and Klepper (1996). These findings refute Schumpeters prediction of ever-increasing concentration of innovation
in large firms.
10. See also Lin, Picot and Compton (2000), who showed that a much higher
proportion of Canadians who left self-employment departed the labour force
altogether, than Canadians who left paid-employment.
11. See also Fuest, Huber and Nielsen (2002), who cited OECD data from the
late 1980s displaying marked cross-country variations in entrants business
survival rates. According to these data, between 30 and 50 per cent of new
entrants survive for seven years. The highest survival rates were observed in
France and Portugal; the lowest in Finland and the UK.
12. See Altman (1983) and Hudson (1989) for US evidence and Hudson (1987b)
and Cressy (1999) for UK evidence.
13. One implication, noted by Frank (1988), is that failing entrepreneurs remain
in the market not because they mistakenly believe that they should condition
their behaviour on sunk costs, but because of their strongly held prior belief
that they are intrinsically able (but unlucky). For rational decision makers
sunk costs are bygones; and bygones are bygones in love, war and economics.
14. Applications to developing countries are less common, though see
Nziramasanga and Lee (2001). Bates (1999) analysed the duration of selfemployment among Asian immigrants into the USA.
231
15. See Brock and Evans (1986), Bates (1990, 1997), Bruderl,
Preisendorfer
and
Ziegler (1992), Cooper, Gimeno-Gascon and Woo (1994), Cressy (1996,
1999), Gimeno et al. (1997), Bruderl
and Preisendorfer
(1998), Taylor
(1999), Boden and Nucci (2000) and Kangasharju and Pekkala (2002). This
finding appears to hold for males and females of all ethnic groups, though
failure rates tend to be higher for women, blacks and non-founders than for
non-minority male founders (Holmes and Schmitz, 1996).
16. However, the effects of age on survival in self-employment may be unstable
through time (Holtz-Eakin, Joulfaian and Rosen 1994b; Cressy, 1996; Taylor,
1999), reflecting the state of the business cycle.
17. UK studies include Dunne and Hughes (1994), Storey (1994a), Westhead
and Cowling (1995) and Hart and Oulton (1996). US studies include Brock
and Evans (1986) Evans (1987a, 1987b), Cooper, Woo and Dunkelberg
(1989), Dunne, Woo and Dunkelberg (1989a), Audretsch (1991), Audretsch
and Mahmood (1995) and Gimeno et al. (1997). For evidence on Portugal
and Germany, see Mata and Portugal (1994), Bruderl,
Preisendorfer
and
Ziegler (1992), and Bruderl
232
death rates. They identified such industries in terms of the degree of turbulence, commonly defined as the ratio of the sum of birth and death rates
to the existing stock of businesses. Reynolds (1999) showed that a variety of
job and establishment turbulence measures were significantly correlated with
annual regional job growth in the USA, which he interpreted as evidence of
creative destruction.
24. Subsequently Kangasharju and Moisio (1998) broadly replicated these findings, using Finnish data and a more efficient instrumental variables estimator.
One difference was their finding that deaths had a major impact on future
births and deaths in Finland, whereas births made relatively little difference
to the dynamics. However, Johnson and Parker (1996) found that the inclusion of macroeconomic variables in (9.9) and (9.10) eliminated some of the
lagged birth/death effects something that Kangasharju and Moisio (1998)
did not take account of.
Part IV
Government policy
10
235
236
10.1
Chapter 5 reviewed the theoretical case for credit rationing and underinvestment in entrepreneurial ventures. This case has received substantial
attention in policy circles and has motivated various kinds of government
intervention, especially loan guarantee schemes (LGSs). In this section,
we first describe such schemes, before evaluating their appropriateness
in terms of theoretical models of credit rationing. Then evidence on their
actual performance in the UK and USA is reviewed. Finally, we briefly
discuss other forms of government intervention in credit markets.
10.1.1
Organisation
LGSs provide a government-backed guarantee to encourage banks and
other financial institutions to lend to small firms who are unable to raise
conventional finance because of a lack of security or an established track
record. LGSs are widespread, with versions operating in the USA, the
UK, France, Germany and Canada and several other countries.
Although the details vary between countries and within given countries depending on the type of loan1 the basic principles of a LGS are the
same. A LGS typically guarantees finance for both new start-ups and going concerns. Only borrowers unable to secure a conventional loan from
a bank, and in non-proscribed industrial sectors,2 may apply for a loan
guarantee. A bank nominates ventures for approval by the government
and administers the loans. Conditional on approval by the government,
the bank takes the usual repayment if the venture succeeds. If it fails, the
bank is liable only for a fraction of the loss, with the rest borne by the
government. In the USA, the Small Business Administration (SBA) underwrites between 75 and 80 per cent of loans; in the UK, the British government underwrites between 70 and 85 per cent. Borrowers are charged
an arrangement fee, and pay the usual market rate plus a small premium.
Operational costs can be substantial (see table 10.1 for details on this and
other aspects of LGSs in several countries).
Theoretical perspectives
Can governments without access to inside information about entrepreneurs ventures use a LGS to improve on the competitive equilibrium under asymmetric information? If financial markets were efficient, one would expect all loans involving reasonable degrees of risk and
promising reasonable rates of return on capital to be made by privatesector lenders. Any rejected loan applications would reflect exceptional
237
Table 10.1 Features of LGSs in the UK, the USA, France, Germany
and Canada
Terms
Maximum
guarantee
Arrangement fee
Loan premium
Loan term
Number of
guarantees
Net cost of
scheme
UK
USA
France
Germany
Canada
7085%
7580%a
5065%b
80%
85%
1% of loan
23.875%
of guarantee
0.5% of
credit
725 years
45,300
(1997)
95million
(1998)
None
0.75%
of guarantee
0.81% of
credit
1523 years
6,850
(1996)
n.a.
2% of loan
1.5% of loan
210 years
6,942
(19967)
46million
(19978)
0.6% of
credit
215 years
5,000
(1996)
36million
(1996)
1.25% of
credit
010 years
30,765
(1997)
42.5m
(1997)
Notes: a 70 per cent for start-ups; 85 per cent for firms with at least two years trading
history.
b 65 per cent for start-ups. n.a. = Not available.
Source: KPMG (1999, table 4.1).
levels of risk; and any government-backed lending to facilitate such ventures would therefore be expected to result in high default rates. However,
if the financial market for small-firm lending is inefficient a possibility
explored in chapter 5 then the case for government intervention in
credit markets may be stronger. A few studies have addressed this issue
directly, the most notable being a pair of papers by William Gale.
Using a simple model with two types of agent, one high-risk (b), and
one low-risk (g), Gale (1990a) showed how a LGS can actually be selfdefeating. In line with the analysis of chapter 5, banks would ideally
prefer to fund gs to bs, but under asymmetric information they cannot
observe these types directly from the pool of loan applicants. All agents
are assumed to have socially efficient ventures, so if there is any credit
rationing it entails an efficiency loss. A crucial assumption made by Gale
is that it is costly for banks to seize collateral C when ventures fail, so
any policy that discourages the use of collateral will increase efficiency in
this respect. There are two possibilities: (a) collateral is plentiful, and (b)
collateral is limited.
Consider (a) first. When collateral is available, the analysis of subsection 5.1.3 can be applied. In terms of figure 5.4, C is the BAD, and a
separating equilibrium exists, in which gs choose a low-D, high-C contract g (where D is the interest repayment) to differentiate themselves
from bs who choose a high-D, low-C contract, b . There is no credit rationing. Now the introduction of a LGS targeted only at g-type ventures
238
239
240
Another limiting factor is that the scale of LGSs is often small in relation to the rest of the market. Guaranteed loans in the UK and the USA
comprise only about 1 per cent of all small and medium-sized enterprise
(SME) on-lending by value, making it a marginal source of lending to
the SME sector.7
Bosworth, Carron and Rhyne (1987) conducted a thorough evaluation of the SBAs LGS. Bosworth, Carron and Rhyne started with an
optimistic estimate that around 20 per cent of SBA-backed loans were
non-additional. Applying an empirically-based 23 per cent default rate
for the whole portfolio, this means that only 60 per cent of SBA loans
could generate benefits to offset the costs of the scheme, requiring a net
subsidy of 8.7 per cent. Thus the economic benefits required for the
scheme to break even were 14.5 (=8.7/0.6) per cent of the loan amount
over and above the mandated loan repayments.8 Bosworth, Carron and
Rhyne and Rhyne (1988) doubted whether the economic benefits would
be as great as this.
Some detailed evaluation evidence has also been compiled for the UKs
Small Firm Loan Guarantee Scheme (SFLGS). Survey work by KPMG
(1999) estimated that around 70 per cent of SFLGS-supported firms
were finance-additional (i.e. would not have been financed without the
involvement of the LGS), and leveraged 161 million of additional private finance between 1993 and 1998. However, survey results identified
high displacement rates of between 76 and 86 per cent. This limited the
employment creation contribution of guaranteed ventures to between 0.3
and 0.6 jobs per firm in the eighteen months following the loan, amounting to under 10,000 net additional jobs in total. The net additional cost
per job charged to the government was estimated at between 9,500 and
16,600.
Naturally, there might be other supply-side benefits from LGSs that are
hard to quantify, such as greater competitiveness caused by the creation
of LGS-backed ventures, and the benefit of keeping initially struggling
businesses afloat that might develop profitably and grow in the future.
Early evidence pointed to high failure rates of LGS-backed businesses
(Bosworth, Carron and Rhyne, 1987; Rhyne, 1988); but since then the
UK and US LGSs have been made more stringent with lower guarantee
fractions. This is reflected in more recent UK evidence that LGS-funded
businesses do not have higher failure rates on average than non-LGSfunded businesses (KPMG, 1999). In addition, Cowling and Mitchell
(1997) provided some econometric evidence that the SFLGS had a positive if modest effect on the aggregate UK self-employment rate. But all
this evidence is only mildly supportive of LGS programmes. While they
241
do not do much obvious harm, they do not appear to do very much good
either.
10.1.2
Other interventions
242
different from zero. Wren conjectured that the (slightly) greater effect for
small firms reflected their higher marginal cost of external funds, which
made them more responsive to assistance.
10.2
243
(10.1)
244
This tax system has three offsetting effects: (1) Taxation reduces post-tax
incomes in entrepreneurship, making entrepreneurship less attractive. (2)
Taxation smooths entrepreneurs incomes over different states, providing insurance that makes entrepreneurship more attractive. And (3) this
benefit of risk pooling increases the demand for labour, pushing up wages
relative to profits (Kihlstrom and Laffont, 1983b).
By the normalisation rule, the proportion of the workforce in
entrepreneurship is n S = [1 + H(, w)]1 , where H(, w) := argmax
V(, w). The governments objective is to maximise a utilitarian social
welfare function, , defined on post-tax utilities:
:= n S V(, w) + [1 n S]U [(1 + )w] .
(10.2)
(10.3)
245
246
There are two principal reasons why entrepreneurs might pay different amounts of tax than employees with the same pre-tax incomes:
247
(1) Allowable cost deductions in self-employment (such as business expenses), and the leeway to draw up accounts to practice intertemporal
tax-shifting;14 and (2) Differing effectiveness of tax enforcement by income source, resulting in different incentives for income under-reporting
and tax evasion by the self-employed. Unlike entrepreneurs profits, wage
and salary incomes usually offer little or no scope for tax evasion, because
of third-party reporting and tax withholding by employers.
There is a large literature on the economics of tax evasion, but we focus
below only on the following issues: (1) How the number of entrepreneurs
is affected by taxation when tax evasion opportunities exist, and (2) Appropriate tax-penalty policies when individuals can choose freely between
entrepreneurship and paid-employment.
Key theoretical studies that address the issue of tax evasion and the
number of entrepreneurs include Watson (1985) and Jung, Snow and
Trandel (1994). For example, Jung, Snow and Trandel analysed a model
of an economy comprising two occupations. Tax evasion is possible in one
occupation (self-employment, S) but not in the other (paid-employment,
E). A proportional tax rate = 1 is applied to pre-tax income in each
occupation, y j = y j (n S) ( j = {E, S}), where income in each occupation
is a function of n S, the proportion of individuals choosing S. Reflecting
diminishing marginal returns to labour in each occupation, dyS/dn S < 0
and dyE /dn S > 0. Each self-employed person chooses how much income
Y to conceal from the tax authorities and which occupation to join; labour
is inelastically supplied irrespective of occupation. The probability of being audited by the tax authority is : if an individual is caught, they must
pay a penalty which is a multiple > 0 of the evaded tax, Y. With all individuals possessing identical utility functions U(), the optimal amount
of income concealed, Y , is
Y =
Labour market equilibrium occurs when individuals are indifferent between E and S:
U() = [1 ].U() + .U( ) ,
where
:= yE (nS) ,
:= yS(nS) + Y (1 ) ,
:= yS(nS) Y (1 ) ,
where nS is the equilibrium number of individuals choosing selfemployment. It is easily shown that nS is decreasing in (see also Watson,
1985).
248
where subscripts on U denote derivatives, and where we define
dyE
dyS
:= U [(1 ).U + .U ] > 0 .
dn S
dn S
Manipulating this expression, it is possible to prove the following proposition:
Proposition 8 ( Jung, Snow and Trandel, 1994). When tax evasion is
endogenously chosen, an increase in the marginal income tax rate will increase (leave unchanged) (decrease) the equilibrium number of self-employed
if individuals have increasing (constant) (decreasing) relative risk aversion.
The logic of this proposition is as follows. An increase in the tax rate
increases the expected benefit of evasion, though this may be offset by a
shift in risk, since tax evasion induces uncertainty and the extent of risk
aversion depends on post-tax income which has been reduced by the tax.
But under increasing relative risk aversion, the individual becomes less
risk averse after the tax so the expected benefits to self-employment are
positive. Given the generally accepted nature of assumption 1 of subsection 2.2.1, which posits non-increasing relative risk aversion, Proposition
8 provides a basis for expecting the number of self-employed to be negatively related to average and marginal income tax rates. However, this
result and indeed all the results discussed in this and the previous section is clearly sensitive to the assumption that workers do not respond
to income taxation by working and producing less. Although this issue is
well researched in labour and public economics, it has yet to command
much attention from researchers in entrepreneurship, perhaps because
of the intrinsic difficulties involved with modelling (continuous) labour
supply adjustments jointly with (discrete) occupational choice (Kanbur,
1981; Parker, 2001).15
A different question is what income taxes and enforcement policies
the government should choose in the presence of tax evasion. Pestieau
and Possen (1991) studied this problem using a model in which only
the self-employed can evade tax, and where its control (e.g. by greater
auditing of the self-employed) discourages risk taking. Auditing is costly
both for the government and for individuals who must prepare their tax
records for inspection: these costs impose deadweight losses on the economy. Therefore governments concerned purely with efficiency should do
no auditing at all. However, inequality-averse governments want to raise
249
tax to redistribute incomes and must audit in order to protect the tax
base. The government chooses the probability that individuals are audited; Pestieau and Possen (1991) further assumed that tax evaders who
are caught are fined an exogenous amount that renders them ex post the
poorest of all individuals. For sufficient degrees of inequality aversion,
Pestieau and Possen (1991) showed that the optimal rises to the point
where tax evasion is deterred completely. The reason is that under extreme inequality aversion, the welfare of the poorest individuals should be
maximised but because these are assumed to be detected tax evaders,
tax evasion itself should be completely discouraged. With this policy in
place, everyone is encouraged to become self-employed, on the assumption that self-employment is the most productive occupation. Clearly,
Pestieau and Possens (1991) results are very sensitive to their assumptions. In practice, many governments impose less stringent penalties on
detected tax evaders (Smith, 1986).
10.4
As the previous two sections have shown, the theoretical literature does
not predict a simple or unambiguous relationship between the extent of
entrepreneurship and the structure of the IT system. Therefore the form
of that relationship has to be determined empirically. Before turning to
econometric investigations of this issue, we briefly describe in subsection
10.4.1 evidence about the extent of income under-reporting and excessive business expensing by the self-employed. Subsection 10.4.2 presents
econometric evidence about the effects of IT and tax evasion opportunities in self-employment on the occupational choice decision. We argue
that most existing evidence is vitiated by various methodological problems, and conclude by presenting some new results that cast doubt on the
thesis that tax and tax evasion opportunities affect occupational choices
for the majority of self-employed people.
10.4.1
Direct evidence about the extent of income under-reporting and tax evasion by the self-employed is available from data provided by the US
Internal Revenue Services (IRSs) Taxpayer Compliance Measurement
Program (TCMP). The TCMP data are compiled by teams of auditors
who analyse thoroughly the tax affairs of samples of employee and selfemployed taxpayers on a case-by-case basis. These data have been utilised
by numerous researchers to estimate rates of income under-reporting.
The TCMP has been running since the 1960s and it tells a reasonably
250
consistent story over time. A typical result, cited by Kesselman (1989) and
based on a 1983 TCMP report, estimated that whereas 9799 per cent of
employee income was reported to the IRS, non-farm proprietors reported
on average only 78.7 per cent of their gross incomes.16 A similar estimate
was obtained from 1969 TCMP data reported by Clotfelter (1983). The
sums involved are not trivial either. Carson (1984) estimated that the selfemployed are collectively responsible for one-quarter of total unreported
income in the USA.
Rates of self-employed income under-reporting to the tax authorities
of around 20 per cent have also been found in the UK, although these
are based on less comprehensive data (Macafee, 1982, p. 155). Smith
(1986) proposed a slightly lower self-employed income under-reporting
rate of 14 per cent, and suggested that preventative policy actions
in the construction sector in particular have reduced under-reporting
rates.
A slightly different question, but one that is directly relevant for empirical research, is the extent to which self-employed people under-report
incomes to survey interviewers, despite assurances by the latter to interviewees that all data are treated in strict confidence and cannot be
divulged to any government department. Several indirect methods for
estimating this kind of under-reporting have been proposed, based on
comparisons between respondents reported incomes and expenditures.
It is not sufficient to identify as under-reporters households that spend
more than they earn, because some households may genuinely dissave and
not under-report, while others may under-report and not dissave (Dilnot
and Morris, 1981). A more reliable approach proposed by Pissarides and
Weber (1989) estimates expenditure equations for the self-employed and
employees, and then inverts them to estimate true incomes. Three assumptions underlie this approach: (i) All occupational groups report expenditures correctly to the survey interviewers;17 (ii) employees report
incomes correctly; and (iii) the income elasticity of consumption is the
same for members of all occupations with the same characteristics. Let
i denote the expenditure of household i , Xi a vector of the households
characteristics, yi the households reported income and zi a dummy variable equal to unity if the household is headed by a self-employed person,
and zero otherwise. Pissarides and Weber estimated the following regression using data on a sample of n households:
ln i = Xi + (1 + 2 zi ) ln yi + zi + ui
i = 1, . . . , n ,
(10.4)
251
i S.
(10.5)
ln i = Xi + 1 ln yi + ui .
(10.6)
Equating (10.5) and (10.6) and re-arranging yields the percentage underreporting rate of self-employment incomes as:
ln yi ln yi = ( + 2 ln yi )/1
i S.
(10.7)
(10.8)
where Xi is a design matrix containing k personal characteristics or environmental control variables, and Ti is a variable designed to capture the
tax incentive effect. Alternatively, in a time-series application, i denotes
252
and
i E MRT
iS ,
j MRTi := MRT
253
254
255
occupations, although it is possible that the experience of selfemployment under the EAS enhanced participants future earnings
(Bendick and Egan, 1987).
Taking account of deadweight costs, displacement effects and the cost
of administering the scheme, relative to the benefits generated by the new
start-ups, Storey (1994a) estimated that after taking account of the fact
that the government would have paid unemployment benefits anyway,
the EAS was essentially cost-effective, even though its effects on job creation and unemployment reduction were slight.27 There is a more general
point to be made here about the precise objectives of EAS-type schemes.
Schemes targeted at the unemployed face a trade-off between economic
objectives (e.g. high survival rates, profitability and employment creation)
and social objectives (e.g. putting to work the hardest to employ). On this
point Bendick and Egan (1987) concluded: The programmes in these
countries [France and Britain] have succeeded in turning less than one
per cent of transfer payment recipients into entrepreneurs, and an even
smaller proportion into successful ones. They cannot be said to have contributed greatly to solving either social or economic problems, let alone
both (1987, p. 540).28 Storey (1994a) concluded that the EAS probably
had a greater political than economic effect.
The evidence for countries other than the UK is similar. Pfeiffer and
Reize (2000) investigated the effects of bridging allowances to unemployed Germans on firm survival and employment growth rates. They
found that survival rates in West Germany were not significantly different for those starting up with bridging allowances; but survival rates were
6 per cent lower in East Germany for those with bridging allowances.
Having a bridging allowance made no discernible difference to employment growth rates, leading Pfeiffer and Reize (2000) to conclude that
Germanys enterprise allowance scheme does not appear to have had a
job creation impact. Together with the British evidence cited above, one
is led to conclude that, despite favourable publicity, schemes designed to
promote enterprise among the unemployed have had only a very limited
impact in practice.
10.5.2
Governments in many countries subsidise or operate agencies that provide support to entrepreneurs, either for new start-ups, existing small
firms, or both. Private-sector institutions are also involved in this process. The oft-cited rationale for support to start-ups is straightforward:
potential entrepreneurs often lack information about what it is like to
start a business, how to develop a business idea and obtain finance,
256
how to identify customers and how regulations and state benefits affect
them. They might also be nave, proposing poorly thought-out business
plans that convey an inadvertently negative impression of their business idea. Even worse, they may be unaware of deficiencies in their
own business skills. These problems may cause inefficiency and excessive exit rates of otherwise viable businesses. Hence there is a case, at
least in principle, for government involvement in improving the access to
information.
Support for start-ups often involves not only the provision of information, but also mentoring, training and advisory services, via public-sector
providers and subsidised advisers and consultants. Many programmes
combine these types of assistance in packages for target groups. For
brevity, and to convey the basic ideas, we describe below only a few
features of the UK institutional set-up, which is quite extensive and
well established. Indeed, it is possible to criticise the proliferation of
small-business support programmes for engendering confusion among
entrepreneurs. In the UK the public-sector organisations involved in delivering these programmes include Business Links, Enterprise Agencies
(EAs), local authorities, Regional Development Agencies (RDAs), the
Department for Trade and Industry (DTI), the Department for Education and Skills (DES), Learning and Skills Councils, non-governmental
organisations (NGOs) (such as the Princes Trust), business associations
and networks and universities and colleges. Rather than provide an account of what each of these organisations do, we shall describe just a
couple of the more prominent ones.
In 1992 the British government established the Business Link (BL)
scheme. BLs purpose is to bring together various sources of support
available to entrepreneurs and small firm owners. Via a network of local
business advice centres, the (publicly funded) BL scheme aims to provide local information; marketing, training and planning support; advice;
and consultancy support for SMEs.29 Initially BL focused its support on
SMEs with high-growth potential that employed between 10 and 200
staff. A key part of the process was the role of personal business advisors,
who conducted free health checks on businesses that requested it. More
recently, however, BL has begun to work with businesses of all sizes, including start-ups. Their work is complemented by Enterprise Agencies
(EAs) (Enterprise Trusts in Scotland) and TECs. TECs are fundholders
of enterprise support and training, on which many EAs are dependent for
funding. The delivery of business services varies from agency to agency,
with considerable geographical diversity.
The Princes Trust is a form of support directed towards young people.
It provides them with cheap small loans packaged with advice, mentoring
257
258
259
260
Brock and Evans (1986) concluded that there is little evidence that regulation has disproportionately harmed small firms. Of course, this could
simply reflect the success of tiering in protecting small firms from the
worst excesses of government interference in their businesses. In recognition of the regulatory damage that governments can inadvertently inflict on small business, the US legislature passed the Regulatory Flexibility Act. This instrument forces US government agencies to undertake a
thorough analysis of the economic impact of their proposed regulations,
and to consider alternatives that are less likely to harm small firms (SBA,
2001).
10.6
Conclusion
This chapter has critically evaluated the existing state of theoretical and
empirical knowledge about the impact of government intervention on
entrepreneurship in general and the self-employed in particular. We discussed interventions to promote new start-ups by making finance easier
to obtain, via loan guarantee schemes and direct assistance to the unemployed; the theory of taxation and occupational choice when incomes in
entrepreneurship are uncertain; theory and evidence about tax evasion
and self-employment; evidence about the effects of the personal income
tax system on self-employment and occupational choice; governmentsponsored advice and assistance to entrepreneurs; and the effects of regulation. It is no easy matter to draw conclusions from such a diverse body
of work. But a few general principles and findings stand out.
First, regarding interventions designed to promote new start-ups, governments in several countries expend substantial resources on LGSs and
schemes to encourage the unemployed to become self-employed. Evaluation studies have not produced a ringing endorsement of these schemes.
While they do not appear to misallocate resources badly, there is little evidence that they improve efficiency much either. If governments are to be
persuaded to enlarge the scope and extent of these schemes, researchers
should provide more convincing evidence that small businesses generate
substantial social and economic benefits that are being impeded by some
kind of market failure.
A second general conclusion is that the rich theoretical literature on
income taxation and occupational choice presents an array of conflicting
predictions and policy recommendations. Even the class of models that
restricts attention to uniform linear income tax systems are unable to
answer unambiguously such basic questions as Will higher income tax
rates increase or decrease the equilibrium number of entrepreneurs? and
What are the effects of income tax on the welfare of entrepreneurs, and
261
262
increasing the number of winners; there is little point after all in helping
some participants to play more cunningly a zero-sum game.
N OT E S
1. For example, the US variants of the basic scheme include the Certified Lender
Program (which promises banks a three-day approval time) and the Preferred
Lender Program (under which loans can be made without prior approval by
the Small Business Administration (SBA), at the price of a smaller guarantee).
According to Smith and Stutzer (1989), about one-third of state governments
in the USA also guarantee loans, with guarantee percentages varying within
and between states. The US SBA LGS dates back to 1953 (see Rhyne, 1988,
for a review of the historical and political context). The UK Small Firms LGS
(SFLGS) dates back to 1981: see Cowling and Clay (1995) for a full background to this scheme, operational details, and an econometric model of takeup rates by entrepreneurs. Bates (1984) describes the Economic Opportunity
Loan program.
2. These include banking, real estate development and publishing in the USA;
and retailing, catering and motor vehicle maintenance in the UK. One reason
for excluding support in certain sectors is to reduce business displacement (see
below).
3. See also Smith and Stutzer (1989), who proposed a similar mechanism and
outcome.
4. In terms of figure 5.3, a LGS targeted on group b increases bs expected rate of
return schedule above in that diagram if the scheme is sufficiently generous.
But also increases, reflecting the greater overall profitability of private loans
possibly leading to redlining of the non-targeted group o, who were not
initially redlined. These perverse crowding-out effects may serve to generate
pressure for further subsidies. In Gales words: Credit subsidies create demand
for more credit subsidies (1990b, p. 190).
5. If financial markets are characterised by credit rationing, then the quality of
the rationed ventures should be high, and LGS programmes should not make
much of a loss. If they do make losses, can this be taken as evidence that
credit rationing does not exist, and that private lenders were right to reject
the ventures? Not necessarily: losses could also be caused by high programme
administrative costs (Rhyne, 1988).
6. The UKs SFLGS was amended in 1989 and 1996 for precisely this reason,
restricting loans to sectors with low displacement rates.
7. The small scale of the UKs SFLGS has prompted some commentators to
argue that the principal role of the scheme was as a temporary demonstration
effect: i.e. to demonstrate to banks profitable opportunities for unsecured
lending in the small business sector (Storey, 1994a).
8. Furthermore, Rhyne (1988) estimated that in order to cover programme costs,
each successful SBA-backed loan would have had to generate additional benefits over the lifetime of the loan of between 17 and 29 per cent above the return
necessary to stay in business.
263
9. The rationale has been two-fold. First, loan guarantees facilitate bankborrower relationships, unlike direct Federal loans; and they also reduce
undesirable competition between the SBA and banks (Rhyne, 1988). More
recent data from the SBA (2001) indicate that between 1991 and 2000 the
SBA backed a total of $95 billion in loans to small businesses.
10. Corporate taxes tend to be flat-rate taxes, whereas IT tends to be progressive, with marginal tax rates that rise with income. This raises the issue of
optimal incorporation choice by the self-employed, since high-income selfemployed individuals have a tax incentive to reclassify their earnings as corporate rather than personal (Fuest, Huber and Nielsen, 2002). According to
Gordon (1998), this tax differential has declined from high levels in the 1950s
and 1960s to very low levels at the time of writing. See Gordon (1998) for
further details and references to the literature.
11. Obviously, entrepreneurship also becomes unambiguously less attractive if
just entrepreneurs are taxed without a subsidy being given to employees and
with the tax receipts being spent on an outside good. Likewise, Kihlstrom
and Laffont (1983b) showed that a tax on wages only (with receipts spent on
an outside good) increases the number of entrepreneurs under assumption 1.
12. See Kanbur (1979), and Yuengert (1995) for affirmative evidence. Gentry
and Hubbard (2000) found the opposite result, but that reflects an unfavourable differential tax to self-employment caused by imperfect loss offsets,
that outweighs insurance or tax evasion advantages to entrepreneurship (see
also Cullen and Gordon, 2002). That is, profits are subject to a higher tax
rate than the rate against which any losses can be deducted, making risky
entrepreneurship less attractive.
13. The only paper we know of in this area is by Moresi (1998), who extended
Mirrlees classic optimal tax analysis to the realm of entrepreneurship. Moresi
studied the general properties of optimal non-linear differential taxes when
entrepreneurs have heterogeneous exogenous abilities and workers receive a
common wage. Few firm predictions emerge from the general form of this
model.
14. For Canadian evidence on intertemporal tax-shifting by the self-employed,
see Sillamaa and Veall (2001).
15. In a simplified model with labour supply choice, Robson and Wren (1999)
showed how higher marginal tax rates can decrease the self-employment rate
if gross incomes are more sensitive to labour supply in self-employment than
in paid-employment.
16. The corresponding figure for net incomes, which includes both understatement of receipts and over-statement of expenses, was 50.3 per cent.
Kesselman (1989) also reported wide industry variations in under-reporting
rates, with taxicab drivers being the most likely to under-report. According to Clotfelter (1983), self-employed income under-reporting is positively
associated with high net incomes and high marginal tax rates, though subsequent evidence by Kesselman (1989) cast doubt on these results. Joulfaian
and Rider (1996) estimated that income under-reporting is significantly negatively associated with the tax audit rate, with an elasticity of approximately
0.70.
264
(2002). Cowling and Mitchell (1997), Robson and Wren (1999), Parker
and Robson (2000) and Bruce (2002) reported insignificant or mixed
effects.
21. For example, Blau (1987) estimated that the reduction in marginal tax rates
(MRT) at the bottom of the US income distribution and the rise in MRT at
the top accounted for between about a half and two-thirds of the observed
increase in self-employment between 1973 and 1982. This was despite Blaus
puzzling finding of conflicting impacts on self-employment rates from MRT
measured at different income levels.
22. In accordance with the evidence cited earlier, there is little or no evasion in
E, so there is no need to introduce a corresponding term for E. In (10.10)
below, is treated as an unknown parameter to be estimated.
23. For a detailed summary of self-employment schemes for the unemployed in
Germany, France, the UK and Denmark, see Meager (1993, 1994).
24. The EAS was later renamed as the Business Start Up Scheme and then became part of various Single Regeneration Budgets, under more flexible terms
than those stipulated at its inception, and with a greater emphasis on targeted
support.
25. Meager (1994) suggested that grant-based schemes are superior to allowancebased schemes (such as the UKs EAS) by enabling new ventures to overcome
entry barriers in some industries, so reducing displacement effects.
26. Storey (1994a) reported that around 14 per cent of EAS entrants failed in the
first year of operation, during which the EAS subsidy was received. Taylor
(1999) cited a UK Department of Employment report that two-thirds of
individuals completing their first year of the EAS were still in business two
years later. These are higher survival rates than Taylor found for British selfemployed workers overall.
27. In particular, all non-proprietor jobs were created by 20 per cent of surviving
firms (Bendick and Egan, 1987). More than 60 per cent of the jobs created
in surviving firms after three years under the EAS were in 4 per cent of the
businesses originally created (Storey, 1994a).
28. Consistent with this, time-series econometric evidence from Parker (1996)
suggests that the EAS increased UK self-employment rates only modestly
265
and in the short run only. See Meager (1993, 1994) for time-series regression
results for Germany.
29. BL was reformed during 20001 by the UK government to be part of the
Small Business Service, in order to replicate aspects of the US SBA. Chiefly,
this involves adding a new role for BL as a voice for SMEs.
30. See also Sandford (1981), who estimated that compliance costs related to
sales taxes were forty times higher as a proportion of turnover for UK firms
with turnover of less than 10,000 than for firms with a turnover of over 1m.
31. More generally, tiering may occur in any of the major aspects of a regulatory
program: in the substantive requirements; in reporting and record keeping requirements; or in enforcement and monitoring efforts. Tiering may entail less
frequent inspections, lighter fines for non-compliance, exemptions, waivers,
reduced requirements, or simpler reporting requirements for certain types of
firms (Brock and Evans, 1986, p. 74).
11
Conclusions
11.1
Summary
Self-employment and entrepreneurship are important economic phenomena. Self-employment is widespread throughout the world and small
firms are the principal vehicles for the organisation of production. Far
from self-employment being an occupation in irrevocable decline, the
evidence outlined in chapter 1 showed that numbers of self-employed
people are holding up strongly in many countries. While it is true that declining transportation and communications costs, more capital-intensive
methods of production, and industry consolidation do not favour many
small-scale enterprises (White, 1984), these changes may be less pervasive in many service industries. And some of these changes might be
amenable to exploitation by entrepreneurs who can discern in them profitable opportunities.
Our review of the theories and evidence about entrepreneurship in
chapters 2 and 3 revealed that economists regard entrepreneurial ability
and willingness to take risks as key factors determining who becomes an
entrepreneur. While more work remains to be done on estimating structural models to identify the empirical importance of these factors, we now
know a fair amount about the specific characteristics of entrepreneurs.
They often come from families with a tradition of self-employment or
business ownership; they are on average older, reasonably well educated
and more likely to be married, and are generally over-optimistic about
their prospects of success. On the balance of evidence, non-pecuniary
factors appear to be more important than pecuniary factors in explaining
why people choose to be entrepreneurs.
Self-employed people in most OECD countries tend to be predominantly white, male and middle aged. This is changing, however.
Increasing numbers of females are turning to self-employment, while
many ethnic minority groups have participation rates in self-employment
that are both higher and growing more rapidly than those of indigenous
groups. Although it is still unclear why females and members of some
266
Conclusions
267
ethnic groups are under-represented in self-employment, the research reviewed in chapter 4 found little evidence of discrimination against them,
either in the product or the capital markets. An ongoing puzzle is why
black Britons and Americans have such low self-employment rates, in
contrast to Asians in these two countries. There is clearly a need for
further research on these topics.
In principle, limited access to finance might be one cause of low black
self-employment rates in the UK and the USA, though the evidence here
is not clear-cut. In fact, it is not well established that there is a shortage
of debt finance for any new start-ups. Just because banks deny credit to
some loan applicants does not necessarily mean that they ration credit.
Even if bank loans are unavailable, other sources of credit often exist, such
as personal and family finance, trade credit, franchising, and sometimes
even equity finance. The scale and potential contribution of these sources
of finance were reviewed in chapter 6. In the case of equity finance, it
seems that the low anticipated returns and high risk of proposed ventures,
rather than unavailability of funds, explains the limited use of this source
of finance in practice.
The theoretical literature reviewed in chapters 5 and 6 is unable to
answer definitively the question about whether finance is rationed, and
whether there is too little or too much investment by entrepreneurs. Consequently, governments should probably not take any of the academic
policy recommendations emanating from this literature too seriously.
The most pressing need is for direct evidence about the nature of any
inefficiency in the market for start-up finance. Chapter 7 reviewed the
evidence about borrowing constraints, including studies finding a positive relationship between personal wealth and windfalls, and participation
and survival in self-employment. We argued that such correlations do not
constitute evidence of borrowing constraints, and concluded that direct
evidence from bank loan rejections suggest that credit rationing, if it exists
at all, can be only very limited in practice. On the other hand, the perception of borrowing constraints among entrepreneurs might discourage
them from applying for funds from banks and other lenders. It is unclear
how prevalent this discouraged borrower syndrome is.
In the light of these findings, it is therefore interesting that governments
in several major economies continue to back private bank loans to new
ventures. The reason is presumably a joint belief in credit rationing and
the importance of entrepreneurship, perhaps because of its job creating
promise. In fact, as shown in chapter 8, although small firms appear to
create a disproportionate number of new jobs on net in the OECD, most
self-employed people in most countries do not hire any employees. Instead, they rely on supplying long work hours of their own. A puzzle is
268
why the self-employed work relatively long hours for relatively low returns.
One reason might be greater income variability in self-employment, combined with non-pecuniary factors, leading self-employees to self-insure
by working harder. Self-employed jobs can be pleasurable in their own
right, especially if they involve the excitement of successfully establishing
and maintaining ones own enterprise. An unwillingness to see ones life
work disappear might also account for why so many self-employed people continue to work well into their seventies and sometimes even their
eighties.
Having launched a new enterprise, what happens to it next? Chapter 9
showed that most new ventures are small and remain so, if they survive
at all. Survivors tend to have higher and more variable growth rates, and
tend to be run by experienced owners located in areas of low unemployment. Only very few new enterprises grow sufficiently to eventually
become large firms. Models of entrepreneurial learning appear to explain
most of these stylised facts well. We suggest that promotion of sustainable entrepreneurship might be better served by trying to forestall exit,
rather than encouraging entry. But government efforts to pick winners
are unlikely to be successful; and it is unclear what specific government
policies are best suited to boost survival rates. This will no doubt be an
ongoing topic of interest in future entrepreneurship research.
Several specific forms of government intervention designed to promote
entrepreneurship were analysed in chapter 10. Because of the policy importance of this issue, we devote the remainder of this chapter to it.
11.2
Conclusions
269
less entrepreneurship than is socially desirable. Note by the way that the
recognition of scope for welfare-improving government intervention does
not automatically justify such intervention. Intervention invariably incurs
direct costs, in addition to the opportunity cost of public funds; and bureaucrats cannot always be trusted to allocate public money wisely. Our
evaluation in chapter 10 of loan guarantee schemes and income support
schemes targeted at the unemployed concluded that these schemes are
relatively small in scope and generate benefits that do not obviously outweigh their costs.
It is quite understandable that government policies towards entrepreneurship err on the side of modesty rather than extravagance. Governments
invariably face conflicting aspirations and objectives. They want to target
resources to achieve focus but are unable to pick winners; they want to
make assistance selective to control budgetary costs but wish also to both
remain inclusive and avoid spreading resources too thinly; and they want
policies to make a big impact for political reasons while minimising costs
and programme deadweight losses. These trade-offs are deep-rooted and
probably inescapable.
We believe that there are several major problems with the way that
governments around the world currently conduct policy with regard to
entrepreneurship. What follows are personal views based on a distillation
of the literature encompassed in this book.
First, it is unclear why governments wish to promote entrepreneurship
in the first place. One is led to suspect that their involvement is motivated
by ideology rather than by a pragmatic evaluation of the costs and benefits. Many governments apparently believe that entrepreneurs create jobs
and that higher levels of enterprise promote economic growth. There is
certainly no shortage of small-business practitioners and academics that
have vested interests in encouraging these beliefs, despite the limited evidence we have found in this book to support them (see in particular
chapters 8 and 9). It rarely seems to be acknowledged in these circles
that entrepreneurial ventures might also possess drawbacks. For example, small firms do less training and pay lower wages than large firms, so
a policy of encouraging small firms at the expense of large ones might
actually damage the national skill base.
Second, there has been an explosion of policy initiatives in many countries, that now resemble a patchwork quilt of complexity and idiosyncracy (Curran, 2000, p. 36).1 This has generated confusion among the
intended beneficiaries, which might help explain why take-up rates for
information-based support services have been so low, rarely exceeding
10 per cent even for programmes like training support that are open to
all small firms. Another problem is that a plethora of policy initiatives
270
Conclusions
271
References
References
273
Amit, R., E. Muller and I. Cockburn (1995). Opportunity costs and entrepreneurial activity, Journal of Business Venturing, 10, pp. 95106
Appelbaum, E. and E. Katz (1986). Measures of risk aversion and comparative
statics of industry equilibrium, American Economic Review, 76, pp. 52429
Appelbaum, E. and C. Lim (1982). Long-run industry equilibrium with uncertainty, Economics Letters, 9, pp. 13945
Arabsheibani, G., D. de Meza, J. Maloney and B. Pearson (2000). And a vision
appeared unto them of a great profit: evidence of self-deception among the
self-employed, Economics Letters, 67, pp. 3541
Armendariz de Aghion, B. (1999). On the design of a credit agreement with peer
monitoring, Journal of Development Economics, 60, pp. 79104
Armendariz de Aghion, B. and C. Gollier (2000). Peer group formation in an
adverse selection model, Economic Journal, 110, pp. 63243
Armington, C. and M. Odle (1982). Small business: how many jobs?, Brookings
Review, Winter, 1417
Aronson, R. L. (1991). Self Employment: A Labour Market Perspective, Ithaca, NY,
ILR Press
Atrostic, B. K. (1982). The demand for leisure and non-pecuniary job characteristics, American Economic Review, 72, pp. 42840
Audretsch, D. B. (1991). New-firm survival and the technological regime, Review
of Economics and Statistics, 73, pp. 44150
Audretsch, D. B. (1995). Innovation and Industry Evolution, MIT Press,
Cambridge MA
Audretsch, D. B. and Z. J. Acs (1994). New firm start-ups, technology and
macroeconomic fluctuations, Small Business Economics, 6, pp. 43949
Audretsch, D. B. and T. Mahmood (1994). The rate of hazard confronting new
firms and plants in US manufacturing, Review of Industrial Organisation, 9,
pp. 4156
(1995). New firm survival: new results using a hazard function, Review of Economics and Statistics, 77, pp. 97103
Audretsch, D. B. and M. Vivarelli (1997). Determinants of new firm start-ups in
Italy, Empirica, 23, pp. 91105
Baker, P. (1993). Taxpayer compliance for the self-employed: estimates from
household spending data, Working Paper, W93/14, London, Institute for
Fiscal Studies
Baldwin, J. and G. Picot (1995). Employment generation by small producers
in the Canadian manufacturing sector, Small Business Economics, 7,
pp. 31731
Baltensperger, E. (1978). Credit rationing: issues and questions, Journal of Money,
Credit, and Banking, 10, pp. 17083
Banerjee, A. V., T. Besley and T. W. Guinnane (1994). Thy neighbours keeper:
the design of a credit co-operative with theory and a test, Quarterly Journal
of Economics, 109, pp. 491515
Banerjee, A. V. and A. F. Newman (1993). Occupational choice and the process
of development, Journal of Political Economy, 101, pp. 27498
Bank of England (1993). Bank Lending to Smaller Businesses, London, Bank of
England
274
References
(1999). The Financing of Ethnic Minority Firms in the United Kingdom, London,
Bank of England
(2001). Finance for Small Firms: Eighth Report, London, Bank of England
Bannock, G. (1981). The Economics of Small Firms: Return from the Wilderness,
Oxford, Basil Blackwell
Bannock, G. and A. Peacock (1989). Government and Small Business, London,
Paul Chapman Publishing
Barkham, R., M. Hart and E. Hanvey (1996). Growth in small manufacturing
firms: an empirical analysis, in R. Blackburn and P. Jennings (eds.), Small
Firms Contribution to Economic Regeneration, London, Paul Chapman Publishing, pp. 11225
Barreto, H. (1989). The Entrepreneur in Microeconomic Theory: Disappearance and
Explanation, London, Routledge
Barro, R. J. (1976). The loan market, collateral, and rates of interest, Journal of
Money, Credit, and Banking, 8, pp. 43956
Barzel, Y. (1987). The entrepreneurs reward for self-policing, Economic Inquiry,
25, pp. 10316
Basu, A. (1998). An exploration of entrepreneurial activity among Asian small
businesses in Britain, Small Business Economics, 10, pp. 31326
Basu, A. and S. C. Parker (2001). Family finance and new business start-ups,
Oxford Bulletin of Economics and Statistics, 63, pp. 33358
Bates, T. (1984). A review of the Small Business Administrations major loan
programs, in P. M. Horvitz and R. R. Pettit (eds.), Small Business Finance:
Sources of Financing for Small Business, Part B, Greenwich, CT, JAI Press,
pp. 21139
(1985). Entrepreneur human capital endowments and minority business viability, Journal of Human Resources, 20, pp. 54054
(1990). Entrepreneur human capital inputs and small business longevity,
Review of Economics and Statistics, 72, pp. 5519
(1991). Commercial bank finance in white and black owned small business
start ups, Quarterly Review of Economics and Business, 31, pp. 6480
(1994). Firms started as franchises have lower survival rates than independent
small business startups, Discussion Paper, Center for Economic Studies, US
Census Bureau, Washington DC
(1995). Self-employment entry across industry groups, Journal of Business Venturing, 10, pp. 14356
(1997). Race, Self-Employment and Upward Mobility: An Illusive American
Dream, Baltimore, Johns Hopkins University Press
(1998). Survival patterns among newcomers to franchising, Journal of Business
Venturing, 13, pp. 11330
(1999). Exiting self-employment: an analysis of Asian immigrant-owned small
businesses, Small Business Economics, 13, pp. 17183
Bates, T. and W. D. Bradford (1992). Factors affecting new firm success and
their use in venture capital financing, Journal of Small Business Finance, 2,
pp. 2338
Baumol, W. J. (1968). Entrepreneurship in economic theory, American Economic
Review, Papers and Proceedings, 58, pp. 6471
References
275
276
References
Besley, T. (1995). Nonmarket institutions for credit and risk sharing in lowincome countries, Journal of Economic Perspectives, 9, pp. 11527
Besley, T., S. Coate and G. Loury (1993). The economics of rotating savings and
credit associations, American Economic Review, 83, pp. 792810
Bester, H. (1985a). Screening vs. rationing in credit markets with imperfect information, American Economic Review, 75, pp. 85055
(1985b). The level of investment in credit markets with imperfect information,
Journal of Institutional and Theoretical Economics, 141, pp. 50315
(1987). The role of collateral in credit markets with imperfect information,
European Economic Review, 31, pp. 88799
(1994). The role of collateral in a model of debt renegotiation, Journal of Money,
Credit, and Banking, 26, pp. 7286
Biais, B. and C. Gollier (1997). Trade credit and credit rationing, Review of
Financial Studies, 10, pp. 90337
Binks, M. and A. Jennings (1986). Small firms as a source of economic rejuvenation, in J. Curran et al. (eds.), The Survival of the Small Firm, 1, Aldershot,
Gower, pp. 1937
Binks, M. and P. Vale (1990). Entrepreneurship and Economic Change, London,
McGraw-Hill
Birch, D. L. (1979). The Job Generation Process, MIT Programme on Neighbourhood and Regional Change, Cambridge, MA, MIT
Birch, D. L., A. Haggerty and W. Parsons (1997). Whos Creating Jobs?,
Cambridge, MA, Cognetics Inc.,
Black, J. and D. de Meza (1990). On giving credit where it is due, Discussion
Paper, 9008, Department of Economics, University of Exeter
(1997). Everyone may benefit from subsidising entry to risky occupations,
Journal of Public Economics, 66, pp. 40924
Black, J., D. de Meza and D. Jeffreys (1996). House prices, the supply of collateral
and the enterprise economy, Economic Journal, 106, pp. 6075
Blackburn, R. A. (1992). Small firms and subcontracting: what is it and where?,
in P. Leighton and A. Felstead (eds.), The New Entrepreneurs: Self-Employment
and Small Business in Europe, London, Kogan Page, pp. 30521
Blanchflower, D. G. (1997). The attitudinal legacy of communist labour relations,
Industrial and Labor Relations Review, 50, pp. 43859
(2000). Self-employment in OECD countries, Labour Economics, 7, pp. 471
505
Blanchflower, D. G. and R. B. Freeman (1994). Did the Thatcher reforms change
British labour market performance?, in R. Barrell (ed.), The UK Labour
Market, Cambridge, Cambridge University Press, pp. 5192
Blanchflower, D. G. and B. D. Meyer (1994). A longitudinal analysis of the young
self-employed in Australia and the United States, Small Business Economics,
6, pp. 119
Blanchflower, D. G. and A. Oswald (1990). Self-employment and the enterprise
culture, in R. Jowell, S. Witherspoon and L. Brook (eds.), British Social
Attitudes: The 1990 Report, London, Gower
(1998). What makes an entrepreneur?, Journal of Labour Economics, 16,
pp. 2660
References
277
278
References
References
279
Bruderl,
J. and P. Preisendorfer
J., P. Preisendorfer
280
References
References
281
282
References
Cowling, M. and M. Taylor (2001). Entrepreneurial women and men: two different species?, Small Business Economics, 16, pp. 16775
Craggs, P. and P. Jones (1998). UK results from the Community Innovation
Survey, Economic Trends, 539, London, HMSO
Cramer, J. S., J. Hartog, N. Jonker and C. M. van Praag (2002). Low risk aversion
encourages the choice for entrepreneurship: an empirical test of a truism,
Journal of Economic Behaviour and Organization, 48, pp. 2936
Creedy, J. and P. S. Johnson (1983). Firm formation in manufacturing industry,
Applied Economics, 15, pp. 17785
Cressy, R. C. (1993). The Startup Tracking Exercise: Third Year Report, National
Westminster Bank of Great Britain, November
(1996). Are business start-ups debt-rationed?, Economic Journal, 106,
pp. 125370
(1999). Small business failure: failure to fund or failure to learn?, in Z. J. Acs,
B. Carlsson and C. Karlsson (eds.), Entrepreneurship, Small and Medium Sized
Enterprises and the Macroeconomy, Cambridge, Cambridge University Press,
pp. 16185
(2000). Credit rationing or entrepreneurial risk aversion? An alternative explanation for the Evans and Jovanovic finding, Economics Letters, 66, pp. 235
40
Cressy, R. C. and O. Tovanen (1997). Is there adverse selection in the credit
market? Warwick Business School, mimeo
Cromie, S. (1987). Motivations of aspiring male and female entrepreneurs, Journal of Occupational Behaviour, 8, pp. 25161
Cukierman, A. (1978). The horizontal integration of the banking firm: credit
rationing and monetary policy, Review of Economic Studies, 45, pp. 165
78
Cullen, J. B. and R. H. Gordon (2002). Taxes and entrepreneurial activity: theory
and evidence for the US, NBER Working Paper, 9015, National Bureau of
Economic Research
Curran, J. (2000). What is small business policy in the UK for? Evaluation
and assessing small business policy, International Small Business Journal, 18,
pp. 3650
Curran, J., and R. A. Blackburn (1993). Ethnic Enterprise and the High Street
Bank, Kingston University (UK), Small Business Research Centre
(2001). Older people and the enterprise society: age and self-employment
propensities, Work Employment and Society, 15, pp. 889902
Curran, J. and R. Burrows (1989). National profiles of the self-employed, Employment Gazette, 97, pp. 37685
(eds.) (1991). Paths of Enterprise, London, Routledge
Curran, J., R. Burrows and M. Evandrou (1987). Small Business Owners and
the Self-Employed in Britain: An Analysis of the GHS Data, London, Small
Business Research Trust
Daly, M. (1991). The 1980s a decade of growth in enterprise, Employment
Gazette, 99, pp. 10934
et al. (1991). Job creation 19871989: the contributions of large and small
firms, Employment Gazette, 99, pp. 10934
References
283
Dant, R. P. (1995). Motivation for franchising: rhetoric versus reality, International Small Business Journal, 14, pp. 1032
Davidsson, P., L. Lindmark and C. Olofsson (1998). The extent of overestimation of small firm job creation an empirical examination of the
regression bias, Small Business Economics, 11, pp. 87100
Davis, S. J. and J. C. Haltiwanger (1992). Gross job creation, gross job destruction
and employment reallocation, Quarterly Journal of Economics, 107, pp. 819
63
Davis, S. J., J. C. Haltiwanger and S. Schuh (1996a). Job Creation and Destruction,
Cambridge, MA, MIT Press
(1996b). Small business and job creation: dissecting the myth and reassessing
the facts, Small Business Economics, 8, pp. 297315
de Aghion, B. A. and J. Morduch (2000). Microfinance beyond group lending,
Economics of Transition, 8, pp. 40120
de Meza, D. (2002). Overlending? Economic Journal, 112, pp. F17F31
de Meza, D. and C. Southey (1996). The borrowers curse: optimism, finance
and entrepreneurship, Economic Journal, 106, pp. 37586
de Meza, D. and D. C. Webb (1987). Too much investment: a problem of asymmetric information, Quarterly Journal of Economics, 102, pp. 28192
(1988). Credit market efficiency and tax policy in the presence of screening
costs, Journal of Public Economics, 36, pp. 122
(1989). The role of interest rate taxes in credit markets with divisible projects
and asymmetric information, Journal of Public Economics, 39, pp. 3344
(1990). Risk, adverse selection and capital market failure, Economic Journal,
100, pp. 20614
(1992). Efficient credit rationing, European Economic Review, 36, pp. 127790
(1999). Wealth, enterprise and credit policy, Economic Journal, 109, pp. 153
63
(2000). Does credit rationing imply insufficient lending?, Journal of Public Economics, 78, pp. 21534
Deakins, D. (1999). Entrepreneurship and Small Firms, 2nd edn., London,
McGraw-Hill
Denison, E. F. (1967). Why Growth Rates Differ: Postwar Experience in Nine Western
Countries, Washington, DC, Broowings Institution
Dennis, W. J. (1996). Self-employment: when nothing else is available?, Journal
of Labour Research, 17, pp. 64561
(DTI) (1999). The Small Business Service: A Public Consultation Document,
London, Department of Trade and Industry
Devine, T. J. (1994a). Characteristics of self-employed women in the United
States, Monthly Labor Review, 117, pp. 2034
(1994b). Changes in wage-and-salary returns to skill and the recent rise in
female self-employment, American Economic Review, Papers and Proceedings,
84, pp. 108113
(1995). CPS earnings data for the self-employed: words of caution for use and
interpretation, Journal of Economic and Social Measurement, 21, pp. 21351
Devine, T. J. and T. Mlakar (1993). Inter-industry variations in the determinants
of self-employment, Pennsylvania State University, mimeo
284
References
References
285
286
References
Fried, J. and P. Howitt (1980). Credit rationing and implicit contract theory,
Journal of Money, Credit, and Banking, 12, pp. 47187
Friedman, M. (1953). The Methodology of Positive Economics, Chicago, University
of Chicago Press
Fuchs, V. R. (1982). Self-employment and labour-force participation of older
males, Journal of Human Resources, 17, pp. 33957
Fuest, C., B. Huber and S. B. Nielsen (2002). Why is the corporation tax lower
than the personal tax rate? The role of small firms, Journal of Public Economics,
87, pp. 15774
Fujii, E. T. and C. B. Hawley (1991). Empirical aspects of self-employment,
Economics Letters, 36, pp. 3239
Gale, D. and M. Hellwig (1985). Incentive-compatible debt contracts: the oneperiod problem, Review of Economic Studies, 52, pp. 64763
Gale, W. G. (1990a). Collateral, rationing, and government intervention in credit
markets, in R. Glenn Hubbard (eds.), Asymmetric Information, Corporate Finance, and Investment Chicago, University of Chicago Press, pp. 4361
(1990b). Federal lending and the market for credit, Journal of Public Economics,
42, pp. 17793
Gaston, R. J. (1989). The scale of informal capital markets, Small Business Economics, 1, pp. 22330
Gavron, R., M. Cowling, G. Holtham and A. Westall (1998). The Entrepreneurial
Society, London, IPPR
Gentry, W. M. and R. G. Hubbard (2000). Tax policy and entrepreneurial entry,
American Economic Review, 90, pp. 28387
(2001). Entrepreneurship and household saving, NBER Working Paper, 7894,
National Bureau of Economic Research
Georgellis, Y. and H. J. Wall (2000). What makes a region entrepreneurial?
Evidence from Britain, Annals of Regional Science, 34, pp. 385403
Geroski, P. A. (1995). What do we know about entry?, International Journal of
Industrial Organization, 13, pp. 45056
Geroski, P. A. and R. Pomroy (1990). Innovation and the evolution of market
structure, Journal of Industrial Economics, 38, pp. 299314
Gersovitz, M. (1983). Savings and nutrition at low incomes, Journal of Political
Economy, 91, pp. 84155
References
287
Ghatak, M. (2000). Screening by the company you keep: joint liability lending
and the peer selection effect, Economic Journal, 110, pp. 60131
Ghatak, M. and T. W. Guinnane (1999). The economics of lending with joint
liability: theory and practice, Journal of Development Economics, 60, pp. 195
228
Gibrat, R. (1931). Les Inegalites Economique, Paris, Siley
Gifford, S. (1998). The Allocation of Limited Entrepreneurial Attention, Boston,
MA, Kluwer
Gill, A. M. (1988). Choice of employment status and the wages of employees and
the self-employed: some further evidence, Journal of Applied Econometrics, 3,
pp. 22934
Gimeno, J., T. B. Folta, A. C. Cooper and C. Y. Woo (1997). Survival of the
fittest? Entrepreneurial human capital and the persistence of underperforming firms, Administrative Science Quarterly, 42, pp. 75083
Gladstone, R. and J. Lane-Lee (1995). The operation of the insolvency system in
the UK. Some implications for entrepreneurialism, Small Business Economics,
7, pp. 5567
Glaeser, E. L., D. Laibson and B. Sacerdote (2000). The economic approach to
social capital?, NBER Working Paper, 7728, National Bureau of Economic
Research
Goedhuys, M. and L. Sleuwaegen (2000). Entrepreneurship and growth of
entrepreneurial firms in Cote
dIvoire, Journal of Development Studies, 36,
pp. 12245
Goldfeld, S. M. (1966). Commercial Bank Behaviour and Economic Activity: A
Structural Study of Monetary Policy in the Post War United States, Amsterdam
North-Holland
Gomez, R. and E. Santor (2001). Membership has its privileges: the effect of
social capital and neighbourhood characteristics on the earnings of microfinance borrowers, Canadian Journal of Economics, 34, pp. 94366
Gompers, P. A. and J. Lerner (1998). What drives venture capital fundraising?,
Brookings Papers on Economic Activity, pp. 14992
Goodman, A. and S. Webb (1994). For richer, for poorer: the changing distribution of income in the UK, 196191, Fiscal Studies, 15, pp. 2962
Gordon, R. H. (1998). Can high personal tax rates encourage entrepreneurial
activity?, IMF Staff Papers, 45, pp. 4980
Gordus, J. P., P. Jarley and L. A. Ferman (1981). Plant Closings and Economic Dislocation, Kalamazoo, MI, W. E. Upjohn Institute for Employment Research
Gray, J. A. and Y. Wu (1995). On equilibrium credit rationing and interest rates,
Journal of Macroeconomics, 17, pp. 40520
Greenwald, B., J. E. Stiglitz and A. Weiss (1984). Informational imperfections
in the capital market and macroeconomic fluctuations, American Economic
Review, 74, pp. 1949
Gromb, D. and D. Scharfstein (2002). Entrepreneurship in equilibrium, NBER
Working Paper, 9001, National Bureau of Economic Research
Grossman, G. M. (1984). International trade, foreign investment, and the
formation of the entrepreneurial class, American Economic Review, 74,
pp. 60514
288
References
Gruber, J. and J. Poterba (1994). Tax incentives and the decision to purchase
health insurance: evidence from the self-employed, Quarterly Journal of Economics, 109, pp. 70133
Guinnane, T. (1994). A failed institutional transplant: Raiffeisens credit cooperatives in Ireland, 18941914, Explorations in Economic History, 31,
pp. 3861
Guiso, L. (1998). High-tech firms and credit rationing, Journal of Economic Behaviour and Organization, 35, pp. 3959
Haber, S. E., E. J. Lamas and J. Lichtenstein (1987). On their own: the selfemployed and others in private business, Monthly Labor Review, 110, pp. 17
23
Hakim, C. (1988). Self-employment in Britain: recent trends and current issues,
Work, Employment and Society, 2, pp. 42150
(1989a). New recruits to self-employment in the 1980s, Employment Gazette,
97, pp. 28697
(1989b). Workforce restructuring, social insurance coverage and the black
economy, Journal of Social Policy, 18, pp. 471503
Hall, B. H. (1987). The relationship between firm size and firm growth in the
US manufacturing sector, Journal of Industrial Economics, 35, pp. 583606
Hall, G. (1992). Reasons for insolvency amongst small firms a review and fresh
evidence, Small Business Economics, 4, pp. 23750
Hamermesh, D. S. (1993). Labour Demand, Princeton, Princeton University
Hamilton, B. H. (2000). Does entrepreneurship pay? An empirical analysis of the
returns to self-employment, Journal of Political Economy, 108, pp. 60431
Hamilton, R. T. (1989). Unemployment and business formation rates: reconciling time series and cross-section evidence, Environment and Planning C, 21,
pp. 24955
Harhoff, D. and T. Korting
References
289
290
References
References
291
292
References
References
293
294
References
Kuhn, P. J. and H. J. Schuetze (2001). Self-employment dynamics and selfemployment trends: a study of Canadian men and women, 19821998,
Canadian Journal of Economics, 34, pp. 76084
Kuznets, S. (1966). Modern Economic Growth: Rate Structure and Spread, New
Haven, CT, Yale University Press
Laband, D. N. and B. F. Lentz (1983). Like father, like son: toward an economic
theory of occupational following, Southern Economic Journal, 50, pp. 474
93
Laferr`ere, A. and P. McEntee (1995). Self-employment and intergenerational
transfers of physical and human capital: an empirical analysis of French
data, Economic and Social Review, 27, pp. 4354
Laffont, J.-J. and T. NGuessan (2000). Group lending with adverse selection,
European Economic Review, 44, pp. 77384
Lazear, E. P. (2002). Entrepreneurship, NBER Working Paper, 9109, National
Bureau of Economic Research
Lazear, E. P. and R. L. Moore (1984). Incentives, productivity, and labour contracts, Quarterly Journal of Economics, 99, pp. 27596
Le, A. T. (1999). Empirical studies of self-employment, Journal of Economic Surveys, 13, pp. 381416
(2000). The determinants of immigrant self-employment in Australia, International Migration Review, 34, pp. 183214
Lebergott, S. (1964). Factor shares in the long term: some theoretical and statistical aspects, in The behaviour of income shares: selected theoretical and
empirical issues, NBER Studies in Income and Wealth, 27, Princeton
Lee, M. A. and M. S. Rendall (2001). Self-employment disadvantage in the
working lives of blacks and females, Population Research and Policy Review,
20, pp. 291320
Lee, R. M. (1985). The entry to self-employment of redundant steelworkers,
Industrial Relations Journal, 16, pp. 429
Leeth, J. D. and J. A. Scott (1989). The incidence of secured debt evidence
from the small business community, Journal of Financial and Quantitative
Analysis, 24, pp. 37994
Leff, N. H. (1979). Entrepreneurship and economic development: the problem
revisited, Journal of Economic Literature, 17, pp. 4664
Leibenstein, H. (1968). Entrepreneurship and development, American Economic
Review, 58, pp. 7283
Leighton, P. (1982). Employment contracts: a choice of relationships, Employment
Gazette, 90, pp. 43339
(1983). Employment and self-employment: some problems of law and practice,
Employment Gazette, 91, pp. 197203
Leland, H. E. and D. H. Pyle (1977). Informational asymmetries, financial structure and financial intermediation, Journal of Finance, 32, pp. 37187
Lentz, B. F. and D. N. Laband (1990). Entrepreneurial success and occupational
inheritance among proprietors, Canadian Journal of Economics, 23, pp. 563
79
Leonard, J. S. (1986). On the size distribution of employment and establishments,
NBER Working Paper, 1951, National Bureau of Economic Research
References
295
296
References
MacDonald R. and F. Coffield (1991). Risky Business? Youth and the Enterprise
Culture, London, Falmer Press
MacMillan, I. C. (1986). To really learn about entrepreneurship, lets study habitual entrepreneurs, Journal of Business Venturing, 1, pp. 2413
Macpherson, D. A. (1988). Self-employment and married women, Economics
Letters, 28, pp. 2814
Maddala, G. S. (1983). Limited-Dependent and Qualitative Variables in Econometrics, Cambridge, Cambridge University Press
Maddison, A. (1991). Dynamic Forces in Capital Development, Oxford, Oxford
University Press
Manove, M. (2000). Entrepreneurs, optimism and the competitive edge, Boston
University, Mimeo
Manser, M. E. and G. Picot (2000). The role of self-employment in US and
Canadian job growth, Monthly Labor Review, 123, pp. 1025
Marsh, A., P. Heady and J. Matheson (1981). Labour Mobility in the Construction
Industry, London, HMSO
Marshall, A. (1930). Principles of Economics, London, Macmillan
Marshall, J. N., N. Alderman, C. Wong and A. Thwaites (1993). The impact
of government-assisted management training and development on small
and medium-sized enterprises in Britain, Environment and Planning C, 11,
pp. 33148
Mason, C. M. and R. T. Harrison (1994). Informal venture capital in the UK,
in A. Hughes and D. J. Storey (eds.), Finance and the Small Firm, London,
Routledge, pp. 64111
(2000). The size of the informal venture capital market in the United Kingdom,
Small Business Economics, 15, pp. 13748
Mata, J. (1994). Firm growth during infancy, Small Business Economics, 6, pp. 27
39
Mata, J. and P. Portugal (1994). Life duration of new firms, Journal of Industrial
Economics, 42, pp. 22745
Mata, J., P. Portugal and P. Guimaraes (1995). The survival of new plants: startup conditions and post-entry evolution, International Journal of Industrial
Organization, 13, pp. 45981
Mattesini, F. (1990). Screening in the credit market, European Journal of Political
Economy, 6, pp. 122
Maxim, P. S. (1992). Immigrants, visible minorities, and self-employment,
Demography 29, pp. 18198
Mayer, A. (1975). The lower middle class as historical problem, Journal of Modern
History, 47, pp. 40936
Mazumdar, D. (1981). The Urban Labour Market and Income Distribution A
Study of Malaysia, New York, Oxford University Press
McClelland, D. C. (1961). The Achieving Society, Princeton, Van Nostrand
McKernan, S. M. (2002). The impact of microcredit programs on selfemployment profits: do noncredit program aspects matter?, Review of Economics and Statistics, 84, pp. 93115
Meager, N. (1992a). Does unemployment lead to self-employment?, Small Business Economics, 4, pp. 87103
References
297
(1992b). The characteristics of the self-employed: some Anglo-German comparisons, in P. Leighton and A. Felstead (eds.), The New Entrepreneurs:
Self-employment and Small Business in Europe, London, Kogan Page, pp. 69
99
(1993). From unemployment to self-employment in the European Community, in F. Chittenden, et al. (eds.), Small Firms: Recession and Recovery,
London, Paul Chapman Publishing, pp. 2753
(1994). Self-employment schemes for the unemployed in the European Community, in G. Schmid (ed.), Labour Market Institutions in Europe, New York,
M. E. Sharpe, pp. 183242
Meager, N., G. Court and J. Moralee (1994). Self-Employment and the Distribution
of Income, Brighton, The Institute for Manpower Studies
(1996). Self-employment and the distribution of income, in J. Hills (ed.), New
Inequalities, Cambridge, Cambridge University Press
Meredith, G. G., R. E. Nelson and P. A. Neck (1982). The Practice of Entrepreneurship, Geneva, ILO
Metcalf, H., T. Modood and S. Virdee (1996). Asian Self-Employment: The Interaction of Culture and Economics, London, Policy Studies Institute
Meyer, B. (1990). Why are there so few black entrepreneurs?, NBER Working
Paper, 3537, National Bureau of Economic Research
Michelacchi, C. (2003). Low returns in R&D due to the lack of entrepreneurial
skills, Economic Journal, 113, pp. 20725
Milde, H. and J. G. Riley (1988). Signaling in credit markets, Quarterly Journal
of Economics, 103, pp. 10129
Miller, R. A. (1984). Job matching and occupational choice, Journal of Political
Economy, 92, pp. 10861120
Moore, B. (1994). Financial constraints to the growth and development of small
high technology firms, in A. Hughes and D. Storey (eds.), Finance and the
Small Firm, London, Routledge, pp. 11244
Moore, C. S. and R. E. Mueller (2002). The transition from paid to selfemployment in Canada: the importance of push factors, Applied Economics,
34, pp. 791801
Moore, R. L. (1983a). Self-employment and the incidence of the payroll tax,
National Tax Journal, 36, pp. 491501
(1983b). Employer discrimination: evidence from self-employed workers, Review of Economics and Statistics, 65, pp. 496501
Moralee, L. (1998). Self-employment in the 1990s, Labour Market Trends, 106,
pp. 12130
Morduch, J. (1999). The microfinance promise, Journal of Economic Literature,
37, pp. 15691614
Moresi, S. (1998). Optimal taxation and firm formation: a model of asymmetric
information, European Economic Review, 42, pp. 152551
Morgan, K. (1997). The learning region: institutions, innovation and regional
renewal, Regional Studies, 31, pp. 491503
Moskowitz, T. J. and A. Vissing-Jrgensen (2002). The returns to entrepreneurial
investment: a private equity premium puzzle?, American Economic Review, 92,
pp. 74578
298
References
Myers, S. C. and N. S. Majluf (1984). Corporate financing and investment decisions when firms have information that investors do not have, Journal of
Financial Economics, 13, pp. 187221
Myrdal, G. (1944). An American Dilemna: The Negro Problem and Modern Democracy, New York, Harper
Nafziger, E. W. and D. Terrell (1996). Entrepreneurial human capital and
the long run survival of firms in India, World Development, 24, pp. 689
96
National Economic Research Associates (NERA) (1990). An Evaluation of the
Loan Guarantee Scheme, Department of Employment Research Paper, 74,
London, HMSO
Nenadic, S. (1990). The life cycle of firms in nineteenth century Britain, in
P. Jobert and M. Mors (eds.), The Birth and Death of Companies: An Historical
Perspective, Lancaster, Parthenon
Nisjen, A. (1988). Self-employment in the Netherlands, International Small Business Journal, 7, pp. 5260
Noe, T. H. (1988). Capital structure and signalling game equilibria, Review of
Financial Studies, 1, pp. 33155
Norton, W. I. and W. T. Moore (2002). Entrepreneurial risk: have we been asking
the wrong question?, Small Business Economics, 18, pp. 2817
Nziramasanga, M. and M. Lee (2001). Duration of self-employment in developing countries: evidence from small enterprises in Zimbabwe, Small Business
Economics, 17, pp. 23953
OECD (1986, 1994a). Employment Outlook, Paris, OECD Publications
(1994b). Taxation and Small Businesses, Paris, OECD Publications
(1998). Fostering Entrepreneurship, Paris, OECD Publications
(2000a). The partial renaissance of self-employment, in Employment Outlook,
Paris, OECD Publications
(2000b). OECD SME Outlook, Paris, OECD Publications
OFarrell, P. N. and A. R. Pickles (1989). Entrepreneurial behaviour within
male work histories: a sector-specific analysis, Environment and Planning,
21, pp. 31131
Oi, W. Y. (1983). Heterogeneous firms and the organisation of production, Economic Inquiry, 21, pp. 14771
Olekalns, N. and H. Sibly (1992). Credit rationing, implicit contracts, risk aversion and the variability of interest rates, Journal of Macroeconomics, 14,
pp. 33747
Ordover, J. and A. Weiss (1981). Information and the law: evaluating legal restrictions on competitive contracts, American Economic Review, Papers and
Proceedings, 71, pp. 399404
Otani, K. (1996). A human capital approach to entrepreneurial capacity, Economica, 63, pp. 27389
Palich, L. E. and D. R. Bagby (1995). Using cognitive theory to explain entrepreneurial risk-taking: challenging conventional wisdom, Journal of Business Venturing, 10, pp. 42538
Parasuraman, S. and C. A. Simmers (2001). Type of employment, workfamily
conflict and well-being: a comparative study, Journal of Occupational Behaviour, 22, pp. 55168
References
299
300
References
References
301
Razin, E. and A. Langlois (1996). Metropolitan characteristics and entrepreneurship among immigrants and ethnic groups in Canada, International Migration
Review, 30, pp. 70327
Rees, H. and A. Shah (1986). An empirical analysis of self-employment in the
UK, Journal of Applied Econometrics, 1, pp. 95108
(1994). The characteristics of the self-employed: the supply of labour, in
J. Atkinson and D. J. Storey (eds.), Employment, the Small Firm and the Labour
Market, London, Routledge, pp. 31727
Reid, G. C. (1991). Staying in business, International Journal of Industrial Organization, 9, pp. 54556
(1993). Small Business Enterprise: An Economic Analysis, London, Routledge
(1999). Capital structure at inception and the short-run performance of microfirms, in Z. J. Acs, B. Carlsson and C. Karlsson (eds.), Entrepreneurship, Small
and Medium Sized Enterprises and the Macroeconomy, Cambridge, Cambridge
University Press, pp. 186205
Reid, G. C. and L. R. Jacobsen (1988). The Small Entrepreneurial Firm, David
Hume Institute, Aberdeen, Aberdeen University Press
Repullo, R. and J. Suarez (2000). Entrepreneurial moral hazard and bank monitoring: a model of the credit channel, European Economic Review, 44,
pp. 193150
Reynolds, P. D. (1999). Creative destruction: source or symptom of economic
growth?, in Z. J. Acs, B. Carlsson and C. Karlsson (eds.), Entrepreneurship, Small and Medium Sized Enterprises and the Macroeconomy, Cambridge,
Cambridge University Press, 97136
Reynolds, P. D., D. J. Storey, and P. Westhead (1994). Cross-national comparisons of the variation in new firm formation rates, Regional Studies, 28,
pp. 44356
Reynolds, P. D. and S. B. White (1997). The Entrepreneurial Process: Economic
Growth, Men, Women and Minorities, Westport, CT, Quorum Books
Reynolds, P. D. et al. (2001, 2002). Global Entrepreneurship Monitor Executive
Reports,
Rhyne, E. H. (1988). Small Business, Banks and SBA Loan Guarantees, New York,
Quorum Books
Riley, J. (1979). Testing the educational screening hypothesis, Journal of Political
Economy, 87, pp. S227S252
(1987). Credit rationing: a further remark, American Economic Review, 77,
pp. 22427
Roberts, E. B. (1991). Entrepreneurs in High Technology, Oxford, Oxford University Press
Robinson, P. B. and E. A. Sexton (1994). The effect of education and experience
on self-employment success, Journal of Business Venturing, 9, pp. 14156
Robson, M. T. (1991). Self-employment and new firm formation, Scottish Journal
of Political Economy, 38, pp. 35268
(1996). Macroeconomic factors in the birth and death of UK firms: evidence
from quarterly VAT registrations, Manchester School, 64, pp. 17088
(1997). The relative earnings from self and paid employment: a time series
analysis for the UK, Scottish Journal of Political Economy, 44, pp. 50218
302
References
References
303
304
References
References
305
306
References
Vijverberg, W. P. M. (1986). Consistent estimates of the wage equation when individuals choose among income-earning activities, Southern Economic Journal,
52, pp. 102842
Wadhwani, S. B. (1986). Inflation, bankruptcy, default premia and the stock
market, Economic Journal, 96, pp. 12038
Wagner, J. (1995). Firm size and job creation in Germany, Small Business Economics, 7, pp. 46974
Wales, T. J. (1973). Estimation of a labour supply curve for self-employed business
proprietors, International Economic Review, 14, pp. 6980
Watkins, J. M. and D. S. Watkins (1984). The female entrepreneur: her background and determinants of business choice some British data, Frontiers of
Entrepreneurship Research, Wellesley, MA, Babson College
Watson, H. (1984). Credit markets and borrower effort, Southern Economic Journal, 50, pp. 80213
(1985). Tax evasion and labour markets, Journal of Public Economics, 27,
pp. 23146
Watson, R. (1990). Employment change, profits and directors remuneration in
small and closely-held UK companies, Scottish Journal of Political Economy,
37, pp. 25974
Webb, D. C. (1991). Long-term financial contracts can mitigate the adverse
selection problem in project financing, International Economic Review, 32,
pp. 30520
Weber, M. (1930). The Protestant Ethic and the Spirit of Capitalism, New York,
Scribner
Wellington, A. J. (2001). Health insurance coverage and entrepreneurship, Contemporary Economic Policy, 19, pp. 46578
Wennekers, S. and R. Thurik (1999). Linking entrepreneurship and economic
growth, Small Business Economics, 13, pp. 2755
Wenner, M. D. (1995). Group credit: a means to improve information transfer and loan repayment performance, Journal of Development Studies, 32,
pp. 26381
Westhead, P. and M. Cowling (1995). Employment change in independent
owner-managed high-technology firms in Great Britain, Small Business Economics, 7, pp. 11140
Wette, H. (1983). Collateral in credit rationing in markets with imperfect information: note, American Economic Review, 73, pp. 4425
Wetzel, W. E. (1987). The informal venture capital market: aspects of scale and
market efficiency, Journal of Business Venturing, 2, pp. 299313
White, L. J. (1982). The determinants of the relative importance of small business, Review of Economics and Statistics, 64, pp. 429
(1984). The role of small business in the US economy, in P. M. Horvitz and
R. R. Pettit (eds.), Small Business Finance: Sources of Financing for Small
Business, Part A, Greenwich, CT, JAI Press, pp. 1949
Whittington, R. C. (1984). Regional bias in new firm formation in the UK,
Regional Studies, 18, pp. 25356
Williams, D. L. (2001). Why do entrepreneurs become franchisees? An empirical
analysis of organisational choice, Journal of Business Venturing, 14, pp. 103
24
References
307
Author index
308
Beesley, M. E. 231232
Belke, A. 172
Bell, C. 178
Bendick, M. 254255, 257, 264
Bennett, R. J. 257
Benz, M. 261
Berger, A. N. 153, 162163, 187188, 190
Bernanke, B. 158
Bernardo, A. E. 263
Bernhardt, D. 142
Bernhardt, I. 104, 107109, 189,
198199, 237239
Bernhardt, T. 214
Bernheim, B. D. 184
Bertrand, T. 208
Besanko, D. 141142, 150, 154155, 162
Besley, T. 118, 169
Bester, H. 153154, 162163
Biais, B. 171
Binks, M. 95, 111, 228229
Birch, D.L. 194196, 206
Black, J. 111112, 163, 183184, 189,
242, 245
Blackburn, R. A. 165, 206, 254
Blanchflower, D. G. 32, 71, 78, 80, 9597,
104110, 116, 179, 182, 184, 189,
212, 216, 218219
Bland, R. 20
Blau, D. M. 22, 30, 91, 103105, 107,
132, 201, 207208, 214, 224, 252,
264
Blinder, A. S. 160
Blundell, R. 198200
Boadway, R. N. 161, 245
Boden, R. J. 67, 72, 107, 125126, 133,
222, 231, 252
Bogenhold,
D. 98, 111
Bolton Report 138
Bonacich, E. 118, 120
Bond, E. W. 224
Bonini, C. P. 214
Boot, A. W. A. 153, 162163
Author index
Bopaiah, C. 171, 178
Borjas, G. J. 75, 107109, 114115,
118119, 209, 214, 121, 123, 130,
131132
Borooah, V. I. 107, 108, 122, 132, 245
Boswell, J. 215
Bosworth, B. P. 240
Bottazzi, L. 171172
Boulier, B. L. 207
Bovaird, C. 171
Bowlin, O. D. 177
Bowman, N. 250
Boyd, D. P. 254255
Boyd, R. L. 103, 107, 108, 112, 121, 122
Bracoud, F. 175
Bradford, W. D. 116, 120, 172
Brearley, S. 228229, 250
Bregger, J. E. 31, 32, 193, 197, 255
Brock, W. A. 3435, 57, 67, 107110,
112, 130, 213215, 219, 229, 230,
231, 258260, 265
Brockhaus, R. H. 76, 83
Bronars, S. G. 107109, 114115,
118119, 121, 123, 130, 209, 214
Brown, C. 197, 206
Brown, S. 20
Browne, F. X. 189
Bruce, D. 104, 107108, 110, 125, 183,
189, 204, 252, 264
Bruderl,
309
Carter, N. M. 128
Carter, S. 128
Casey, B. H. 142, 197, 206
Casson, M. 166, 216, 229, 257
Chamley, C. 153
Chan, Y.-S. 153, 162, 164
Chell, E. 228229, 250
Chiswick, C.U. 33
Cho, Y. 147
Christiansen, L.R. 209
Clark, K. 17, 34, 68, 75, 104,
107108, 110, 113, 115, 120, 121,
122, 132
Clay, N. 262
Clemenz, G. 142, 150, 156, 162
Clotfelter, C. T. 250, 263
Coate, S. 117, 169
Cockburn, I. 195197
Coco, G. 162163
Coffield, F. 109
Cohen, W.M. 230
Compton, J. 32, 72, 104105, 107108,
193, 206, 222223, 230
Connelly, R. 133
Cooper, A. C. 215, 219, 223, 230231,
263
Copulsky, W. 256257
Cosh, A. D. 179, 190, 217, 224
Court, G. 17, 3334, 129, 242
Covick, O. 188
Cowling, M. 96, 104105, 107109,
111, 124, 126, 133, 163, 189, 194,
215, 216, 219, 222, 231, 238240,
262, 264
Craggs, P. 217
Cramer, J. S. 104, 107108, 194, 264
Creedy, J. 107
Creigh, S. 108, 197, 206
Cressy, R. C. 153, 156, 184, 220,
222223, 230, 231
Crewson, P. E. 104, 107, 252
Cromie, S. 258260, 262
Cukierman, A. 141
Cullen, J. B. 105, 112, 263
Curran, J. 33, 76, 110, 165, 194, 197,
206, 269, 271
Cuthbertson, K. 231
da Rin, M. 171172
Daly, M. 181182, 219
Dant, R. P. 177, 257
Davidson, M. J. 216
Davidsson, P. 196
Davis, S. J. 195197, 230
de Aghion, B. A. 167
310
Author index
Felstead, A. 178
Ferber, M. A. 209, 241
Ferman, L. A. 110
Fielden, S. L. 216
Field-Hendrey, E. 108, 125
Fitz-Roy, F. R. 108, 194, 214, 256, 260
Flota, C. 107, 114, 119, 121122
Folster,
Author index
Gruber, J. 108
Guimaraes, P. 225
Guinnane, T. W. 154, 169, 178
Haber, S. E. 127, 188, 209
Haggerty, A. 206
Hakim, C. 31, 33, 80, 95, 125, 206207,
216, 218220
Hall, B. H. 196, 230
Hall, G. 231
Haltiwanger, J. C. 195197, 230
Hamermesh, D. S. 56
Hamilton, B. H. 72, 97, 104, 108,
110111, 122, 186, 209, 214,
258260
Hamilton, D. 128
Hamilton, J. 197, 206
Hamilton, R. T. 231232
Hanoch, G. 203
Hanvey, E. 215, 230
Harhoff, D. 162, 184
Harper, D. A. 185
Harris, J. E. 205
Harris, R. I. D. 215
Harrison, R. T. 111, 172, 178
Hart, M. 107, 108, 111, 122, 132, 215,
230, 245
Hart, O. 153
Hart, P. E. 196, 214, 230, 231
Harvey, M. 31, 110, 251, 253
Hawley, C. B. 104, 107108, 115, 214,
237
Haworth, C. 228229, 427
Headen, A. E. 1516, 35
Heady, P. 206
Hebert, R. F. 216, 228229
Heckman, J. J. 2122
Hellmann, T. 172, 174175
Hellwig, M. 141, 161, 155
Henrekson, M. 128
Highfield, R. 111112, 227
Hillier, B. 149, 156, 158161, 175
Hodgman, D. 161
Holmes, T. J. 212, 222, 224, 231
Holtz-Eakin, D. 19, 67, 72, 8586, 104,
107108, 129, 182183, 189, 204,
250, 264 223, 228, 231, 242, 246,
271
Honig, M. 203
Horvitz, P. M. 177
House, W. J. 208
Hout, M. 109, 122, 132, 267268
Howitt, P. 141, 186
Hubbard, R. G. 183, 189
Huber, B. 177, 193, 230, 263, 271
311
Hudson, J. 111112, 224225, 230231
Hughes, A. 178179, 190, 217, 224, 231
Hundley, G. 128, 260
Huppi, M. 178
Iams, H. M. 204205, 207
Ibrahimo, M. V. 156, 158161
Ibrayeva, E. 208215
Idiara, G. K. 208
Ijiri, Y. 214
Innes, R. 154, 173, 239
Iyigun, M. F. 110
Jacobsen, L. R. 228, 231, 257
Jaffee, D. 140142, 150, 160, 183
Jain, B. 172
Jarley, P. 110
Jefferson, P. N. 193
Jeffreys, D. 111112, 183184, 189
Jenkins, S. P. 193, 213
Jennings, A. 95, 111
Johansson, E. 108, 189
Johnson, D. G. 209
Johnson, P. S. 107, 110111, 227, 230,
232
Jones, A. M. 97, 105
Jones, P. 217
Jones, T. 116, 121, 166, 207
Joulfaian, D. 107108, 182, 189, 223, 231,
245, 263
Jovanovic, B. 21, 31, 3334, 58, 6667,
72, 107, 179, 180181, 208215, 218,
220, 223, 227
Julien, P. A. 248249
Jung, Y. H. 247248
Kalleberg, A. L. 133, 230
Kanatos, G. 153, 162
Kanbur, S. M. 216, 219, 222, 227229,
243245, 248, 263
Kangasharju, A. 215, 223, 231, 232
Kaplan, S. N. 183
Karlsson, C. 171
Katz, E. 222
Katz, J. A. 31, 228
Kaufmann, P. J. 79, 119
Kawaguchi, D. 214
Keasy, K. 163
Keeble, D. 243, 231
Keeton, W. R. 139, 141
Kent, C. A. 142
Kesselman, J. R. 250, 263
Kets de Vries, M. F. R. 7778
Keuschnigg, C. 177
Khandker, S. R. 169
312
Author index
Levine, R. 218
Levy, B. 179
Lewis, W. A. 183184
Lichtenstein, J. 127, 188, 209
Light, I. 118, 120, 129130, 166, 255
Lim, C. 230
Lin, Z. 32, 72, 104105, 107108, 193,
206, 222223, 230
Lindh, T. 104, 109110, 112, 182, 189,
264
Lindmark, L. 196
Link, A. N. 216
Little, R. D. 22, 34
Lofstrom, M. 107, 121122, 130
Long, J. E. 105, 108, 110, 112, 132,
252
Lopez, R. 199
Loscocco, K. A. 262
Loufti, M. F. 93
Loury, G. 169
Lovalolo, D. 262
Lucas, R. E. 5458, 62, 64, 67, 70, 73,
8687, 89, 9192, 208209, 243
Luthans, F. 32
Lyon, F. 257
Macafee, K. 250
MacDonald, R. 109
MacMillan, I. C. 213
Macpherson, D. A. 133
MaCurdy, T. 198200
Maddala, G. S. 25
Maddison, A. 56
Mahmood, T. 224225, 231
Majluf, N. S. 175176
Makepeace, G. H. 104, 107, 132,
213214, 236
Makin, P. J. 216
Manove, M. 263
Manser, M. E. 32
Marchand, M. 245
Marsh, A. 31
Marshall, A. 42, 226
Marshall, J. N. 257
Mason, C. M. 172, 178
Mata, J. 225, 230, 231
Matheson, J. 31
Mattesini, F. 155
Maxim, P. S. 107108, 214
Mayer, A. 194
Mazumdar, D. 208
McClelland, D. C. 250
McCormick, D. 33
McCosham, A. 257
McCue, K. 17, 33, 197
Author index
McEntee, P. 104, 107110, 112, 189
McEvoy, D. 116, 121, 207
McKay, S. 96, 108, 186
McKernan, S. M. 168169
McNulty, H. 256257
Meager, N. 17, 3334, 9596, 108, 111,
129, 264265
Medoff, J. 197, 206
Meredith, G. G. 219, 230
Metcalf, H. 115, 165
Meyer, B. D. 95, 107108, 110, 113114,
119120, 122, 124, 130, 132133,
184, 214, 230
Michelacchi, C. 218
Milde, H. 141142, 154
Miller, R. A. 240
Mitchell, P. 70, 104105, 109, 111, 240,
264
Mlakar, T. 92, 104
Modigliani, F. 141
Modood, T. 115, 165
Moisio, A. 232
Moore, C. S. 32
Moore, J. 153
Moore, R. L. 104105, 107108,
110111, 115, 195, 197, 252
Moore, W. T. 264
Mora, M.T. 107, 114, 119, 121122
Moralee, J. 128129, 133, 188, 190, 193,
197198, 204, 206207, 212213
Morduch, J. 167, 178
Moresi, S. 263
Morgan, K. 216
Morris, C.N. 250
Mosakowski, E. 72, 104, 110, 257
Moskowitz, T. J. 190
Mueller, R. E. 104, 107108, 110111,
207
Muller, E. 94, 109, 195197, 249250
Myers, S. C. 175176
Myrdal, G. 113, 132
Nafziger, E. W. 223
Neck, P. A. 45, 66
Nee, V. 74, 113
Nelson, R. E. 219, 230
Nenadic, S. 219
Newman, A. F. 9091, 100, 110, 133
Nielsen, S. B. 122, 177, 230, 263, 271
Nisjen, A. 34
Noe, T. H. 176
Nolan, M. A. 108, 194, 214, 256, 260
Norton, W. I. 264
Nucci, A. R. 6, 222, 231
Nziramasanga, M. 230
313
OFarrell, P. N. 104, 108, 257
Odle, M. 195
OECD 103, 127, 170171, 197, 205207,
229, 245246, 254
Ohlsson, H. 104, 109110, 112, 182, 189,
264
Oi, W. Y. 212, 224
Olekalns, N. 142
Olofsson, C. 196
Ophem, H. van 96, 104, 107, 110, 189,
230, 241, 252, 256
Ordover, J. A. 147, 201202
Oswald, A. 104, 105110, 116, 179, 182,
184, 189, 207, 240, 257, 260261
Otani, K. 224225
Oulton, N. 196, 230
Owen, A. L. 110
Pakes, A. 208
Palich, L. E. 264
Parasuraman, S. 81
Parker, S. C. 88, 92, 97, 103105, 107,
109, 111112, 156, 159, 166, 177,
185186, 193194, 196, 199,
202207, 209, 213214, 217218,
223, 225, 227, 229, 231232, 235,
237, 238239, 253, 264
Parsons, W. 206
Pavitt, K. 216217
Pekkala, S. 215, 223, 231
Penrod, J. 243
Perez, S. J. 188
Pestieau, P. 245, 248249
Petersen, B. 183
Petersen, M. A. 162
Petrin, T. 207
Pfeiffer, F. 219, 225, 255
Phillips, B. D. 219, 230
Phillips, J. D. 32
Phillips, P. C. B. 202
Pickles, A. R. 104, 108, 257
Picot, G. 104105, 107108, 193, 196,
206207, 222223, 230, 241
Pierce, B. 17, 33, 193, 196, 206, 222223,
230
Piore, M. J. 88
Pissarides, C. A. 213, 250251
Pitt, M. M. 169
Pollert, A. 177
Pomroy, R. 217
Portes, A. 122, 130
Portugal, P. 225, 231
Posssen, U. M. 231, 248249
Poterba, J. 108, 176
Power, L. 206207
314
Author index
Rushing, F. W. 214
Russell, T. 140, 141, 150, 160
Sabel, C. F. 88
Sacerdote, R. 245
Sakova, Z. 17, 28, 34, 69, 104, 194,
261262
Sammelson, L. 206, 230
Sanders, J. M. 113, 246
Sandford, C. 265
Santor, E. 74
Say, J-B. 88, 216217
Scase, R. 108109, 206, 258
Schaffner, J. A. 88, 92
Scharfstein, D. 206
Scheffler, R. M. 207
Scherer, F. M. 217, 230
Schiller, B. R. 104, 107, 252
Schmidt-Mohr, U. 154
Schmitz, J. A. 8890, 212, 222, 224, 231
Schuetze, H. J. 32, 9697, 104105,
107108, 110111, 193, 197, 252,
264
Schuh, S. 195197
Schultz, T. P. 92, 104, 203, 271
Schultz, T. W. 216217, 230
Schumpeter, J. 41, 66, 78, 8788, 216,
230, 231
Scott, J. A. 162
Segal, U. 213
Selden, J. 226
Sessions, J. G. 20
Sexton, D. L. 77, 133
Sexton, E. A. 107108
Shah, A. 104, 107108, 132, 197,
199201, 213214, 236
Shane, S. 230
Shapero, A. 254, 256
Sheshinski, E. 47
Shleifer, A. 184
Shorrocks, A. F. 194
Sibly, H. 142
Sillamaa, M.-A. 263
Simmers, C. A. 81
Simmons, P. 231
Simon, H. A. 214
Singell, L. D. 229
Sleuwaegen, L. 107, 230
Slovin, M. B. 187
Sluis, J. van der 196, 214
Smallbone, D. 32, 257
Smiley, R. 111112, 227
Smith, A. 109, 161
Smith, B. D. 155, 160, 241, 262
Smith, I. J. 217
Author index
Smith, S. 249250
Snow, A. 247248
Sollis, R. 35
Southey, C. 8182, 163, 231
Sowell, T. 115
Spear, R. 125
Spilling, O. R. 101
Spivak, A. 213
Squire, L. 33
Staber, U. 98, 111
Stajkovic, A. 208215
Stanworth, J. 225
Steinmetz, G. 29, 32, 94, 111, 247,
257258
Stiglitz, J. 143148, 153154, 156158,
160163, 167, 169, 173175, 183,
201, 219, 238239
Stoll, H.R. 176
Storey, D. J. 95, 97, 101, 104105,
110112, 193, 199, 207208, 212,
215, 217, 230231, 255, 257, 262,
264, 266267
Stutzer, M. J. 155, 179, 241, 262
Stutzes, A. 32, 71, 81, 107108
Suarez, J. 223
Summers, L. H. 184
Sumner, D. A. 197
Sushka, M. E. 187
Sutton, J. 230
Taylor, M. P. 34, 6768, 79, 84, 96,
104105, 107111, 126, 132133,
181, 183, 189, 194, 219, 222224,
231, 264
Teilhet-Waldorf, S. 33
Tennyson, S. 117
Terrell, D. 223
Tether, B. S. 217
Thakor, A. V. 141143, 150, 153155,
162, 164
Thornton, J. 199, 207
Thurik, R. 88
Thwaites, A. T. 217
Timmons, J. A. 253255
Todaro, M. P. 263
Tovanen, O. 156
Townsend, J. 216217
Townsend, R. 161
Trandel, G. A. 247248
Tucker, I. B. 104105, 107109, 132, 264
Tyson, L. dAndrea 207
Udell, G. F. 153, 162163, 187188, 190
Uusitalo, R. 96, 105, 107109, 181182,
264
315
Vale, P. 228229
Variyam, J. N. 215, 230
Veall, M. R. 263
Vijverberg, W. P. M. 2223, 29, 3435,
132
Virdee, S. 115, 165
Vissing-Jrgensen, A. 190
Vivarelli, M. 105, 107, 231
Wadhwani, S. B. 231
Wagner, J. 196
Waldfogel, J. 209, 241
Waldinger, R. 118, 120121
Waldorf, W. H. 208
Wales, T. J. 199
Walker, S. 243, 231
Wall, H. J. 99, 101, 105, 108,
110112
Watkins, D. S. 127
Watkins, J. M. 127
Watson, H. 148, 247
Watson, R. 163, 215
Weathers, R. 19, 72, 129
Webb, D. G. 142, 147, 150, 153,
156159, 163164, 173174, 184,
231
Webb, S. 33
Weber, G. 34, 250251
Weber, M. 257
Weiss, A. 143148, 147, 153154,
156158, 161163, 173175,
238239
Welch, I. 263
Wellington, A. J. 26, 108, 133, 264
Wellisz, S. 88, 92, 224225, 231, 239
Welter, F. 207
Wennekers, S. 88
Wenner, M. D. 168
Westhead, D. 101, 104, 110, 112
Westhead, P. 215216, 219, 222, 231
Wette, H. 161
Wetzel, W. E. 172, 178
White, L. J. 182, 266
White, M. J. 229
White, S. B. 93, 247248, 256257,
261
Whittington, R. C. 110
Wicks, P. J. 257
Willard, K. L. 188190
Williams, D. L. 119, 207, 265
Williams, D. R. 207, 241242
Williams, M. 128
Williams, S. L. 197
Williamson, O. E. 228
Williamson, S. D. 149
316
Author index
Willig, R. D. 153154
Winden, F. van 104, 108109, 214, 224,
237239, 257, 269
Wit, G. de 104, 108109, 214, 219, 224,
228, 237239, 257, 269
Wolpin, K. I. 22
Woo, C. Y. 8183, 215, 223, 230, 231
Wood, E. 217, 224
Worrall, T. 149
Wren, C. 105, 205, 241242, 252,
263264
Wright, E. O. 9, 11, 29, 32, 94, 111,
270
Wu, Y. 142
Wydick, B. 168
Xu, B. 149, 181
Yamawaki, H. 227
Yoon, I. J. 118, 165166
Yuengert, A. M. 121, 130, 133, 264
Yunus, M. (Grameen Scheme) 167
Zhou, M. 122, 130
Ziegler, R. 224, 231
Zingales, L. 183
Subject index
317
318
Subject index
co-operatives 166
co-ordination, of factors of production 216
corporation tax, and venture capital 177
creative destruction 216
credit cards 177
credit co-operatives 169170, 178
credit rationing 137, 138, 262
effect of government loans 241
and equity rationing 174
evaluation of 154156, 267
loan guarantee scheme 237
redlining 139, 143, 147, 148, 161, 239,
262
temporary 179, 189
Type I 139, 140142, 180, 181182,
183, 184185, 186
Type II 139, 142150, 186189
see also EvansJovanovic model,
StiglitzWeiss model
criminal behaviour 254255
cultural traditions 74
debt finance
and equity finance 173174, 175, 267
survival rates 223
see also credit rationing
debt repayment 150154
decreasing absolute risk aversion (DARA)
184
Department for Education and Skills 256
Department for Trade and Industry (DTI)
230, 256
developing countries
credit rationing 179, 186
duration of self-employment 230
entrepreneurship 240
family finance 166
incomes 208
micro-finance schemes 167168,
168169
occupational choice 238
self-employment rates 256257, 82 in
Asia 262
differential income tax 246
discrimination against ethnic minorities
in capital markets 116117,
by consumers 118120
by employers 115116, 117
disequilibrium process 217
distressed company phenomenon 187
double-limit tobit maximum likelihood 201
drug-dealers, and risk aversion 265
earnings functions 2023
in structural probit model 26
Subject index
equity gap 174, 176
equity rationing 174176
ethnic enclaves 120, 121122
ethnic groups, and self-employment 107,
113, 266267
earnings 114
industrial concentration 120
non-black 113114
role models 122
see also discrimination
EvansJovanovic model of credit rationing
180181
experience
and age 240
different types 241
effect on earnings 241
survival 222223
failure rates 116, 228
see also survival rates
family background 266, 110, 194
family finance 137, 165166, 178, 267
and survival rates 223
family workers 231
female self-employment 266267
earnings 126129
move out of unemployment 96, 111
rates 124126
working hours 197
female workers 212213
financial markets, development 223
financing costs, and equity finance 173
firm entry and exit
model 208213, 227
relationship between 225227, 232
firm growth, see Gibrats Law
firm size
and capital stock 56
definition of self-employment 64
growth rates 214
impact of technology 270
loan denial 190
see also Gibrats Law
firm survival, effect of assets 182183
first-order stochastic dominance 220222
fixed-effects model 30
flexibility 125
formal qualifications 243
France, self-employment rates 257
franchising
finance 177, 267
risk 84
self-employment 93, 197, 207,
119120
survival rates 225
319
fringe benefits 242246
income measurement 16
funding gap, see equity gap
gambling 83
gazelles 196
Germany, self-employment schemes 264
Gibrats Law 55, 56, 213214
refinements to 214
government policy
attitude to entrepreneurship 235
employment creation 194, 260
information and advice provision
261262
involvement in entrepreneurship
268271
survival rates 228229
see also credit rationing, loan guarantee
schemes, procurement, social
protection
government regulation
excess 246
impact on small firms 258260
intervention in credit markets 236239
Grameen Bank 167, 178
grants to small businesses 241, 264
group lending 162, 167
advantages of 167168
hazard models, of firm survival 220222
health
flexibility of self-employment 248249
insurance 108, 127
hidden information, in financial contracts
150
high-tech firms, survival rates 219
home-workers 32
house prices, and regional
self-employment 100101
human capital 239
and credit rationing 183
husbands role in household 125
immigrants
cohort effects 131132
duration of residence 130131
likelihood of becoming entrepreneurs
129
implicit contract theory 186
income effect, in labour supply models 198
income risk, and occupational choice 223
income tax 260
and job creation 194
small firm growth rates 216
and venture capital 177
320
Subject index
income tax
and corporation tax 263
and entrepreneurship 242246
see also tax evasion
incomes, from self-employment
in Australia 17
average aggregate differences 69
in Europe 188
inequality 190
measurement 205206
in paid employment 209
in transition economies 17
in UK 187
under-reporting 199
in US 1617, 18
incorporation of business 19, 31
and incomes of owners 5458,
208213
independence, preference for 258
industrial structure, and self-employment
9294
information costs, and equity finance
173
information flows 176
inheritance tax 246
impatience 66
inheritance
and firm survival 182183
loan security 166
and start-ups 181182
Initial Public Offering 171
injury 207
innovation 216, 217218
small firms advantage 216217
interest rates
and bankruptcy 225
business finance 103105
high initial rate 153154
intertemporal tax-shifting 247
intrapreneurship 31
investment information, and venture
capital 172
investment, and cash flow 183
job change 96
job creation
Enterprise Allowance Scheme 254
by entrepreneurs 193194
quality 196197
small firms 194196, 206207,
job layoffs 97
job satisfaction 260
job-shopping theory 70
joint liability 154
see also group lending schemes
Subject index
moral hazard
hidden action 148149
hidden information 149
joint liability schemes 167
StiglitzWeiss model 147
motivation 217
multinomal logit model 28
multi-period lending contracts 162,
multiple job-holding 207
multiplier effect, firm births and deaths
226
Mutual Guarantee Scheme 170, 178
n-Ach, see achievement, need for
NASDAQ 173
National Economic Research Associates
(NERA) 188
National Insurance contributions 258
National Longitudinal Survey of Youth 132
negative income 137
networking 239241
non-governmental organisations (NGOs)
256257
non-increasing relative risk aversion 45
and decreasing absolute risk aversion 45
occupational choice 45
costs of switching 5052
employee ability 5860
government intervention 242
Lucas model 5557
tax incentives 251253
theories 43
time-series approach to modelling 175
cointegration methods 203
panel data 203
over-investment 139, 218, 228
and Loan Guarantee Scheme 239
in de Meza and Webb model 156158,
163, 184
over-optimism 254
attitude to risk 264
own-account workers 6, 194
parental managerial experience 197198
part-time workers 212213, 126, 133
payroll taxes, and occupational choice 264
|
https://id.scribd.com/document/274151291/The-Economics-of-Self-Employment-and-Entrepreneurship-2004-Parker
|
CC-MAIN-2019-22
|
refinedweb
| 62,905 | 54.22 |
Back to index
import "nsIHttpChannel.idl";
This interface allows for the modification of HTTP request parameters and the inspection of the resulting HTTP response status and headers when they become available.
FROZEN
Definition at line 54 of file nsIHttpChannel.idl..
Get the value of a particular request header.
Get the value of a particular response header.
Returns true if the server sent the equivalent of a "Cache-control: no-cache" response header.
Equivalent response headers include: "Pragma: no-cache", "Expires: 0", and "Expires" with a date value in the past relative to the value of the "Date" header.
Returns true if the server sent a "Cache-Control: no-store" response header...
Set the value of a particular request header.
This method allows, for example, the cookies module to add "Cookie" headers to the outgoing HTTP request.
This method may only be called before the channel is opened.
If aValue is empty and aMerge is false, the header will be cleared..
Call this method to visit all request headers.
Calling setRequestHeader while visiting request headers has undefined behavior. Don't do it!
Call this method to visit all response headers.
Calling setResponseHeader while visiting response headers has undefined behavior. Don't do it!
This attribute is a hint to the channel to indicate whether or not the underlying HTTP transaction should be allowed to be pipelined with other transactions.
This should be set to FALSE, for example, if the application knows that the corresponding document is likely to be very large.
This attribute is true by default, though other factors may prevent pipelining.
This attribute may only be set before the channel is opened.
Definition at line 160 of file nsIHttpChannel.idl..
This attribute specifies the number of redirects this channel is allowed to make.
If zero, the channel will fail to redirect and will generate a NS_ERROR_REDIRECT_LOOP failure status.
NOTE: An HTTP redirect results in a new channel being created. If the new channel supports nsIHttpChannel, then it will be assigned a value to its |redirectionLimit| attribute one less than the value of the redirected channel's |redirectionLimit| attribute. The initial value for this attribute may be a configurable preference (depending on the implementation).
Definition at line 174 of file nsIHttpChannel.idl.
Get/set the HTTP referrer URI.
This is the address (URI) of the resource from which this channel's URI was obtained (see RFC2616 section 14.36).
This attribute may only be set before the channel is opened.
NOTE: The channel may silently refuse to set the Referer header if the URI does not pass certain security checks (e.g., a "https://" URL will never be sent as the referrer for a plaintext HTTP request). The implementation is not required to throw an exception when the referrer URI is rejected.
Definition at line 92 of file nsIHttpChannel.idl.
Set/get the HTTP request method (default is "GET").
Setter is case insensitive; getter returns an uppercase string.
This attribute may only be set before the channel is opened.
NOTE: The data for a "POST" or "PUT" request can be configured via nsIUploadChannel; however, after setting the upload data, it may be necessary to set the request method explicitly. The documentation for nsIUploadChannel has further details.
Definition at line 75 of file nsIHttpChannel.idl.
Returns true if the HTTP response code indicates success.
The value of nsIRequest::status will be NS_OK even when processing a 404 response because a 404 response may include a message body that (in some cases) should be shown to the user.
Use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response codes, if that is required by your application.
Definition at line 216 of file nsIHttpChannel.idl.
Get the HTTP response code (e.g., 200).
Definition at line 189 of file nsIHttpChannel.idl.
Get the HTTP response status text (e.g., "OK").
NOTE: This returns the raw (possibly 8-bit) text from the server. There are no assumptions made about the charset of the returned text. You have been warned!
Definition at line 201 of file nsIHttp.
|
https://sourcecodebrowser.com/lightning-sunbird/0.9plus-pnobinonly/interfacens_i_http_channel.html
|
CC-MAIN-2016-44
|
refinedweb
| 686 | 58.79 |
Feeding, morphological changes and allometric growth during starvation in miiuy croaker larvae
Authors
Abstract
We investigated the effects of the timing of first feeding (larvae in F0, F1, F2, F3 and S were first fed on day 3, 4, 5, 6 days after hatching (DAH) and unfed, respectively) on feeding, morphological changes, survival and growth in miiuy croaker larvae at 24°C. The fed larvae initiated feeding on 3 DAH and reached point of no return (PNR) on 6 DAH. Larvae in F0 and F1 groups survived apparently better than F2 group at the end of the experiment on 36 DAH. High larval mortality occurred from 3 to 7 DAH in all feeding groups, accounting for 40% (F0, F1 and F2 groups) to 90% (F3 and S groups) of the total mortality. Larvae in F0 and F1 groups grew better than F2 group throughout the experiment. Eye diameter, body height, head height and mouth gape of the first feeding larvae were more sensitive to starvation than other morphometrics and could be used as indicators for evaluating their nutritional status. Results indicated that delayed first feeding over 1 day after yolk exhaustion could lead to poor larval survival and growth. To avoid starvation and obtain good growth in culturing, larvae feeding should be initiated within 1 day after yolk exhaustion at 24°C.
|
http://link.springer.com/article/10.1007%2Fs10641-008-9412-0
|
CC-MAIN-2016-36
|
refinedweb
| 222 | 52.02 |
Recommended JSF Enhancements
- 3.1 An Introduction to Facelets
- 3.2 Seam JSF Enhancements
- 3.3 Add Facelets and Seam UI Support
- 3.4 PDF, Email, and Rich Text
- 3.5 Internationalization
The Hello World example in Chapter 2 demonstrates how to build a Seam application with standard EJB3 and JSF. Seam chooses JSF as its web framework for many reasons. JSF is a standard technology in Java EE 5.0 and has a large ecosystem of users and vendors. All Java application servers support it. JSF is fully component-based and has a vibrant vendor community for components. JSF also has a powerful and unified expression language (EL, using the #{...} notation) that can be used in web pages, workflow descriptions, and component configuration files throughout the application. JSF also enjoys great support by visual GUI tools in leading Java IDEs.
However, JSF also has its share of problems and awkwardness. JSF has been criticized for being too verbose and too component-centric (i.e., not transparent to HTTP requests). Being a standard framework, JSF innovates more slowly than grassroots open source projects such as Seam itself and is therefore less agile when it comes to correcting design issues and adding new features. For these reasons, Seam works with other open source projects to improve and enhance JSF. For Seam applications, we strongly recommend that you use the following JSF enhancements:
- Use the Facelets framework for web pages. Write your web pages as Facelets XHTML files instead of JSP files. Facelets provides many benefits over the standard JSP in JSF; see Section 3.1.1 for more details.
- Use the Seam JSF component library for special JSF tags that take advantage of Seam-specific UI features, as well as Seam's extended EL for JSF.
- Set up Seam filters to capture and manage JSF redirects, error messages, debugging information, and so on.
Throughout the rest of the book, we assume that you already have these three JSF enhancements installed and enabled (see Section 3.3 for instructions). In Section 8.1.1, we explain how Seam supports lazy loading in JSF page rendering and expands the use of JSF messages beyond simple error messages. In Part III, we will cover integration of data components directly into the JSF web pages. Such direct integration allows Seam to add important features to JSF, including end-to-end validators (Chapter 12), easy-to-use data tables (Chapter 13), bookmarkable URLs (Chapter 15), and custom error pages (Chapter 17). In Part IV, we will discuss how to incorporate third-party AJAX UI widgets in Seam applications. In Section 24.5, we discuss how to use the jBPM business process to manage pageflows in JSF/Seam applications. This allows you to use EL expressions in page navigation rules and to have navigation rules that are dependent on the application state.
In this chapter, we will first explore how those additional frameworks improve your JSF development experience. You will see how to develop applications with Facelets and Seam UI libraries. Then, in Section 3.3, we will list the changes you need to make in the Hello World example to support the Facelets and Seam UI components. The new example is in the betterjsf project in the book's source code bundle. Feel free to use it as a starting point for your own applications.
3.1 An Introduction to Facelets
JavaServer Pages (JSP) is the de-facto "view" technology in JavaServer Faces (JSF). In a standard JSF application, the web pages containing JSF tags and visual components are typically authored as JSP files. However, JSP is not the only choice for authoring JSF web pages. An open source project called Facelets () allows you to write JSF web pages as XHTML files with significantly improved page readability, developer productivity, and runtime performance compared to equivalent pages authored in JSP. Although Facelets is not yet a Java Community Process (JCP) standard, we highly recommend that you use it in your Seam applications whenever possible.
3.1.1 Why Facelets?
First, Facelets improves JSF performance by 30 to 50 percent by bypassing the JSP engine and using XHTML pages directly as the view technology. By avoiding JSP, Facelets also avoids potential conflicts between JSF 1.1 and JSP 2.4 specifications, which are the specifications supported in JBoss AS 4.x (see the accompanying sidebar for details).
Second, you can use any XHTML tags in Facelets pages. It eliminates the need to enclose XHTML tags and free text in the <f:verbatim> tags. These <f:verbatim> tags make JSP-based JSF pages tedious to write and hard to read.
Third, Facelets provides debugging support from the browser. If an error occurs when Facelets renders a page, it gives you the exact location of that error in the source file and provides context information around the error (see Section 17.5). It is much nicer than digging into a stack trace when a JSP/JSF error occurs.
Last, and perhaps most important, Facelets provides a template framework for JSF. With Facelets, you can use a Seam-like dependency injection model to assemble pages instead of manually including page header, footer, and sidebar components in each page.
3.1.2 A Facelets Hello World
As we discussed, a basic Facelets XHTML page is not all that different from the equivalent JSP page. To illustrate this point, we ported the Hello World sample application (see Chapter 2) from JSP to Facelets. The new application is in the betterjsf project. Below is the JSP version of the hello.jsp page:
<%@ taglib<br/> <h:commandButton </h:form> </f:view> </body> </html>
Compare that with the Facelets XHTML version of the hello.xhtml page:
<html xmlns="" xmlns: <body> <h2>Seam Hello World</h2> <h:form> Please enter your name:<br/> <h:inputText <br/> <h:commandButton </h:form> </body> </html>
It is pretty obvious that the Facelets XHTML page is cleaner and easier to read than the JSP page since the XHTML page is not cluttered up with <f:verbatim> tags. The namespace declarations in the Facelets XHTML page conform to the XHTML standard. Other than that, however, the two pages look similar. All the JSF component tags are identical.
3.1.3 Use Facelets as a Template Engine
For most developers, the ability to use XHTML templates is probably the most appealing feature of Facelets. Let's see how it works.
A typical web application consists of multiple web pages with a common layout. They usually have the same header, footer, and sidebar menu. Without a template engine, you must repeat all those elements for each page. That's a lot of duplicated code with complex HTML formatting tags. Worse, if you need to make a small change to any of the elements (e.g., change a word in the header), you have to edit all pages. From all we know about the software development process, this type of copy-and-paste editing is very inefficient and error-prone.
The solution, of course, is to abstract out the layout information into a single source and thus avoid the duplication of the same information on multiple pages. In Facelets, the template page is the single source of layout information. The template.xhtml file in the Seam Hotel Booking example (the booking project in source code) is a template page.
<html xmlns="" xmlns: <head> <title>JBoss Suites: Seam Framework</title> <link href="css/screen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="document"> <div id="header"> <div id="title">...</div> <div id="status"> ... Settings and Log in/out ... </div> </div> <div id="container"> <div id="sidebar"> <ui:insert </div> <div id="content"> <ui:insert </div> </div> <div id="footer">...</div> </div> </body> </html>
The template.xhtml file defines the layout of the page header, footer, sidebar, and main content area (Figure 3.1). Obviously, the sidebar and main content area have different content for each page, so we use the <ui:insert> tags as placeholders in the template. In each Facelets page, we tag UI elements accordingly to tell the engine how to fill the template placeholders with content.
Figure 3.1 The template layout
Each Facelets page corresponds to a web page. It "injects" contents for the <ui:insert> placeholders into the template. Below is the main.xhtml page of the Seam Hotel Booking example application.
<ui:composition <ui:define <ui:include <div class="section"> <h:form> <h1>Search Hotels</h1> ... ... </h:form> </div> <div class="section"> <h:dataTable <h1>Current Hotel Bookings</h1> </div> <div class="section"> <h:dataTable <h1>Stateful and contextual components</h1> <p>... ...</p> </ui:define> </ui:composition>
At the beginning of the main.xhtml file, the code declares that the template.xhtml template is used to format the layout. The <ui:define> elements correspond to the <ui:insert> placeholders of the same names in the template. You can arrange those <ui:define> elements in any order, and at runtime, the Facelets engine renders the web pages according to the template.
3.1.4 Data List Component
One of the biggest omissions in the current JSF specification is that it lacks a standard component to iterate over a data list. The <h:dataTable> component displays a data list as an HTML table, but it is not a generic iteration component.
Facelets remedies this problem by providing a <ui:repeat> component to iterate over any data list. For instance, the following Facelets page snippet displays a list in a table-less format:
<ui:repeat <div class="faninfo">#{fan.name}</div> </ui:repeat>
In Section 3.4.1 and Section 3.4.2, you will see that the Facelets <ui:repeat> component can be used in completely non-HTML environments.
In this section, we just scratched the surface of what Facelets can do. We encourage you to explore Facelets () and make the most out of this excellent framework.
|
http://www.informit.com/articles/article.aspx?p=1324941&seqNum=5
|
CC-MAIN-2017-09
|
refinedweb
| 1,647 | 65.93 |
I love this: C++ Multi-Dimensional Analog Literals.
I quote:
Have you ever felt that integer literals like “4” don’t convey the true size of the value they denote? If so, use an analog integer literal instead:unsigned int b = I---------I;
It goes on to explain that you can use 2- and 3-dimensional “analog literals”. Genius. Read the article. Try to read the code :)
Isn’t C++ … erm … powerful?
You’ll notice that there are 9 dashes used to denote 4. This is because the trick it is using uses operator--. I’m sure the original author did this in his/her sleep and thought it was too trivial to post (or posted it before?) but I thought: if we can use operator! instead, can’t we create analog literals that use the same number of symbols as the number we want?
The answer is yes, and it’s pretty simple:
notliterals.h:
class NotLiteral { public: NotLiteral( unsigned int ival ) : val_( ival ) { } NotLiteral operator!() const { return NotLiteral( val_ + 1 ); } operator unsigned int() const { return val_; } unsigned int val_; }; const NotLiteral NL( 0 );
test_notliterals.cpp:
#include "notliterals.h" #include <cassert> int main() { assert( !!!!NL == 4 ); assert( !!NL == 2 ); assert( !!!!!!!!!!!!!!!NL == 15 ); }
With this simpler form, it’s almost believable that there might be some kind of useful application?
Extending this to 3 dimensions is left as an exercise for the reader. For 2 dimensions, if you just want the area (not the width and height), how about this?:
assert( !!! !!! !!!NL == 9 );
Update: By the way, if you don’t like all the emphasis! of! using! exclamation! marks! you can do the same thing with the unary one’s complement operator, ~. Just replace “!” everywhere above with “~” and you’re done. Unfortunately, you can’t do the same with – or + because the parser recognises “–” as the decrement operator instead of seeing that it is clearly two calls to the unary negation operator.
|
https://www.artificialworlds.net/blog/2009/05/20/analog-literals/
|
CC-MAIN-2020-45
|
refinedweb
| 322 | 67.15 |
Using Web Components in Vue
Cory Rylan
・3 min read
This post is a modified excerpt chapter from my new EBook Web Component Essentials
VueJS is a new JavaScript framework that has recently gained a lot of popularity for its simple API and easier learning curve. In this post, we will learn how to use a web component in a Vue application.We will create a Vue CLI project and add a simple dropdown web component to the project. You can learn more about the Vue CLI at cli.vuejs.org.
Our dropdown is a simple web component I have built and published
at the npm package
web-component-essentials. Here is a clip of our dropdown web component.
Creating a Vue Project with the Vue CLI
For this example we will use the Vue CLI tool to generate a Vue project. The Vue CLI will provide all the tooling we need to get started building and running our application.
First, we need to install the Vue CLI via NPM. We can install the Vue CLI by running the following command:
npm install -g @vue/cli
Once installed we can create our project by running the following:
vue create my-app
This command will create a basic Vue project as well as installing any dependencies. Once installed we can install our dropdown by running the following:
npm install web-component-essentials --save
This command installs the dropdown package that we published in an earlier chapter. Once installed we can now import our dropdown into our Vue application. In the
main.js
we can add the following:
import Vue from 'vue' import App from './App.vue' import 'web-component-essentials' Vue.config.productionTip = false new Vue({ render: h => h(App) }).$mount('#app')
To run our Vue application, we can run the following command:
npm run serve
This command will start up our Vue app at
localhost:8080. Let's take a look at the
HelloWorld.vue component. Vue components use a single file style of organization. For example, Angular components have a TypeScript, HTML and CSS file. Vue components have a single file that contains all three parts of the component. We will start with the template first.
Property and Event Binding in Vue
Web components communicate primarily three ways, setting properties (input), emitting events (output), and accepting dynamic content between the element tag with content slots. The dropdown component in our example uses all three of these APIs.
// HelloWorld.vue <template> <div> <h1>VusJS Application using Web Components</h1> <p> {{show ? 'open' : 'closed'}} </p> <x-dropdown : Hello from Web Component in Vue! </x-dropdown> </div> </template>
We can see an expression that shows if the dropdown is open or closed,
{{show ? 'open' : 'closed'}}. On the dropdown component, we are using Vue's binding syntax. This binding syntax works with all HTML elements as well as custom elements from using web components. This template binding syntax is similar to the element binding syntax in Angular.
To bind to a property, we use the
: character. To bind a property to the dropdown title property, we write
:title="myTitle". In our Vue component, we have a
myTitle property that has its value assigned to the
title of the dropdown component.
To listen to events, we use the
@ character. Our dropdown has a single event
show. To listen to this event, we write
@show="log". This event binding will call the log method on our Vue component whenever the show event occurs.
Next, let's look at the Vue component JavaScript.
<script> export default { name: 'HelloWorld', data: function () { return { myTitle: 'project-vue', show: false } }, methods: { log: function (event) { console.log(event); this.show = event.detail; } } } </script>
The Vue component definition has data and method properties we want to bind on our Vue template. In our example, we have the two data properties,
myTitle and
show. We have a single method
log which we saw being bound to the
@show event.
If everything is hooked up correctly we should see something similar to the following in the browser:
Using web components allow us to share UI components between any
framework of our choice. VueJS is a great option to build JavaScript applications and works very well with web components out of the box.
Find the full working demo here!
|
https://dev.to/coryrylan/using-web-components-in-vue-41db
|
CC-MAIN-2019-43
|
refinedweb
| 714 | 64.61 |
Enter a login "username" & "password", get them, use WebAPI and convert them into JSON Object and display the result of JSON object in XAMARIN Android App.
please help me with this.
It is strange. But I never use it inside Toast. May be you can try with TextView? Or in Console? Just to check, because I do the same actions like you wrote, but in Console and everything is fine.
Answers
To convert string into JSON it is better to use Json.Net (). You can get this as Nuget Package. To create json from two strings, you need to create an object with two string fields and after that you can convert it into json-object. Json.Net can do it. You can find code samples here -.
Thanks for the hint @VladislavP but how do i display these content in a activity
In Activity or in View? Anyway you need a function that will get this data and show it where you need (View or just to use it in code). May be I don't understand you in right way, but I am not sure that it is too difficult to get this content and use inside Views.
Or do you mean that you need to show in TextView exactly JSON-structure?
In this case you can use string.Format() or something like this:
yourTextView.Text = $"{\n\"username\": {userData.userName}, \n\"password\": {userData.password} }";
when clicking a button CONVERT , it should convert the given username and password which present in details object
string json = JsonConvert.SerializeObject(details);
then view content in textview ? <---- Struggling to do
You wrote right variant. Like in example, that I showed you. TextView.Text = json.
Or what more problems?
Button convertButton = FindViewById(Resource.Id.ConvertButton);
details --> has the collection i need
but when i convert in json i'm getting --> "{}" <-- in the var json
var json = JsonConvert.SerializeObject(details);
Do you mean that "{}" is all that you get without any other data that is in details?
Yes, that is what I'm getting when i try to convert my object as JSON
It is strange. But I never use it inside Toast. May be you can try with TextView? Or in Console? Just to check, because I do the same actions like you wrote, but in Console and everything is fine.
I do this:
string dt = JsonConvert.SerializeObject(details);
byte[] dataBytes = Encoding.UTF8.GetBytes(dt);
I don't know if do you want send to api but this works
@felipe1902 No, not working
for your code it's still coming the same output as [{}] <--
strange, can you show your class credentials??
are you sure the command JsonConvert it's from newtonsoft?
I did the same code in another project it is working like charm but i don't know why it is not working in this project anyways thanks guy @VladislavP @felipe1902
post your code, we will try help you..
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using System.Collections;
using Newtonsoft.Json;
using static Android.Resource;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Javax.Xml.Validation;
namespace JObj
{
[Activity(Label = "JSon View", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
}
I think you can't show object json attributtes with toast, always will show {}, if do you want to see try with attributtes like
jsondetails.Usename
Yeah that's how i have tried, if you could see the commented codes.
You have to convert json data to string and then display
|
https://forums.xamarin.com/discussion/comment/284447
|
CC-MAIN-2020-10
|
refinedweb
| 586 | 77.43 |
The documentation can be something like this. I just added the last paragraph below. -Tak `M-x occur' Prompt for a regexp, and display a list showing each line in the buffer that contains a match for it. To limit the search to part of the buffer, narrow to that part (*note Narrowing::). A numeric argument N specifies that N lines of context are to be displayed before and after each matching line. Currently, `occur' can not correctly handle multiline matches. The buffer `*Occur*' containing the output serves as a menu for finding the occurrences in their original context. Click `Mouse-2' on an occurrence listed in `*Occur*', or position point there and type <RET>; this switches to the buffer that was searched and moves point to the original of the chosen occurrence. `o' and `C-o' display the match in another window; `C-o' does not select it. After using `M-x occur', you can use `next-error' to visit the occurrences found, one by one. *note Compilation Mode::. When the numeric argument N is 0 or negative the buffer `*Occur*' collects all the matched strings. When N is 0 the entire text matched is collected. When N is negative the text in the -Nth parenthesized expression in the regexp is collected. Thu, 04 Nov 2010 11:36:54 -0700: Tak Ota <address@hidden> wrote: > Thu, 4 Nov 2010 06:58:20 -0700: Stefan Monnier <address@hidden> wrote: > > > >> How about rename the command as collect-occur instead of > > >> collect-string and document it as next? > > > Wrong namespace. IMO, the name should *start* with occur (but Stefan > > > and Yidong are final authorities on that). > > > > Agreed, namespace cleanliness is one of my favorite forms of > > anal retentiveness. > > > > The way I see it, the suggested collect-string is a variant of occur > > where the result buffer contains none of the regexp matches's context. > > So it would make sense to integrate it very tightly with `occur', > > i.e. make M-x occur do the job of collect-strings for some particular > > value of its argument NLINES. Currently, NLINES is assumed to be > > a number and all values of that number have a useful meaning, so we'd > > have to add this new feature via a non-number value of NLINES. > > > > E.g. C-u M-x occur could do the collect-string thingy (which is still an > > incompatible change since some people may like to use C-u M-x occur to get > > 4 lines of context, but you can make omelets without breaking eggs). > > > > > > Stefan > > > > Now I am convinced. How about the change below? In conventional > occur zero or negative value for nlines is meaningless correct? We > can use that for collection purpose. i.e. C-u 0 M-x occur does the > collection of the matching pattern. C-u -1 M-x occur performs the > collection of the recorded pattern 1. > > -Tak > > (defun occur-1 (regexp nlines bufs &optional buf-name) > (unless (and regexp (not (equal regexp ""))) > (error "Occur doesn't work with the empty regexp")) > (unless buf-name > (setq buf-name "*Occur*")) > (let (occur-buf > (active-bufs (delq nil (mapcar #'(lambda (buf) > (when (buffer-live-p buf) buf)) > bufs)))) > ;; Handle the case where one of the buffers we're searching is the > ;; output buffer. Just rename it. > (when (member buf-name (mapcar 'buffer-name active-bufs)) > (with-current-buffer (get-buffer buf-name) > (rename-uniquely))) > > ;; Now find or create the output buffer. > ;; If we just renamed that buffer, we will make a new one here. > (setq occur-buf (get-buffer-create buf-name)) > > (if (or (null (integerp nlines)) > (> nlines 0)) > ;; nlines is not zero or negative so perform nomal occur > (with-current-buffer occur-buf > (occur-mode) > (let ((inhibit-read-only t) > ;; Don't generate undo entries for creation of the initial > contents. > (buffer-undo-list t)) > (erase-buffer) > (let ((count (occur-engine > regexp active-bufs occur-buf > (or nlines list-matching-lines-default-context-lines) > (if (and case-fold-search search-upper-case) > (isearch-no-upper-case-p regexp t) > case-fold-search) > list-matching-lines-buffer-name-face > nil list-matching-lines-face > (not (eq occur-excluded-properties t))))) > (let* ((bufcount (length active-bufs)) > (diff (- (length bufs) bufcount))) > (message "Searched %d buffer%s%s; %s match%s for `%s'" > bufcount (if (= bufcount 1) "" "s") > (if (zerop diff) "" (format " (%d killed)" diff)) > (if (zerop count) "no" (format "%d" count)) > (if (= count 1) "" "es") > regexp)) > (setq occur-revert-arguments (list regexp nlines bufs)) > (if (= count 0) > (kill-buffer occur-buf) > (display-buffer occur-buf) > (setq next-error-last-buffer occur-buf) > (setq buffer-read-only t) > (set-buffer-modified-p nil) > (run-hooks 'occur-hook))))) > ;; nlines is zero or negative integer perform collect-string > (with-current-buffer occur-buf > (setq nlines (- nlines)) > (fundamental-mode) > (let ((inhibit-read-only t) > (buffer-undo-list t)) > (erase-buffer) > (while active-bufs > (with-current-buffer (car active-bufs) > (save-excursion > (goto-char (point-min)) > (while (re-search-forward regexp nil t) > (let ((str (match-string nlines))) > (if str > (with-current-buffer occur-buf > (insert str) > (or (zerop (current-column)) > (insert "\n")))))))) > (setq active-bufs (cdr active-bufs)))) > (display-buffer occur-buf)))))
|
http://lists.gnu.org/archive/html/emacs-devel/2010-11/msg00141.html
|
CC-MAIN-2014-15
|
refinedweb
| 858 | 50.06 |
Subject: [Boost-bugs] [Boost C++ Libraries] #11930: huiller method is inaccurate
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2016-01-21 19:05:41
#11930: huiller method is inaccurate
----------------------------------------+---------------------------
Reporter: Charles Karney <charles@â¦> | Owner: barendgehrels
Type: Bugs | Status: new
Milestone: To Be Determined | Component: geometry
Version: Boost 1.58.0 | Severity: Problem
Keywords: area |
----------------------------------------+---------------------------
The following code illustrates a problem with the "huiller" strategy
for computing spherical areas. It computes the area of a sequence of
progressively skinny triangles. The relative errors in the computed
areas are much larger than they need be.
{{{#!c++
#include <iostream>
#include <cmath>
#include <boost/geometry.hpp>
namespace bg = boost::geometry;
typedef bg::model::point<double, 2,
bg::cs::spherical_equatorial<bg::degree> > pt;
int main() {
bg::model::polygon<pt, false, false> poly;
bg::read_wkt("POLYGON((0 45,0 -45,0 0))", poly);
double c = 0.014458780939650811;
std::cout << " area relerr" << "\n";
for (int i = 3; i <= 6; ++i) {
double h = std::pow(10.0, -i);
poly.outer()[2].set<0>(h);
double
area = bg::area(poly),
// Relative error in this estimate is 2e-11 for h = 0.001
area0 = h * c;
std::cout << area << " " << (area - area0)/(area0) << "\n";
}
}
}}}
Running this code gives
{{{
area relerr
1.44588e-05 -2.0871e-06
1.44594e-06 4.55941e-05
1.43961e-07 -0.00433739
0 -1
}}}
Discussion:
* Surely it's a bad idea to embed the algorithm name "huiller" into
the API. Computing spherical areas is really straightforward.
Users shouldn't need to worry about the underlying method. Maybe
"spherical_area" is a better name.
* In any case, you've misspelled the guy's name. It's either
"l'Huilier" or "l'Huillier" with two "i"s.
* Furthermore, you're needlessly blackening l'Huilier's name by
applying his formula for the area of a spherical triangle in terms
of its sides.
* The three-side formula is a terrible choice because if a + b is
nearly equal to c (as is the case in my example), the triangle is
badly condititioned.
* Much better is to use the formula of the area of a triangle in terms
of two sides and the included angle. See the last two formulas in
the Wikipedia article on
[
spherical excess].
This nicely reduces to the familar trapezium rule in the plane limit.
* This formula comes with a sign attached, so there's no need to
kludge a sign on afterwards as there is with the current
implementation.
* This formula together with an ellipsoidal correction is used by
[ GeographicLib] for
computing geodesic areas.
-- Ticket URL: <> Boost C++ Libraries <> Boost provides free peer-reviewed portable C++ source libraries.
This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:19 UTC
|
https://lists.boost.org/boost-bugs/2016/01/43985.php
|
CC-MAIN-2019-43
|
refinedweb
| 449 | 56.86 |
Commit 5b9553ab authored byBrowse files
Committed by
Linus Torvalds
checkpatch: make "return is not a function" test quieter
This test is a bit noisy and opinions seem to agree that it should not warn in a lot more situations. It seems people agree that: return (foo || bar); and return foo || bar; are both acceptable style and checkpatch should be silent about them. For now, it warns on parentheses around a simple constant or a single function or a ternary. return (foo); return (foo(bar)); return (foo ? bar : baz); The last ternary test may be quieted in the future. Modify the deparenthesize function to only strip balanced leading and trailing parentheses. Signed-off-by:
Joe Perches <[email protected]> Cc: Julia Lawall <[email protected]> Reviewed-by:Joe Perches <[email protected]> Cc: Julia Lawall <[email protected]> Reviewed-by:
Josh Triplett <[email protected]> Cc: Monam Agarwal <[email protected]> Cc: Greg KH <[email protected]> Signed-off-by:Josh Triplett <[email protected]> Cc: Monam Agarwal <[email protected]> Cc: Greg KH <gregkh@linuxfoundation 7 deletions
Please register or sign in to comment
|
https://source.denx.de/Xenomai/ipipe-arm64/-/commit/5b9553abfc97f923b99868a04c3b3d99a6014163
|
CC-MAIN-2021-31
|
refinedweb
| 186 | 61.53 |
Unity 5.5
Package downloads
Select the runtime platforms of your choice from the list below (the desktop runtime is included as standard) or, to install the full complement of runtime platforms, use the download assistant installer.
Unity Download Assistant (Win)
Unity Editor 64-bit (Win)
Unity Editor 32-bit (Win)
Windows Target Support - now part of Editor as default player instead of web player
Windows Store (.NET) Target Support
Windows Store (IL2CPP) Target Support
Samsung TV Target Support
Unity Download Assistant (Mac)
Mac Target Support - now part of Editor as default player instead of web player
Samsung TV Target Support
New to Unity? Get started
Release notes
5.5.0f3 Release Notes (Full)
System Requirements Changes
- OSX 10.8 support is deprecated and will be dropped in the near future. OSX 10.9 and above is therefore recommended.
- Samsung TV 2013 and 2014 support will be dropped in the near future.
Features
- Animation: Animation Window box tool. This allows far simpler moving, scaling, and even ripple editing (“r” hotkey) of keyframes in both Dopesheet and Curves.
- Audio: Added support for Microsoft Research Head Related Transfer Function (Spatial Sound) targeting Windows 10 and UWP. This HRTF solution can be used for any Windows 10 application and works best with VR/AR and head tracked headphones.
- Editor: High Detail view in the CPU Profiler Timeline. Shows all profiler samples without filtering.
- Editor: Native memory allocation profiling in CPU Profiler Timeline. Shows call stacks of native memory allocations.
- Editor: New selection highlighting in scene view. Instead of showing a wireframe a selection outline is now shown. This outline color can be configured in the preferences of Unity. In the gizmo / annotation window you can select if you would like this behavour, the old behaviour, or both.
- Editor: Option to run Cache Server locally for quick platform switching.
- Graphics: Added support for BC4,BC5,BC6,BC7 compressed texture formats, and RGBAHalf format. These formats are supported on PC (DX11+, GL4, Metal) and consoles (PS4, XboxOne).
- BC6H for high quality compressed RGB HDR textures.
- BC7 for high quality compressed RGB(A) textures.
- HDR Textures and Reflection Probes now default to FP16 for uncompressed, and BC6H for compressed textures on PC/console platforms.
- BC7 is chosen automatically by the Texture Importer for textures set up as "High Quality Compressed" on supported platforms (see Texture Importer documentation).
- Note: DX9 and Mac GL do not support BC6/BC7 formats. If a Texture is set as BC6H, it is automatically uncompressed to FP16. If a Texture is set as BC7, it is automatically uncompressed to RGBA8.
- BC4 and BC5 formats can be used manually for single and two-channel texture compression on PC/console platforms. These formats are available even on DX9.
- Graphics: Added support for cubemap arrays (CubemapArray C# class). Similar to Texture2DArray, this is a graphics feature that lets the GPU access a bunch of same size/format cubemaps as a unit, index into them when sampling, and other related tasks. Cubemap arrays are a desktop and console class feature, supported on DX10.1+/GL4.0+ on PC, and on PS4/XB1.
- Graphics: Linear color space is supported on Android with OpenGL ES 3.x and iOS with Metal.
- Graphics: New (Preview) LookDev editor window for viewing & validating meshes and materials in various lighting environments.
- Graphics: Unity splash screen tools.
- Particles: Added support for sending custom data to Particle System vertex Shaders.
- Particles: New Modules:
- Lights Module, for adding realtime lights to particles
- Noise Module, for adding Curl Noise to Particle Movement
- Trails Module, for rendering ribbonized trails behind particles
- Physics: New CapsuleCollider2D.
- Scripting: Built-in support for opening scripts in Visual Studio Code as an external script editor on Windows and macOS. Unity will now detect when Visual Studio Code is selected an external script editor and pass the correct arguments to it when opening scripts from Unity and setup a default .vscode/settings.json with file excludes, if it does not already exist.
- Shaders: Per-rendertarget blend modes. New shader syntax: "Blend N Src Dst", "BlendOp N Op", "ColorMask Mask N", where N is the render target index (0..7). This feature works on DX11/12, GLCore, Metal, PS4.
- VR: HoloLens support graduated from the Technical Preview!
- VR: In-Editor holographic emulation.
- Core: Using Object.Instantiate(Object, Transform) will now use the Object position as the local position by default. This is a change from the 5.4 behaviour, which used the Object position as world.
- Editor: Time.deltaTime now updates in the Editor for any script marked with [ExecuteInEditMode], or any MonoBehaviour that has runInEditMode set to true.
- OpenGL: Legacy desktop OpenGL2 support has been removed. It had already been removed as the default option in Unity in 5.3, and deprecated in Unity 5.4. This only affects Mac & Linux.
- Scripting: EditorJsonUtility now serializes object references by assetGUID/fileID rather than InstanceID, making the serialized data stable across Editor sessions.
- Shaders: DX9 half-pixel offset adjustments are now done at Shader compilation time. This means that shaders no longer need to do any UNITY_HALF_TEXEL_OFFSET checks, and any possible C# code for coordinate adjustment no longer needs to happen on DX9. However, vertex Shader constant register #255 (c255) is now reserved by Unity, and all vertex shaders get two instructions automatically added to do the adjustment.
- WebGL: Removed support for loading LZMA compressed AssetBundles, as LZMA decompression is too slow for WebGL.
Changes
- Editor: Building a player will now fail if the project does not build in the Editor.
- Editor: Reflection Probe: "Probe Origin" has been renamed to "Box Offset", and "Size" to "Box Size" in the Inspector UI.
- Editor: Removed fading/lerping behaviour when dragging/docking views, for a cleaner and less visually confusing UI.
- GI: Deprecated the directional specular lightmap mode in Unity 5.5, since it will disappear in Unity 5.6 (as part of the lighting modes functionality).
- Graphics: A fatal error is now shown if the Unity player is forced to run with a graphics API that it wasn't built for in the Editor.
- Graphics: Removed logic that used guesswork to downscale shadow resolution based on how much free VRAM was available at the time.
- Graphics: Rendering Path settings have been moved from Project Settings > Player to Project Settings > Graphics.
- Graphics: The default uncompressed texture format is now RGBA32 on all platforms, and the default format for new Texture2D script API. Previously, ARGB32 was the default on some platforms, but RGBA32 is better because it needs less color channel re-ordering at Texture upload time.
- Graphics: Warnings are now shown when a Renderer that statically batched is going to be rendered instanced.
- Physics: The breakForce reported by the OnJointBreak callback is now the original breakForce, regardless of whether the Joint was disabled and re-enabled during the callback cycle.
- Physics: The physics system now rejects Meshes containing non-finite vertices.
- Profiler: User profile markers in scripts now show in platform-specific profiling tools even when the Unity profiler is not running.
- Samsung TV: Support for 2013 and 2014 Samsung TVs has been dropped. Deploying to these two years of TV no longer works.
- VR: Oculus Touch Controllers and Oculus Remote now present themselves as standard joysticks.
- VR: OpenVR controllers now present themselves as standard joysticks.
- WebGL: asm.js code is now written in a separate file for normal JS, which allows for better memory optimizations in Firefox.
Improvements
- Android: Enabled TLSv1.1 and TLSv1.2 for JellyBean and KitKat devices.
- Android: Enhanced big.LITTLE core detection. This fixes core detection on Parker.
- Android: IL2CPP: Stripping of symbols and debug info is now enabled by default. Development builds still have symbols, which makes for a slightly larger binary.
- Android: IL2CPP: The full debug version of IL2CPP libraries are now stored in Temp/StagingArea/Il2Cpp/Native.
- Android: Symbols for release libraries are now available in PlaybackEngines/AndroidPlayer/Variantions/*/Release/Symbols.
- Animation: Added a new default ClipAnimationMaskType "None" to the Animation Importer. Use this value when you do not need a mask.
- Animation: Implemented Reset for BlendTrees.
- Animation: Import avatar improvements: A warning is now generated when importing avatar configurations with hierarchies that do not match properly. These configurations continue to work, but do need to be updated with a proper avatar configuration. This update also includes improvements to the default auto-mapping.
- Animation: In the Clip Importer, AvatarMask is now set to "None" by default when importing new FBX files.
- Build Pipeline: AssetBundles now work with engine code stripping. A custom player build can understand which AssetBundles will be loaded by the player at run time, and determine which parts of the engine code those AssetBundles need to preserve. See BuildPipeline.BuildPlayer method change for more information.
- Build Pipeline: Optimized the build pipeline so that AssetBundles which contain Scene files don't need to recompile the scripts every time. This results in a much quicker build process.
- Cache Server: Upgraded the node.js version used by the Cache Server to version 0.12.7.
- Collaboration: Various bug fixes and UI improvements.
- Editor: Added 'Discard changes' in Scene context menu in the Hierarchy. This reloads selected modified Scenes from disk.
- Editor: Added support for resizing the height of the Preferences window.
- Editor: Added undo support for Sorting Layers.
- Editor: Added Unity version to the main Unity Editor window title bar, making it easy to see which Unity version you currently have open.
- Editor: Area lights now indicate their effective range in the Inspector.
- Editor: EditorGUIUtility.ObjectContent now adds type information to the text string as shown for ObjectFields. For example: "Concrete (Texture2D)" instead of "Concrete".
- Editor: In SceneView, the wireframe is now hidden on objects with the hideInHierarchy flag. Previously it would still be visible when the object's parent was selected.
- Editor: It is now possible to dock views to the tops of windows and other views. Previously only left, right and bottom were possible.
- Editor: The Game View now has the option to emulate low resolution for aspect ratios when on a retina monitor, using a checkbox at the top of the Aspect Ratio/Resolution menu. This update applied to macOS-only, because retina support is currently macOS-only.
- Editor: Unity now treats quotes in the .exe path in the same way the Windows command line does.
- Editor: Windows Editor now remembers the directory where a project was last created, and defaults to that location rather than the directory of the last opened project.
- GI: MaterialPropertyBlocks are now applied for Realtime GI Meta pass rendering.
- Graphics: Added a Texture Mode to the Line/Trail Renderers, to control whether the texture repeats or stretches.
- Graphics: Added Graphics.DrawMeshInstanced and CommandBuffer.DrawMeshInstanced API, allowing instanced draws without the overhead of creating thousands of renderers.
- Graphics: Added RenderTexture.GenerateMips script API for manual control over mipmap generation. Renamed existing RenderTexture.generateMips property to autoGenerateMips.
- Graphics: Added the ability to batch Renderers of different LOD fade values together by using the "lodfade" option in the instancing_options directive.
- Graphics: Command buffers attached to Lights are now visualised in the Inspector, and buttons have been added for removing each/all of them.
- Graphics: GPU Instancing: Added support for Android with OpenGL ES 3.0 or newer, and iOS/macOS with Metal. Note that instancing is disabled on Android devices with GLES3.0 Adreno GPUs.
- Graphics: GPU Instancing: Implemented SpeedTree instancing. Light Probes are still not allowed.
- Graphics: Improve shadows precision for large game worlds. Use reverse-float depth buffer for improved depth buffer precision on modern GPUs. Particularly improves directional light shadowing for large view distances.
- Graphics: Improved in-editor graphics emulation:
- Metal setting added, used by default on iOS/tvOS (instead of previous GLES2.0 setting).
- OpenGL ES 3.0 setting added, used by default on Android (instead of previous GLES2.0 setting).
- WebGL 1 and WebGL 2 settings added; WebGL1 used by default on WebGL (instead of previous GLES2.0 setting).
- Shader Model 4 setting added, available on Standalone/Windows Store.
- Graphics: Improved Line/Trail Renderer handling of corners and gradients.
- Graphics: Improved LODGroup component UI:
- The sliding Camera icon is now aware of the global LOD bias value, and works accordingly.
- The "Recalculate Bounds" button is now only enabled when clicking it will result in a change.
- Graphics: Metal (iOS/macOS) can now render into slices of 3D and 2DArray Textures.
- Graphics: Metal: Switched the shader backend to HLSLcc. This is the same compiler used for OpenGL Core and ES3.0. Now it enables instancing, and soon compute shaders on Metal.
- Graphics: Multi-Scene occlusion culling now works correctly. Culling data has been extracted to a separate Asset, and can be baked/reloaded with multi-Scene setups. Note that the data is stored relative to the active Scene, and is loaded correctly when loading any Scene or group of Scenes that reference it.
- Graphics: Shader.globalMaximumLOD is now restored after exiting Play Mode.
- Graphics: Static batch rendering is now faster, and uses fewer draw calls in many cases.
- IL2CPP: Reduce the binary size and build time for projects which make use of many C# attributes.
- IMGUI: The Event.Use() function logs a warning if the event type is Repaint or Layout.
- iOS: Added a way for the user to retrieve Game Center authentication error strings.
- iOS: Added an option for users to disable the filtering of emojis in the iOS keyboard via the trampoline code.
- iOS: Fixed audio ducking for iOS platform (background audio applications muting).
- iOS/tvOS: Relative symlinks are now used for plug-ins when building to a related folder. Previously, only absolute symlinks were used.
- iOS/tvOS: Significantly reduced the size of shipped static libraries.
- Occlusion Culling: Unity now supports multi-Scene occlusion culling. Scenes built concurrently will be computed as expected.
- OSX/iOS Metal: Added -force-metal switch to force Metal rendering on OSX/iOS.
- Particles: Added "Show Bounds" to Particle System UI. This shows the world and local AABB for the system.
- Particles: Added a new Render mode to make particle billboards face the eye position. This is good for VR rendering.
- Particles: Added a new Shape Module option to rotate particles to face their initial direction of travel.
- Particles: Gradients now support a fixed color mode, where no blending is performed. This is useful when users want to define a simple list of possible colors to be chosen from.
- Particles: Gravity Modifier can now be a curve over time.
- Particles: Improved the Particle System curve editor so that it now supports wrap modes, and improved selection and editing of keys.
- Physics: Added more performance metrics to the Physics profiler.
- Physics: All Effector inspector editors now use animated roll-outs to group properties.
- Physics: Exposed Physics.queriesHitBackfaces. This is disabled by default, so all physics queries do not detect hits with backface triangles. Previously, some queries would detect and some wouldn't, which was inconsistent.
- Physics: Physics engine updated from PhysX 3.3.1 to PhysX 3.3.3.
- Physics: Physics2D settings now have the option to show Collider2D AABB in the Gizmo roll-out.
- Physics: Rigidbody2D and Collider2D Inpsector editors now have an "Info" roll-out showing useful information.
- Physics: Rigidbody2D now accepts a PhysicsMaterial2D, which is then used for all attached Collider2Ds that don't specify their own.
- Plugins: You can exclude specific platforms when "Any Platform" is selected. This allows you to set plug-in compatibilities on any platform except your selected specific platform. Added additional API to PluginImporter.
- SamsungTV: Added support for deploying to multiple Samsung TVs at once. Separate TV IPs with a forward slash to do this.
- Scripting: EditorJsonUtility now allows any object type to be passed in for serialization, not just UnityEngine.Object types. This means vanilla C# types can take advantage of the object reference serialization behaviour.
- Scripting: Improved the performance of System.IO.StringReader.ReadLine.
- Scripting: JsonUtility.ToJson is now faster and uses less temporary memory.
- Scripting: On macOS, the Unity Editor no longer starts BugReporter on Null exceptions when in batch mode.
- Scripting: Upgraded C# compiler to Mono 4.4. The new compiler still targets C# 4 and .NET 3.5, but provides better performance and many bug fixes.
- Serialization: Added new scripting class attribute 'PreferBinarySerialization' which allows developers to hint Unity that a ScriptableObject derived type prefers to use binary serialization regardless of project's asset serialization mode.
- Serialization: The serialization depth limit warning now prints the serialization hierarchy that triggered the warning.
- Services: Game Performance service; added option to prevent exceptions that occur in Play mode (in the Editor) from being reported.
- Shaders: Added a Render Queue setting to the Material UI. Previously this was a script-only setting on the Material.
- Shaders: Fixed various half-pixel offset issues when using Direct3D 9. Rendering now exactly matches other platforms (such as DX11, OpenGL).
- Shaders: Improved exception messages when passing invalid arguments to the ComputeShader constructor.
- Shaders: Improved memory usage for large Shaders compiled for multiple APIs. Only the active API's data will be decompressed in the player.
- Shaders: Improved usability of "Show compiled code" for Shaders. Now compiled Shader variants are grouped together in a more useful way.
- Shaders: Increased the number of allowed shader keywords to 256 (up from 128). Optimized related parts of the code, so it's often actually faster now.
- Shaders: Renamed variables and cleaned code in UnityStandardBRDF.cginc. See 5.5 upgrade guide for details.
- Shaders: Shaders are now exported to the Unity player completely in binary. There is no Shader text string and parsing in run time.
- Shaders: When Shader compilation fails and the reason is unknown, the error output from the platform Shader compiler is now shown in the error message.
- Terrain: Terrain LOD pre-computation is optimized and now runs faster (specifically, TerrainData.SetHeights and setting the size property are faster now).
- Unity Ads: Updated Unity Ads to v2.0.5. Fixed crashes related to calling user-defined callbacks from outside the main Unity thread.
- Version Control: Major improvements to memory and CPU usage.
- Visual Studio: Added cancel button to "Opening Visual Studio" progress dialog.
- VisualStudio: COM is no longer used to launch VisualStudio. This results in a faster VisualStudio startup time.
- VR: GUI elements now work with single-pass stereo rendering
- VR: UnityEngine.VR.InputTracking.GetLocalRotation() and UnityEngine.VR.InputTracking.GetLocalPosition() can now be used to query the position and orientation of Oculus Touch and HTC Vive controllers.
- VR: Updated the native plug-in support for VR devices. Plug-ins in user projects override native VR plugins when used.
- WebGL: Aded the option to use Brotli compression instead of Gzip.
- WebGL: Rebuilds which don't change code now cache the complete JS build, resulting in much faster iteration times.
- WebGL: Reduced the size of release builds by stripping away duplicate functions.
- WebGL: WebGL 2.0 is now enabled by default for new projects.
- Windows Standalone: Added the "Copy PDB files" option to the Build Settings window. PDB files are large, but useful for profiling or crash debugging.
- Windows Standalone: Windows Standalone applications can now correctly run in low integrity mode.
- Windows Store: Added a "Copy References" option in the Build Settings window. This allows for generated solutions to reference Unity files from the Unity installation folder, instead of copying them to an exported folder. This can save up to 10 GB of disk space. Note that you can't copy the exported folder to another PC, because there is a dependency on Unity's installation folder.
- Windows Store: Added new option for input handling in XAML-based applications: pointer input can now be recieved from SwapChainPanel. This is an alternative to independent input sources.
- Windows Store: Added partial hardware cursor support. The default cursor set in PlayerSettings acts as a hardware cursor. Cursors set at runtime still act as software cursors. See Cursor documentation for more information.
- Windows Store: Added the concept of "target device type", which allows you to target only one family of devices (such as PC, mobile or HoloLens). This enables better resource optimization for a particular device type. See documentation on EditorUserBuildSettings.wsaSubtarget for more information.
- Windows Store: Assembly C# projects are now generated next to the main solution in the GeneratedProjects folder.
- Windows Store: Expanded UnityEngine.WSA.Cursor.SetCustomCursor. If you pass 0 to this function, it will restore the cursor to arrow icon.
- Windows Store: New implementation for TouchScreenKeyboard on UWP. XAML and D3D apps are now supported, as well as IME input. To turn on older implementation, pass the command line argument -forceTextBoxBasedKeyboard.
- Windows Store: Windows Store platform no longer appears in the Build Settings window if the Editor is not running on Windows.
API Changes
- AI: NavMesh related types are moved from namespaces UnityEngine and UnityEditor to UnityEngine.AI and UnityEditor.AI.
- Asset Pipeline: Added an offset argument to the AssetBundle.CreateFromFile and AssetBundle.LoadFromFile methods. (764802)
- Asset Pipeline: Added callback events for PackageImport for start, success, failure and cancellation.
- Asset Pipeline: EditorApplication.SaveAssets has been deprecated; use AssetDatabase.SaveAssets instead. The ScriptUpgrader should fix existing code automatically.
- Asset Pipeline: New argument to the BuildPipeline.BuildPlayer method to support Asset Bundle engine code stripping.
- Editor: Add MonoBehaviour.runInEditMode to set a specific instance to run in edit mode.
- Editor: Added Handles.DrawWireCube to draw cubes in the same way as Gizmos.DrawWireCube.
- Editor: Added toggle for preventing/allowing cross scene references from the Editor UI (see EditorSceneManger.preventCrossSceneReferences).
- Graphics: Added array property getters (e.g. GetFloatArray) for Material, MaterialPropertyBlock and Shader class.
- Graphics: Added bool SystemInfo.usesReversedZBuffer to be able to know if the platform is using a "reversed" depth buffer.
- Graphics: Added BuiltinRenderTextureType.ResolvedDepth enum so command buffers can use it.
- Graphics: Added CommandBuffer.SetGlobalBuffer.
- Graphics: Added Light.customShadowResolution, QualitySetting.shadowResolution and LightShadowResolution enum to scripting API to make it possible to adjust the shadow mapping quality in code at run time on a per-light basis. (805056)
- Graphics: Added List overloads for array property setters for Material, MaterialPropertyBlock, Shader and CommandBuffer class.
- Graphics: Added property getters (e.g. GetGlobalFloat) for Shader class.
- Graphics: Added QualitySettings.shadows and QualitySettings.softParticles to the scripting API. (805056)
- Graphics: BillboardAsset can now be constructed from script.
- Graphics: Native code plugins can access underlying graphics API Mesh & ComputeBuffer data. New script APIs for that: Mesh.GetNativeIndexBufferPtr, Mesh.GetNativeVertexBufferPtr, ComputeBuffer.GetNativeBufferPtr.
- Graphics: SystemInfo.supportsRenderTextures and SystemInfo.supportsStencil always return true now (all platforms have them).
- HoloLens: Removed the preview mode parameter from PhotoCapture.StartPhotoModeAsync.
- HoloLens: Spatial mapping component API changes:
- The "Custom Render Setting" property is now "Render State".
- The "Custom Material" render setting is now "Visualization".
- "Custom Material" is now "Visual Material".
- "volume" property is now "volumeType".
- "sphereRadiusMeters" is now "sphereRadius".
- "boxExtentsMeters" is now "halfBoxExtents".
- "lod" is now "lodType".
- Particles: Added IsEmitting property.
- Particles: Exposed the Maximum Particle Timestep (maximumParticleDeltaTime) to the public API.
- Particles: Fully exposed main particle properties to script.
- Particles: Particles Stop function now takes an enum to stop emitting or stop emitting and clear.
- Physics: PlatformEffector2D now has a rotationalOffset property to adjust the local up (surface) vector.
- Physics: Rigidbody2D component now has a bodyType property that allows selection of Dynamic, Kinematic or Static bodies.
- Physics: The following properties have been renamed:
- Physics.solverIterationCount to Physics.defaultSolverIterations
- Physics.solverVelocityIterationCount to Physics.defaultSolverVelocityIterations
- Rigidbody.solverIterationCount to Rigidbody.solverIterations
- Rigidbody.solverVelocityIterationCount to Rigidbody.solverVelocityIterations
- Physics2D: Physics2D.CapsuleCast and Physics2D.OverlapCapsule API.
- Profiler: Profiler class moved from UnityEngine namespace to UnityEngine.Profiling.
- SceneManager: Added SceneUtility class with scene path to build index conversion methods and added SceneManager.GetSceneByBuildIndex.
- SceneManager: Added UnloadSceneAsync API which can be called anytime unlike UnloadScene.
- SceneManager: UnloadScene has now be marked deprecated and will throw an exception if called at illegal times. UnloadSceneAsync should be used instead (762371)
- Scripting: Add Application.Unload to unload Unity from memory without exiting the application.
- Scripting: Add disposable scope helper for Begin/EndChangeCheck.
- Scripting: Add missing generic overloads for Object.Instantiate.
- Scripting: Added global define UNITY_5_5_OR_NEWER, which can be used for conditionally compile code that is compatible only with Unity 5.5 or newer.
- Scripting: EditorJsonUtility methods now accept any object type, not only UnityEngine.Object subclasses.
- Substance: Added ProceduralMaterial.FreezeAndReleaseSourceData() function. This makes the material immutable and releases some data to decrease memory footprint.
- Terrain: Added Terrain.SetSplatMaterialPropertyBlock and Terrain.GetSplatMaterialPropertyBlock API that allows per-terrain shader properties to be used for rendering the terrain.
- Terrain: Added Terrain.treeLODBiasMultiplier for adjusting LOD bias for SpeedTree trees.
- Terrain: Added TerrainChangedFlags for use with the OnTerrainChanged message.
- Terrain: Added TerrainData.bounds for retrieving the local bounding box of terrain heightmap data.
- Texture Importer: Added GetAutomaticFormat API method to Texture Importer.
- Tizen: Add UnityEngine.Tizen.Window.evasGL to retrieve a pointer to the native Evas_GL object used by Unity to render.
- UI: Added rootCanvas property to Canvas. (782957)
Fixes
- 2D: Fix potential hang when rendering Sprites with large number of vertices.
- 2D: Fix SpriteEditorWindow not showing selected texture after exiting play mode. (782177)
- 2D: Fix SpriteEditorWindow polygon mode bugs related to the change shape popup. (782158, 782212, 782229)
- Android: Don't decompress RGB ETC2 textures on devices that support it when using OpenGL ES 2.0. (784866)
- Android: Fix for potential crash when Video can not be prepared. (788486)
- Android: Fix Java NoSuchFieldError exception on Gingerbread OS devices.
- Android: Fixed an issue where RenderTexture content would be lost on pause/resume. (749983)
- Android: Fixed an issue where SystemInfo.deviceUniqueIdentifier would return an empty string on some x86 devices.
- Android: Fixed crash bug related to LocationService. (757111)
- Android: Fixed input issues after tapping the splash screen. (825716)
- Android: Fixed startup crash on Adreno GPUs when protected graphics memory is used. (832025)
- Android: Fixes an issue where UI touch input would be ignored. (776437)
- Android: Handle '#' in project paths. (743640)
- Android: Removed permissions added by checking "Split Application Binary".
- Android: Show name of missing library on export failure.
- Android: Vibrate() is now asynchronous. (777556)
- Animation: Added more feedback to the AvatarMaskInspector for cases where the transform mask is empty. (805945)
- Animation: Added non-alloc version of Animator.GetCurrent/NextAnimatorClipInfo.
- Animation: Added visual feedback to Transform animation curves when part of a positon/rotation/scale is not explicitly animated. (778046)
- Animation: Added warning icon in animator controller to inform user that a base layer with humanoid motion should preferably not have an avatar mask. (823794)
- Animation: Animator.CrossFade is now interruptable like Animator.CrossFadeInFixedTime. (798560)
- Animation: Fix crash when changing AnimationControllerPlayable during runtime with Constant animation curves. (805887)
- Animation: Fixed a case where StateMachineBehaviours on preview assets would be run (804909)
- Animation: Fixed a crash when building a clip with an invalid curve. (818668)
- Animation: Fixed a crash when deleting a layer with an index smaller than the layer on which other layers are synchronized. (820546)
- Animation: Fixed a crash when setting a null AnimatorController on an Animator. (821384)
- Animation: Fixed a crash while building SelectorTransitionConstant. (825310)
- Animation: Fixed an issue where Animator.SetTrigger was not forwarded to all AnimatorControllers in a playable graph. (823880)
- Animation: Fixed an issue where events could be fired more than once when the framerate was exceedingly low. (825132)
- Animation: Fixed an issue where objects that should have been culled were still animated. (816950)
- Animation: Fixed an issue whereby empty clips would be rebuilt repeatedly. (791563)
- Animation: Fixed animation window breaking because of unhandled AmbiguousMatchException in animation events. (801649)
- Animation: Fixed animation window breaking when resized to small sizes. (802394)
- Animation: Fixed case of duplicate Euler angle properties on the animation window. (820494)
- Animation: Fixed case of leaking animation clips in Animation Component. (826304)
- Animation: Fixed case of nested property game object name not showing in the animation window when selecting from the project folder. (823679)
- Animation: Fixed crash when calling Animator.GetCurrentAnimatorStateInfo during an interrupted transition. (802327)
- Animation: Fixed crash when calling Animator.Play on a disabled GameObject during playback. (812440)
- Animation: Fixed crash when manually destroying an AnimatorState. (810871)
- Animation: Fixed display of invalid AnyState transitions. (807592)
- Animation: Fixed erroneous "Missing" tag displayed in Animator.Motion curves for generic animation in animation window. (805254)
- Animation: Fixed first rotation key frame not properly set when recording in animation window. (811173)
- Animation: Fixed HumanPoseHandler not supporting fingers. (788540)
- Animation: Fixed inability to input negative X values in the floating curve editor. (817689)
- Animation: Fixed layers overriding the base layer's rootmotion event when no rootmotion on layers. (785608)
- Animation: Fixed null exception when deleting property in Animation Window. (802229)
- Animation: Fixed playable not updating when animator controller is already set in animator. (788662)
- Animation: Fixed property removal not undoing Euler value hints when recording animation. (817356)
- Animation: Fixed renaming of grand children properties in animation window. (789410)
- Animation: Fixed slow data invalidation in the animation window. (808124)
- Animation: Fixed stack overflow exception in the transition inspector, caused by looping transitions. (817057)
- Animation: Fixed StateMachineBehaviour.OnEnable/OnDisable been called in editor while not in play mode.
- Animation: Fixed transitions not being previewable with objects imported with Copy Avatar From Other.
- Animation: Fixed vertical scrollbar in dopesheet editor out of sync with animation window hierarchy. (803345)
- Animation: Prevent Animator to disable themselves while being animated. (795444)
- Animation: Prevent from creating States and StateMachine with a "." in their name (803366)
- Animation: Removed wrong framing applied when changing Curve Editor property selection in Animation Window. (802226)
- Animation: Updated hash code for editor curve binding to reduce likelikood of collisions. (816028)
- Asset Bundles: Fixed editor not taking into account #if UNITY_EDITOR defines around fields in scripts when building asset bundles, thus causing deserialization issues in the player (800200)
- Asset Bundles : Fixed memory leak when using AssetBundle.LoadFromMemory (756652)
- Collaboration: Various bug and UI fixes.
- Debugger: Fix rare crash when setting breakpoints. (735335)
- Debugger: Prevent debugger from prematurely interrupting calls to Monitor.Wait. (772064)
- Editor: Add missing System.Runtime.Serialization reference to generated .csproj files. (599678)
- Editor: Add support for the GZipStream class in the editor and standalone players. (569612)
- Editor: After changing Graphics API some player settings editor UI elements do not respond correctly. (752218)
- Editor: Edit -> Select All menu does not work on Windows (Ctrl+A works). (370257)
- Editor: Editor window title was only updated after changing graphics emulation, leaving it a step behind when changing build targets. (795797)
- Editor: File Menu entry is 'Save Scenes' now (was 'Save Scene') since all modified scenes are saved.
- Editor: Fix case where no assets were shown in the project browser after rename. (748103)
- Editor: Fix clicking Player Settings button in Build Settings window not giving focus to inspector. (720992)
- Editor: Fix crash when dragging a prefab instance from one scene to another scene (if the prefab has a game object parent). (769764)
- Editor: Fix double icon in macOS dock area when editor is relaunched to creating or opening a new project. (769784)
- Editor: Fix dragging a cubemap onto a scene view doesn't generate skybox material, duplicates file twice instead. (742896)
- Editor: Fix errors in console when opening project with no longer supported build target selected; active platform will be switched to Standalone instead. (790514)
- Editor: Fix icon tab in PlayerSettings doesn't stay open. (831307)
- Editor: Fix inspector debug mode array editing. (773260)
- Editor: Fix missing context menu on header of material inspector. (796924)
- Editor: Fix poor performance when previewing some FBX models. (784892)
- Editor: Fix to make foldouts in internal inspectors behave like property fields. (784939)
- Editor: Fix to make validation for Delete asset menu items more consistent. This for instance prevents the delete option from being displayed when not applicable. (581887)
- Editor: Fix unneccessary reimporting of audio files when switching platforms. (782188)
- Editor: Fix white skin showing in Preferences window options list when dark skin was set. (732880)
- Editor: Fixed a possible memory corruption when performing undo/redo with a malformed undo stack.
- Editor: Fixed Account Help link in editor launcher. Now points to Account Help instead of Unity general help. (784432)
- Editor: Fixed case of blank/grey webviews (e.g. asset store) in the main window under macOS 10.12.1. (842708)
- Editor: Fixed case of RenderTexture inspector format popup missing ARGB4444 and determining ARGB1555 incorrectly. (832867)
- Editor: Fixed case of TextEditor caret position being reset after domain reload. (821758)
- Editor: Fixed crash that could occur when user unloads a scene immediately after starting an asynchronous load of the scene. (842396)
- Editor: Fixed crash when duplicating a game object which has a name that is all numbers and a right parenthesis e.g. "10)". (817928)
- Editor: Fixed exceptions in corner cases when closing tabs for editor windows. (813333)
- Editor: Fixed issue that could result in a crash when doing copy/paste between gradient fields. (711487)
- Editor: Fixed issue whereby the name of a newly-created asset would be displayed in the wrong case occasionally. (536739)
- Editor: Fixed redo of selection only restoring selection to previously active game object. (775865)
- Editor: Fixed RenderTexture preview in Mac/Linux editor. (498769)
- Editor: Fixed Scene View filtering not always getting correctly cleared which could cause previously filtered objects to get picked when they shouldn’t be.
- Editor: Re-instated '*' and '?' in the project browser search string splitter list. (771577)
- Editor: Same shortcut key can be set to multiple tools. (374335)
- Editor: Several tooltips were not working across the editor. (783770)
- Editor: The OnGeneratedCSProjectFiles callback will now be triggered when using Visual Studio. (789883)
- Editor: Will not reference .NET 4.x assemblies when compiling scripts for the Editor even if the settings allow it, Editor can only understand assemblies targeting .NET 3.5 or lower (777750)
- GI: Fixed case of GI being overridden by bad values from cache after using meta pass for emission. (741304)
- GI: Fixed Defult-Medium parameter in the lighting window to appear as not viewable. (762159)
- GI: Fixed issue where backface tolerance was not applied when baking lightmap with Final Gather. (733421, 792579)
- GI: Renamed LightmapEditorSettings.resolution to realtimeResolution. (753022)
- Graphics: Added SetFloatArray and related functions to Material class, to match the functions in MaterialPropertyBlock. (795553)
- Graphics: Added Texture conversion to RenderTargetIdentifier, so that CommandBuffer.SetGlobalTexture now accepts Textures.
- Graphics: Avoid creating textures with unsupported formats, if uses tries to create one without checking SystemInfo.SupportsTextureFormat first. (786229)
- Graphics: Disabled instancing for renderers that use lightprobes or lightmaps, in order to optimize GPU performance. (843125)
- Graphics: Ensure that unsupported wrap or filter modes aren't set on textures (e.g. linear filtering for floating point textures on platforms that can't do that). (778188)
- Graphics: Fix a crash if MaterialEditor.GetMaterialProperties is called with a null in the list of materials. (764995)
- Graphics: Fix crash when user attempts to SetPixel and Apply onto a Texture2D with an zero width or height. (789600)
- Graphics: Fixed a case where the editor could get out of sync with what graphics APIs were enabled and build a player without the matching shaders. (792541)
- Graphics: Fixed an issue where recalculating LOD bounds won't dirty the scene and record an undo. (808278)
- Graphics: Fixed anisotropic filtering setting sometimes going wrong for uploaded textures. (814501)
- Graphics: Fixed case of custom LineRenderer animation vertices being inverted occasionally. (832043)
- Graphics: Fixed case of Light Probe Proxy Volumes gizmos not rendering correctly. (836787)
- Graphics: Fixed case of LineRenderer setPositions resulting in an "index out of bounds" error. (820738)
- Graphics: Fixed case of Shader.SetGlobalVector/SetGlobalMatrix and CommandBuffer equivalents not being able to set some of the global properties (the "built-in" ones).
- Graphics: Fixed changing shader emulation or shader hardware tier emulation keeping around an extra menu separator each time. (795700)
- Graphics: Fixed directional light shadows not working properly with some non-standard projection matrices. (668520)
- Graphics: Fixed error messages from static batching code where different types of renderers share the same material.
- Graphics: Fixed issue where instantiating non-readable texture crashes in Texture2D awake. (843287)
- Graphics: Fixed mesh not properly disappearing if deleting the MeshFilter component. (757838)
- Graphics: Fixed RenderTexture mipmap generation on Metal when multiple render targets are used.
- Graphics: Fixed shadow pancaking for Directional shadows. (800737)
- Graphics: Fixed tree billboard batching when rendering a large number of billboards. (836486)
- Graphics: If Graphics.SetRandomWriteTarget is called with an out of range index, an exception is thrown instead of crashing. (766695)
- Graphics: Introduced check to verify that camera is still valid to render after OnPreRender callback. (826844)
- Graphics: Protected against some thread-unsafe code inside shader property name handling. (794400)
- Graphics: Renderers now are not culled by a disabled LODGroup.
- Graphics: Semitransparent shadow casters now take Fresnel transparency into account better. (667609)
- Graphics: TreeCreator; fixed errors when branch length is zero. (468942)
- Graphics: When changing shader hardware tier emulation, only reload shaders (not textures/RTs) to stop reflection probes breaking. (755072)
- Graphics: When making a RenderDoc capture from editor UI, make sure to include the whole frame including user script updates. (762795)
- IL2CPP: Improve error message when link.xml file specifies assembly not referenced in project. (719650)
- IL2CPP: Provide a useful error message when an interface cannot be found on a class because it was not AOT compiled. (798625)
- IL2CPP: WebGL/iOS: UI module will no longer depend on and require Physics and Physics2D modules. (788244)
- iOS: Fix to adapt font fallback order to Korean and Chinese locales where applicable. (821645)
- iOS: Support more than one pending game center user callback. (755388)
- Linux: Fix anti-aliasing in various window configurations.
- Linux: Fix repeated play/stop/pause with WebCamTexture. (780810)
- Linux: Sanitize company and product locations when creating directories for preferences. (763625)
- macOS: Fix to respect requested framerate in batch mode. (702370)
- Mono: Fix Thread.MemoryBarrier implementation on ARM architecture. (810451)
- Mono: Fix to prevent floating point operations from returning incorrect values when a managed debugger is attached. (836825)
- Mono: Improve call stack walking on 64 bit Windows. (809003)
- MonoDevelop: Disabled Git and Subversion add-ins by default. Fixes issue with being unable to write to newly created scripts. (759138)
- MonoDevelop: Fixed issue with MonoDevelop showing "��u" symbols in document view after using "Save As". (754609)
- MonoDevelop: Fixed issue with MonoDevelop sometimes giving focus to the wrong script when opened from Unity. (485138)
- MonoDevelop: macOS; fixed issue with MonoDevelop not working when copied to case-sensitive partition. (729201)
- MonoDevelop: Show hint in breakpoints dialog that explains exceptions list is generated from currently selected project. (731111)
- Networking: Fix issue with SendToAll sending double messages to local client when hosting. (795897)
- Particles: Added extra parameter to ParticleSystem.Simulate script function, to allow updates with very small timesteps. (729435)
- Particles: DestroyImmediate in particle trigger callback causes a crash. (806175)
- Particles: Editor now correctly focuses on empty particle systems. (803084)
- Particles: Emitters containing sub-emitters can have their playback time smoothly scrubbed in the Editor. (432980)
- Particles: Fix to allow sub-emitters to use inherited velocity settings for any simulation space. (822070)
- Particles: Fix to hide unncessary properties in the Renderer Module when using "None" render mode. (831193)
- Particles: Fixed bounding box scaling on world simulated particle systems. (811270)
- Particles: Fixed bug where world collision didn't work when the particle system was scaled on the vertical axis. (765535)
- Particles: Fixed case of shape module single material index property cutting off when inspector was narrow.
- Particles: Fixed crash if SkinnedMeshRenderer without a mesh is assigned to particle system shape. (807942)
- Particles: Fixed horizontal/vertical billboards with pivot offset. Previously the particles would get scaled and flipped in such cases. (746327)
- Particles: Fixed incorrect inspector style on Particle System Renderer Pivot field. (733896)
- Particles: Fixed issue where particle sub module parent was set incorrectly.
- Particles: Fixed issue where setting Particle.rotation3D had no effect on a particle rotation in some cases. (828869)
- Particles: Fixed issue whereby a child sub-emitter could not be rotated and emitted in one direction only. (781282)
- Particles: Fixed issue whereby disabled sub-emittor particles weren't cleared. (829208)
- Particles: Fixed issue whereby mesh particles with negative scale would get inverted incorrectly with Standard shader. (803265)
- Particles: Fixed issue whereby state getters would return the wrong value for one-shot systems that had died offscreen. (800868)
- Particles: Fixed missing animation bindings to particle system modules. It is now possible to animate all modules. (761003)
- Particles: Fixed particle IDs changing when one of the sorting mode is enabled. (501463)
- Particles: Fixed particle system default values not being set when created using AddComponent. Editor behaviour is now the same as standalone(Material is now defaulted to null instead of Default-Particle as the material may not have been included in a build). (764899, 756699)
- Particles: Fixed particles emited via script with EmitParams flickering when using sort modes. (765375)
- Particles: Fixed ParticleSystem.Play() with start delay pausing the particles. (803272)
- Particles: Fixed simulating particle system in scene view stopping it after certain amount of time. (801335)
- Particles: Improved inspector labels to make low quality paticle collisions more intuitive. (754014)
- Particles: Medium quality collisions can now be used with static colliders only. (822417)
- Particles: Nested subemitter does not emit bursts when simulating in editor but works fine when played. (803350)
- Particles: Particles sometimes spawn without start speed when shape is circle. (807628)
- Particles: Particles will now use a rigidbody's velocity if one is present. (800811)
- Particles: Scale is now applied to stretch parameters. (804772)
- Physics: Added warning in ClothInspector if MeshRenderer used with Cloth component. (769137)
- Physics: Ensure that 2D Overlap/Cast checks use consistent 'skin' radius for all shapes. (766261)
- Physics: Fix CharacterController falling through very long MeshColliders. (806800)
- Physics: Fix convex mesh inflation causing flat MeshCollider to be enlarged twice along each dimension. (677652)
- Physics: Fix crash in Cloth cooking when instantiated game object is activated. (775583)
- Physics: Fix interpolated ragdolls jittering under certain circumstances. (772337)
- Physics: Fix issue for Circle, Box & Capsule casting API where an initial overlapped state was not correctly detected.
- Physics: Fix issue where Character Controller firing trigger callbacks when Character Controller center is set. (783968)
- Physics: Fix issue where Max Angular Velocity values being reset when disabled. (802249)
- Physics: Fix issue where Setting Configurable Joint target position not waking up connected bodies. (733654)
- Physics: Fix issue with multi-object editing on Rigidbody2D & Collider2D now correctly showing properties of different values.
- Physics: Fix MeshCollider cubes not falling asleep on Terrain under certain circumstances. (628258)
- Physics: Fix physics queries detecting backfaces inconsistently. (753730)
- Physics: FIx Raycast against MeshCollider returning wrong RaycastHit.triangleIndex when degenerate triangles were present in the mesh. (699563)
- Physics: Fix Raycast detecting false hits when the whole scene was enlarged. (732865)
- Physics: Fix Raycast not detecting hits with a MeshCollider under certain circumstances. (733291, 772433, 722954)
- Physics: Fix Raycasts against CapsuleCollider returning incorrect result occasionally. (718712)
- Physics: Fix Rigidbody starting to bounce or falls through the ground when center of mass was offset from the pivot. (797993)
- Physics: Fix setting useGravity to true though it was already true causing the Rigidbody to become awake. (796324)
- Physics: Fix SphereCast failing to detect Colliders in some cases. (720683, 746417)
- Physics: Fix SphereCast returning inaccurate hit position against non-uniformly scaled colliders. (790258)
- Physics: Fix SpringJoint's min and max distances being updated wrongly after set to the same value. (788323)
- Physics: Fix the surface normal being inverted by CharacterController when colliding with a sphere. (704111)
- Physics: Fix to ensure that changing the Rigidbody2D.bodyType doesn't affect the Trigger/Collision callback state.
- Physics: Fixed a memory leak that occured when applying animated non-uniform scaling to a MeshCollider. (828570)
- Physics: Fixed a TerrainCollider crash that could be triggered when a capsule collided with an edge whose shared triangles had a hole material. (822486)
- Physics: Fixed bug where MeshRenderer would occasionally miss a transform update from an interpolated kinematic Rigidbody. (822406)
- Physics: Fixed case of SphereCastAll returning inverse normals when cast against MeshColliders with backfaced triangles. (775825)
- Physics: Fixed missing or invalid properties when accessing them through script, except useVirtualParticles. (743626)
- Physics: Fixed performance spike when activating a game object with Cloth component. (760721)
- Physics: Renamed 'Physics2D Material' to 'Physics Material 2D' in the create drop-down in the project view. (564671)
- Physics: WheelJoint2D suspension angle now correctly deserialized when used in prefabs. (759676)
- Profiler: Fixed self-profiling of Profiler.BeginSample calls in deep-profiling mode. Previously the profiler would show irrelevant data in such cases. (776595)
- Profiler: Prevented negative numbers in the Physics Profiler and showing more accurate numbers for dynamic rigid bodies and kinematic nodes instead. (792907)
- Profiler: Save Record setting when re-opening the Profiler window during the Editor session. (704398)
- Profiler: Show correct used memory graph when allocated memory exceeds 2GB. (663149)
- Samsung TV: Fixed SIMD bug which could cause occlusion culling to not work as intended.
- Samsung TV: Networking device discovery is now supported.
- Scripting: Always throw an exception when calling AssetDatabase methods from constructors and during serialization. (765357)
- Scripting: Fix crash when field type in C# (array) and single string in prefab (YAML) mismatches. (790501)
- Scripting: Fix SerializeProperty.type for serialized objects in arrays (was always "Generic Mono"). (705074)
- Scripting: Fixed crash after calling DestroyImmediate(gameObject) in MonoBehaviour.Awake (766939)
- Scripting: Fixed crash in some cases when using DestroyImmediate in a coroutine. (764672)
- Scripting: Fixed crash relating to construction of a generic Dictionary via reflection. (829757)
- Scripting: Fixed crash that may occur when [InitializeOnLoad] attribute is present on generic type. (803587)
- Scripting: Fixed crash when accessing SerializedProperty.tooltip in some cases. (723650)
- Scripting: Fixed crash when calling 'AppDomain.Load(byte[], byte[])' in a non-development player. (827833)
- Scripting: Fixed issue with being unable to use ScriptableObject.CreateInstance with a nested ScriptableObject class. (697550)
- Scripting: Fixed Mono AOT registration of particle system native calls. (754856)
- Scripting: GetComponent throws an exception if called from constructors or deserialization. (750066)
- Scripting: GetTransform<>() invoked from a constructor or field initializer could crash. (750066)
- Shaders: Add compile warning when shader target is increased above #pragma target due to feature use (e.g. geometry shaders). (757859)
- Shaders: Added support for parsing errors from #error in a shader. (824020)
- Shaders: Allow manual inclusion of Lighting.cginc in surface shaders (allows redefining macros before it). (774822)
- Shaders: Changed shader include file handling to properly handle nested and relative include paths. (735442)
- Shaders: Changed shader search paths so that the shader file had higher precedence than the project root. (754682)
- Shaders: Correct a compile error if a project had a local modified copy of some of the Unity includes. (782199)
- Shaders: Fix a case where a material using Standard shader with transparency could be sorted wrongly if the shader is reselected. (778700)
- Shaders: Fix a potential crash if an internal compiler error is encountered compiling a D3D11 shader. (782654)
- Shaders: Fix a shader compiler crash if a compute shader declares a samplerstate that doesn't match the naming scheme. (719344)
- Shaders: Fix DX11 shader disassembly not showing correctly in the editor UI for 'show compiled code'.
- Shaders: Fixed division by zero error in VertexLit shaders when light position exactly matches some vertex position. (776123)
- Shaders: Fixed header annotations on shaderlab properties overwriting the name of the property in the material editor. (793168)
- Shaders: Fixed incorrect Standard shader self-shadowing when using parallax & alpha test. (631592)
- Shaders: Fixed Metal pixel depth output to be always full float precision.
- Shaders: Fixed support for CustomEditor statements in fixed function shaderlab shaders. (793886)
- Shaders: Improved error messages for unknown shader render queues. (743871)
- Shaders: Improved error messages if a syntax error is found early in surface shader analysis. (784141)
- Shaders: Mobile normal mapped shaders have texture tiling/offset field hidden on normal maps now, since it does not do anything. (794072)
- Shaders: Removed a spurious error about _Emission if a legacy Self-Illumin shader was selected in a material. (786534)
- Shaders: Shaders using more than the maximum available number of textures will be marked as unsupported. (767884)
- Shaders: Surface shaders with directional lightmaps and light-prepass now use the normals from the camera normals texture for lighting. (765161)
- SpeedTree: Fixed crash when selecting billboard while the original .spm asset is deleted. (768057)
- SpeedTree: Fixed incorrect detail blending at branch seams.
- SpeedTree: Fixed rendering on some of the mobile devices (e.g. iPhone 6s) when tree is in dithering.
- Substance: Fixed SubstanceImporter.ExportBitmaps generated file names.
- Terrain: Fixed an issue where terrain could be selected in Scene View even if its layer is locked. (795496)
- Terrain: Fixed crash triggered when neighboring terrain resolutions didn't match. Now neighboring will be disabled and a warning message will be printed. (821794)
- Terrain: Fixed error message when rendering a terrain of zero size. (832184)
- Terrain: Fixed incorrect scaling of billboards when trees are rescaled using SetTreeInstance. (849011)
- Terrain: WindZone component now can be reset. (775690)
- UI: Fixed dropdown options not being selectable when outside of scrollview. (755377)
- UI: Fixed issue where Drowpdown List is added to the GraphicRegistry when being destroyed.
- UI: Fixed UI flickering in some cases of multithreaded rendering scenarios. (780185)
- UI: Fixed UI placeholder not appearing when input field is selected and the field is empty.
- UI: Stopped raycast from traversing up the hierarchy when a canvas with override sorting is encountered. (755377)
- UnityWebRequest: Fixed case of exception being thrown when loading cached content. (822698)
- VR: Fixed crash when VR Support is enabled but no actual device drivers could be loaded.
- VR: Fixed rendering issues when using the Global Fog standard asset in VR. (815914)
- VR: Graphics.DrawTexture places image at incorrect screen location when VR enabled. (696245)
- VR: Using Deferred Rendering + MSAA + Blur Image Effect, renders black screen. (713551)
- WebGL: Adjust the mouse wheel scale to match other platforms better. (793261)
- WebGL: Always import WebGL audio at 44.1kHz, as Web Audio will resample it anyways, and timing is incorrect otherwise. (781544)
- WebGL: Avoid input axes getting stuck if WebGL loses focus. (797338)
- WebGL: Catch exception thrown in Application.Eval statements. (690762)
- WebGL: Fix "getProcAddress" errors in Chrome console. (783786)
- WebGL: Fix anisotropic texture filtering in Safari. (778027)
- WebGL: Fix API deprecation warnings about MediaStreamTrack and mozGetUserMedia APIs.
- WebGL: Fix AudioClip.PlayScheduled and SetScheduledEndTime not working in Safari. (749303)
- WebGL: Fix build errors when using WebGL Templates with files marked as read-only. (755195)
- WebGL: Fix building with "use pre-built unity engine" option. (838754)
- WebGL: Fix error when clicking fullscreen button before content is initialiazed. (775373)
- WebGL: Fix GUITexture NPOT scaling. (766316)
- WebGL: Fix to correctly clamp the max value for WebGL Heap size to 2032.
- WebGL: Fix unnecessary waste of memory by keeping an unneeded copy of the player code at startup.
- WebGL: Fix use of Min and Max shader blend modes. (781565)
- WebGL: Fix warning messages in WebGL 2.0. (782235)
- WebGL: Fixed AudioSource.time to report correct values.
- WebGL: Fixed case of international keyboard input being processed incorrectly on Firefox. (822669)
- WebGL: Fixed case of ReadPixels method not working on floating point render textures. (827435)
- WebGL: Fixed copy/cut/paste for InputField and TextField on macOS. (762928)
- WebGL: Fixed exception on Safari when using PlayScheduled and SetScheduledEndTime. (749303)
- WebGL: Fixed line spacing in fonts generated using CreateDynamicFontFromOSFont. (819964)
- WebGL: Fixed rendering plugin support: previously interface functions for native render plugins were not getting called. (818729)
- WebGL: Make it possible to build WebGL players from non-ascii path names on windows. (627976)
- WebGL: Make it possible to whitelist UnityEngine.SpeedTreeWindAsset in link.xml. (773309)
- WebGL: Removed unused code in default WebGL template. (789899)
- WebGL: Set up editor to correctly emulate WebGL Graphics capabilities when editor mode is set to WebGL. (790287)
- Windows: Windowed DX11 applications will no longer run at maximum framerate when minimized. (784933)
- Windows Editor: Screen.resolutions will now return all available resolutions when used inside the Windows Editor. (611660)
- Windows Store: Files located in Assets/Resources won't end up in generated Assembly-CSharp-firstpass project, but will be correctly placed in Assembly-CSharp project (777741)
- Windows Store: Fix Build & Run when Product Name has characters with diacritics. (776483)
- Windows Store: Fix build failure using .NET 4 plugins and Mono compiler (compilation override None). (750001)
- Windows Store: Fix crash when UWP application throws exception through managed/native boundary. (775702)
- Windows Store: Fix JPG visual asset (tiles, splash screens etc.) support. (769109)
- Windows Store: Fix occasional build failures when using UnityEngine.Networking API and .NET Core. (763173)
- Windows Store: Fixed $(OutDir) and $(IntDir) paths for generated il2pp Visual Studio solutions which prevented appx bundles to build correctly. (774295)
- Windows Store: Fixed cases where the Editor profiler would sometimes fail to connect to an application running on a remote device (e.g. Windows Phone). (833525)
- Windows Store: SystemInfo.deviceType now returns Console when application runs on Xbox One, and returns Handheld when it runs on IoT devices (e.g. Raspberry Pi). (827089)
- Windows Store: Unity won't steal key events when another XAML element (e.g. TextBox) is focused.
- Windows Store: When playing video using Handheld.PlayFullScreenMovie, you'll be able to stop using Escape or Back button. (803250)
Known Issues
- Android: Auto rotation causes rendering artifacts on Android 4.1 and older (854739)
- Asset Import: Modifying importer settings from script produces a non-deterministic texture asset representation, which may result in a performance drop (unnecessary reimports) for projects using version control or cache sever. Fix expected shortly in a patch release. (856344)
- Editor: Asset bundle building performance decrease when building multiple small asset bundles. (849376)
- Editor: OSX: Launcher window cannot be closed when opening it via 'Account->Sign in' in Editor. (836131)
- Editor: Play mode performance regression on Windows. Fix expected shortly in a patch release. (848131)
- GI: In Editor, light does reflect off static objects when Baked GI is used with mobile platforms selected. Note that the issue is not present when the project is deployed to a device. Fix expected shortly in a patch release. (849671)
- Graphics: Camera.SetReplacementShader renders objects affected by projectors even when the tag does not match. (840141)
- Graphics: GPU profiling is not supported in macOS Editor (works in Standalone player builds). (823371)
- Graphics: GPU profiling is not supported when graphics jobs are enabled. (802273)
- Graphics: Occlusion Culling: Editor crashes when reading a scene with occlusion culling from an asset bundle. Player builds are not affected and work fine. Fix is expected shortly in a patch release. (846853)
- Particles: MacOS: Destroy() with particle system object in IEnumerator Start() causes crash. (855467)
- Physics: CapsuleCollider might penetrate a scaled MeshCollider if it stands exactly on an edge of the mesh in PCM collision detection mode. Workaround: disable PCM (uncheck Edit -> Project Settings -> Physics -> Enable PCM). Fix coming shortly in a patch. (850059)
- Physics: Using a Transform scale in X or Y or zero with a CapsuleCollider2D added will cause a crash. Fixed in the first 5.5.0 patch. (853163)
- UI: Undocked windows are placed behind the main window after assembly reload. (846877)
- VR: Single-pass deferred rendering with multiple cameras in a scene results in the scene being rendered upside down. (851910)
5.5.0f3 Release Notes (Delta since f2/RC2).
The following are changes and fixes to 5.5.0 features and regressions...
Fixes
- Core: Fixed Library folder corruption when opening project in previous versions of Unity (851782)
- Editor: Fixed undoing Transform changes when multiselection includes prefab instance and share a common ancestor (822868)
- GI: Clearing baked data at certain lighting calculation stages causes uninformative errors in the console (757816)
- GI: Fixed broken GI Previews on Retina Mac (836815)
- Graphics: Fixed a crash in the renderloop, caused by incorrect memlabel when releasing shared LightmapSettings data. (834235)
- Graphics: Fixed issue where occlusion mesh was incorrectly displayed when using single pass stereo (850170)
- Graphics: Fixed Reflection Probes artifacts when multiple overlapping lights are captured by the Reflection Probe (835423)
- Graphics: Fixed several issues regarding single pass stereo with Image effects and deferred rendering (832185, 830612 ,832283, 814290, 821746)
- Graphics: LightProbes are sometimes applied incorrectly, depending on object use/don't use probes flag, and object render order (840641)
- Serialization: Fix rare issue where prefab references from scene objects would be show as missing when using text serialization. (850947)
- UI: Fixed issue where calculation of Text perferred height was incorrect. (850077)
- VR: Fixed MsHRTFSpatializer load failure. No longer requires external dependencies to Unity and Windows. (847470)
Revision: 38b4efef76f0
Changeset: 38b4efef76f0
|
https://unity3d.com/unity/whats-new/unity-5.5.0
|
CC-MAIN-2020-05
|
refinedweb
| 9,291 | 50.84 |
Revamped Project Properties UI
In Visual Studio 2022 we are improving your experiences around navigating and modifying your project’s properties. The world of .NET is in a very different place than it was a few years ago. With a growing diverse user-base and increasingly cross-platform projects, we decided that the Visual Studio project properties were due for a much-needed re-vamp.
We want to share with you some improvements in the following areas:
- Theming and UI Updates
- Search
- Property Evaluations
- Improved Conditional Configurations
This new project properties experience is turned on in our latest preview for C# SDK style projects. The new UI will become the default in the official Visual Studio 2022 release.
Visual Studio Theming:
Immediately upon opening your project’s properties you will notice our revamped, modern, and fresh new UI.
The new look is not just intended to be pleasing to the eye, but you’ll also find that we designed it to highlight important and commonly used properties. This will make it easier for you, whether you are new to Visual Studio of have been using Visual Studio for a long time, to find exactly what you are looking for.
A request that we frequently heard was for the project properties to match theming with the rest of Visual Studio. The previous project properties UI was outdated and did not match the more modern look of the rest of the editor.
The last time we updated the look of the project properties UI was before you had the ability to change the Visual Studio theme! Because of this, an obvious flaw of the old UI was the lack of appropriate theming to match the rest of Visual Studio. The good news is that with the new Project Properties, you can use dark mode in peace! The new project properties will match the theming that you have chosen for the IDE without distracting bright UI elements unexpectedly popping up during your workflow.
Search and Property Discoverability:
Another highly requested feature, one that will make life easier for new and experienced developers alike, is the search function in the project properties. Just search for any property or value and your search term will be highlighted in the UI and you will be able to locate and edit the field immediately.
Previously you would have to sift through the various tabs in the properties dialog to find the property you were looking for. Search now simplifies this process. The ability to search for a specific property allows for clean new UI which seamlessly scrolls between tabs so that you no longer need to open multiple windows and switch from tab to tab to locate a property field.
As before, property changes also automatically save to the project file when your code is run, so there is no need to hit a save button before leaving the page. This way, complex property changes will not be lost if you navigate away prematurely.
In this new update we have streamlined the project properties to be property-centric and distilled the UI down to its essential components. As a part of this effort, the launch profiles editor been moved to its own UI where it will be easier for you to manage many profiles at once.
When originally designed, the project property pages were created as a central place for generalized configuration of one’s project. However, the complexity of launch profiles continues to scale up, with most developers adding and deleting profiles and utilizing multiple configurations. It became necessary to reconsider what fit into the project properties experience, and we ultimately concluded that it was time that launch profiles deserved its own dedicated UI outside of the project properties. Long term we believe this will be a clearer experience for users. We are working on intuitive gestures to launch that UI directly to improve Launch Profiles discoverability. In the meantime, the Launch Profiles UI can be accessed by Debug >MyProject Debug Properties at the bottom of the drop-down or by clicking the drop-down on the left of the start-up projects in the toolbar.
For discoverability within the project properties, for your convenience, the Launch Profiles dialog may also be accessed via the hyperlink in Debug Settings in the Project Properties.
Property Evaluations:
The new project properties UI also displays evaluated property values. Properties for which there is an evaluated value will show the evaluation underneath in shadow text, differentiating it from the property labels surrounding it.
This change makes it much easier to understand evaluated values without having to spend time debugging or unnecessarily jumping through code. We have done our best to enable you to fix issues quickly by making all the information you will need available and simple to discover in the project properties UI.
Conditional Configuration Improvements:
The last exciting feature we want to highlight is improved conditional configurations. There are multiple dimensions across which a project in Visual Studio may be configured: Configuration (e.g. debug/release), Platform (e.g. AnyCPU, x86, ARM), and target framework (e.g. .NET Framework 4.8, .NET Standard 2.0, .NET 6). It’s now possible to specify property value along any of these dimensions — a given property may vary its value by configuration, platform, or target framework.
To support this complexity, we have made it much easier to keep track of these configurations and see how properties vary. Previously you would have to toggle configurations in the drop-down list and monitor for values that changed. This made it difficult to tell if a given configuration applied to all conditions or just one without going through all of them manually.
Now if you want to have separate configurations for debug or release builds, for example, you no longer must change them in separate windows and toggle between the conditions to view the setting for each conditional configuration. For properties for which this type of configuration is possible, such as in the screenshot below, hovering over the little gear icon in the top left corner gives the option to vary the value by configuration. Selecting this option will add fields where you will be able to edit the property value for each configuration, in this case, for both debug and release builds.
Our new UI enables you to see if there are conditional configurations with just a glance at the project properties. It is also much clearer what the value is for a given configuration. You may continue to add conditions directly in the code itself, which will be reflected in the UI after saving.
What do you think?
As always, we appreciate you taking the time to check out what we have been working on, and we are very excited to finally share out some of these long-awaited changes.
One of the things we are most excited about is that our new data-driven UI will allow us to add value to our customers faster and react more quickly to changes in the platform. Now we will be able to easily ship new updates and react more swiftly to customer feedback.
If you haven’t looked at your project’s properties in a while, give them a look in this new experience, search around, see the evaluated values, and more! Then let us know what you think!
This looks very promising, good work! Will this be made available for C++ as well, or is it C# exclusive?
Especially messing with conditional compilation and other per-configuration settings is even more important in C++ projects.
Hi Lukas. For now this is only available for SDK-style C# projects. We will roll it out to other project types and languages over time.
I don’t mind UI changes if functionality remains the same. But it looks like you once again simplified everything and by simplifying I mean you removed a lot of stuff. For example I cannot see “Prefer 32bit” in your comparison screenshot in the new UI.
Hi Max,
Thanks for the feedback! In fact, we have added considerably more properties than were there before. The UI is now generated from data, so it’s much easier for us to add them now than it was before. You can see where the “Prefer 32-bit” property is defined here:
It is only visible for .NET Framework projects targeting AnyCPU and having the correct output type.
If there are other properties you feel should be present, open an issue on GitHub at
Would love to see ability to have a “1 page” view of all project settings, which could then be printed, or saved as a json file.
This would help in situations where you are editing multiple projects/solutions, and are manually trying to get them to have a consistent set of settings….often projects deviate in different ways from the initially generated project files.
Yes, “shared/inherited” property pages can often be a way to have some kind of consistent properties, but not always desirable to do that, and even then they can be overridden, and then projects can deviate from what you want.
Would be nice if you tried to use/follow the behaviour that VSCode uses for it’s settings pages…i.e. navigation, scrolling through…..provides some kind of familiarity – and DO show a tree view.
Even better would be a way to compare/diff project settings between different projects.
Hi cs. The easiest way to share properties between multiple projects is to use a Directory.Build.props file. Doing so allows you to specify a set of properties once and have them picked up by multiple projects automatically, which is much easier than manually copying settings and trying to keep them in sync over time. You can read more about that here:
We made a conscious effort to align the new Project Properties UI with VS Code’s Settings UI as much as possible, so I believe the areas you call out should already be covered.
Can’t try it out right now, just hoping that the performance of the new Project properties UI has improved since it was in preview in VS 2019. (Several seconds for a small & simple .NET project is in my opinion way to much and just editing the project files directly is then a much better option 😒).
Hi Bas. Performance has been improved since VS2019, so please try it out when you get a chance and let us know what you think.
I’ve tested it and my first reaction was pretty bad as I thought it was just an loooong list of properties. Then I understood I could get directly to an (invisible) anchor in that long list, by just clicking on the left headers/groups. Ok, I still don’t see the benefit as a user, and not saying the old system couldn’t/shouldn’t be improved. But what I think is still bad is this system only use a very small portion of the available space in the Visual Studio document Window. So it’s still a very long vertical list with plenty of space lost on the right… Would it be possible to (maybe with an option) use more space, like just stacking all properties in the window, and let them wrap maybe, or arranging them in (possibly a fixed set of) columns? It really starts like the revamped “New project dialog” which is awful.
I think I agree with what you are saying Simon. A long scrolling list instead of a good chunk of information at a glance may be good for the uninitiated. But for experienced VStudio-ers will be a step backwards.
The search capability seems good, but is basically necessary because you can’t see a lot at a glance.
Hi Simon,
Thanks so much for the feedback. We’re currently working with some designers to orient the property labels and fields in a way that leaves much less blank space on the right and creates clearer delineations between the various sections of the project properties. Visible anchors and section header highlights are in the works. If you would like to be involved in the longer term design decisions related to fixing the spacing and layout of each section, please reach out to collaborate, as we definitely want the opinions of experienced developers to be heard as we settle on a pleasing AND functional layout for project properties.
I totally agree with the comment that a lot of realestate is lost on the right. For me personally, this makes it harder to just browse the possible settings I can change. Ok, if you know what to look for you can just use the search (which is great), but sometimes you just want to browse for possible settings you can change without knowing what to look for. With using a long list, this makes this a lot harder.
It’s great to see this aspect of VS getting attention but my first reaction is that the information density is far too low for experienced developers. The new abilities and features for dealing with modern complexity of apps is amazing but I would be far more enthusiastic if it was tailored a bit more toward the experienced developer and show more information at once.
Hi Dan,
I hear you on that — we are trying to address this particular issue with our design team and work together to tailor the project properties UI to be easier to navigate and in an intuitive layout that is less sparse than it currently is in this preview. Do you have any particular properties or pieces of information that you feel are hidden or could be better highlighted to improve the experience for experienced developers like yourself?
Having a node/section, which allows a developer to pin/group their “favourite” properties together and show on one page could help with cutting out the burden of cycling through pages of properties.
A similar way to pin favourites in the Tools | Options dialog would be handy too.
Thanks for the suggestion. We are continuously looking for ways to simplify the properties experience for developers who know exactly what they are looking for. The ability to “favorite” properties is definitely one way to approach this. The feedback is appreciated.
What I would suggest is a special “choose favourites” mode which toggles the display of a checkbox (or star control) just prior to every property/control defined in the options list….a user can then tick whatever properties they want as favourites…then come out of “choose favourites” mode…this is instead of having some “permanent” indicator/selector for “favourites” which might be distracting.
It’s hard to find the property during scrolling. It is not clear which category the property belongs to.
Hi Vladislav. Properties are in the same categories as the old UI, though I totally understand there are years of muscle memory associated with the old UI. Have you tried the search function? It can be helpful to discover what category a property belongs to so you can more quickly find it in future.
From the screenshots it doesn’t appear to support configuring multiple target frameworks. Any plans on adding that feature?
Hi Praveen. I’d like to call out two points around your question. Hopefully they’re helpful.
1. The old UI only supported configuring a given property by configuration (Debug/Release/…) and platform (AnyCPU/x86/…). The new UI allows also you to vary a property’s value by target framework for multi-targeting projects.
2. The ability to toggle between single-targeting and multi-targeting is limited by a technical issue that currently requires reloading the project, which we don’t think creates a great experience for users. Until we can fix that, the recommended approach is to manually edit your project file and change TargetFramework (singular) to TargetFrameworks (plural). You will be prompted to reload the project. After that point, the Project Properties UI will display a text box into which you can manually edit the set of target frameworks. We hope to make this process smoother in a future release.
I also do not like new design. Previous one was comapact. Look at screnshot comparing old and new design. Previous settings shown 16 fields while new design shows only 6 of them at the same sized area. I consider new design 62.5% worse. (1 – 6/16).
I also like separate pages rather then one long page. Similarly I do not like new navigation menu. If you want to do treeview do it as a normal treeview which is user expandatable and prevent doing this crazy things which you have implemented. The menu which you have implemented change component locations on click because it collapse previously expanded menu entry (in fact collapsing was not requested by user) and expand some other new menu. If you want to retain current design I recommend just letting all entries expanded whole time.
New features like hints can be integrated to the old design in more compact way like having small help button near to field or just implementing tooltip.
Hi Michal, and thanks for the thoughtful feedback. We hear you on the property density being lower. This was a conscious decision with the goal of creating better alignment between Visual Studio and Visual Studio Code. The layout of properties and the navigation via the “tree view” behaves in much the same way as VS Code’s does.
We have discussed the ability to toggle to a denser layout, possibly by hiding property descriptions, which would increase the number of properties on screen. Support for per-configuration values and the display of evaluated values does mean we cannot reach the same property density as the old UI. We are very happy to hear your feedback and ideas on how we can further improve this experience.
“This was a conscious decision with the goal of creating better alignment between Visual Studio and Visual Studio Code. The layout of properties and the navigation via the “tree view” behaves in much the same way as VS Code’s does.”
That explains so much.
This will likely go the same way it usually does. MS will push this alien design into VS, no matter what feedback we give, and we will have to wait years for enough current team members to be shuffled off before we can move back towards something sensible.
In fact, you have done a good work. I have been very happy since I started testing this new version (VS 2022).
But Microsoft Report Viewer RDLC haven’t been added to the package. Please do so. Thanks.
Before revamping the major UI design at least share the UI prototype screenshot on GitHub and have views of other developers working outside MS.
Visual Studio is becoming less visual and more like a search and find tool. You are trying to mimic VS Code project property style screen design. This idea is not pleasing at all. First, you messed up with the NEW project dialog box and now the project property window. The old project property screen was only lacking a dark theme otherwise it was well and good.
Once again you are asking the user to search whereas in the previous design it was all appearing right options in the right place and just by looking at the screen you may know what options are available. Kindly don’t bring VSCode ideas to VS. Too much screen space is wasted and one needs to scroll to find the property to set/reset.
Yah… I tend to agree with this. I’m not really “enjoying” the new “one-page” layout. Really hard to wrap my head around this and creating new “muscle memory” will be really hard since it’s just a huge scrollable page. The search bar really becomes the only way to utilize this somewhat efficiently.
Agreed. The change has made it much harder to see the component parts.
The visual grouping that used to be achieved with line dividers has been lost with the headings only and the distance between and heading and the preceeding section is exactly the same as the following space, which it is meant to be part of. More air between (at the end of) sections please. I think some indenting of the property items would also help here.
Grouping also used to occur by having two columns, for example, with Assembly name and Default namespace on the same line. On a large screen you now just end up with a sea of white.
The treeview also hides sub-items on the non-selected items which, for me, is a good way loosing all context and forces me to use the search textbox, which I don’t want to do.
In preview 4 you will see an improved layout that adds more structure within the list of properties, adding a fine line between categories and using some nesting to improve at-a-glance comprehension.
Here’s a screenshot:
Looks like a good direction to move in overall. Wouldn’t the information density issue be improved if you just removed the boatload of informational text in between the labels and the controls? The (?) icon is still there and its job should be to provide a panel containing that info on click/hover.
HI Stephen, thanks for the feedback. We are considering adding an option to control visibility of description text in a future version.
Hi VS team, happy to hear about this great enhancement in the product,
But could you please consider my feedback here :
AS I have a solution with more than 100 projects.
Thanks
This looks great, would it be possible to one day get command line parameters editable/viewable multiline? 🙏🙏🙏
Editing lots of our microservice command line args in launchSettings.json all in one line is a bit painful.
Hi Mike. That’s a great idea, and we’d love to support this. It’s being tracked in.
|
https://devblogs.microsoft.com/visualstudio/revamped-project-properties-ui/
|
CC-MAIN-2022-27
|
refinedweb
| 3,674 | 60.85 |
Profile isActive is not taken into account
I have created profiles as per the documentation (tablet and phone). If I create a profile and return false from the isActive method, the profile is still loaded and the views from that profile are displayed. Moreover, if I load multiple profiles and they all return false (meaning I wish for the default views to display), random profile views are used (sometimes tablet, sometimes phone.
Thank you for the report.
Sencha Inc
Jamie Avins
@jamieavins
Loading all classes for all Profiles is actually the intended behavior - if we didn't do this then production builds would not work correctly. As it stands, a production build is a universal app - it works on all Profiles you have defined, without using dynamic loading in production.Ext JS Senior Software Architect
Personal Blog:
Twitter:
Github:
I don't mind what it loads. I mind that isActive is not working. If isActive returns false, it should not be the active profile, so how is it that my view from that profile is being displayed?
The Profile itself doesn't determine which views your app instantiates. At some point your code must be calling something like Ext.create('MyApp.view.someProfile.someView') - the framework doesn't do that for you, it's all in the app itself.Ext JS Senior Software Architect
Personal Blog:
Twitter:
Github:, this does not seem to be correct:
"Once the Profiles have been loaded, their isActive functions are called in turn. The first one to return true is the Profile that the Application will boot with" and "Now when we load the app on a phone, the Phone profile is activated and the application will load the following files:"
Clearly the application is making the decision about which profiles to launch. In our application our views are being autocreated via their xtype as such:
this.getNav().push(
{
xtype: 'vehicleDetail'
}
);
If I have profiles defined in my application controller: profiles: ['Tablet', 'Phone'], then the above code AUTOMATICALLY creates a view from one of the profiles, even though both profiles are marked as inActive. If I remove the profile declaration, then the default views are created.
Ah - sounds like you're registering the same xtype for both the Phone and Tablet profiles, is that correct? That's one are where our guidance could be better - in general that pattern is not a good one as it makes the xtype mapping potentially nondeterministic. I would suggest you use unique xtypes for every component (even if it's just a Profile-specific variant) until we figure out a more elegant solution to thisExt JS Senior Software Architect
Personal Blog:
Twitter:
Github:
Yes, that was it. I had multiple views with the same xtype. My mistake. So what I did was implement my own "View Factory", using the current active profile, something like:
createView: function (viewName, profile) {
var view = null;
if (profile)
view = Ext.create('App.view.' + profile._namespace + '.' + viewName);
else
view = Ext.create('App.view.' + viewName);
return view;
},
getView: function (className) {
var profile = this.getApplication().getCurrentProfile();
var views = profile.getViews();
if (views.indexOf(className) > -1)
return this.createView(className, profile);
else
return this.createView(className);
},
pushView: function (className, title) {
var view = this.getView(className);
var nav = this.getNav();
nav.push(view);
nav.getNavigationBar().titleComponent.setTitle(title);
}
So I can push views onto my navigator like this:
this.pushView('MyViewClassName', 'Some view title');
Awesome, glad you were able to solve it
The framework really should offer a neat way to do this without the confusion though, I don't know what the solution looks like yet (could just be some written conventions) but it's something we're thinking aboutExt JS Senior Software Architect
Personal Blog:
Twitter:
Github:
Had exactly the same problem - tearing my hair out on this one.
I assumed I could use same xtype across platforms and that profile executed views down the tree from its initial view loaded - even using fully pathed 'requires' statements didnt help.
profile specific xtypes fixed it - thx.
Yes I think some guidance around this in the doco on profiles would be great.
cheers
|
https://www.sencha.com/forum/showthread.php?190986-Profile-isActive-is-not-taken-into-account
|
CC-MAIN-2015-48
|
refinedweb
| 684 | 53 |
...
It's certainly possible to learn C++ as a first programming. That said, it is a complex language, but there's no reason why it can't be your first. Many other languages could also equally well be your first language, so you need to consider what you're trying to achieve. If you're happy so far with C++ from what you've learnt then by all means stick with it.
As for tutorials, they vary greatly in quality. In my opinion you're much better off investing in a beginners book. It will always be there for you as a reference, and will usually cover all of the basics of the language. There's a large number of beginners books to choose from, and most of them are reasonably priced so money shouldn't be too much of an issue.
As you progress, you'll want to add additional books to your collection - there's no single book that I've seen that will teach you everything you need to know about C++. But a beginners book will get you off to a better start than online tutorials IMO.
And hang around in forums such as this, or a relevant newsgroup, for help when you need it.
[Edit:- ah, you deleted your post text while I was writing ;-) ]
C and C++ cover all the bases from systems level and embedded programming to full blown desktop applications, and in that respect you cannot go wrong. However because of thier general purpose nature, they may not be the quickest way of producing some applications.
Having said that products like Borland's C++ Builder and to some extent Visual C++ help improve productiviy in visually rich applications. (I have heard that C++.Net is better in the RAD department).
C and to a lesser extent C++ (of which C is a subset) compilers are available for the widest range of processors and platforms, for that reason if you wish to (one day) program professionally, and especially if you are interested in embedded systems, then C/C++ are the languages to learn. If you will only ever code desktop applications, then whatever gets the job done. Programming for the Web particularly may require learning a wider range of more specialist programming and scripting languages, such as Java for example, but learning C++ first will do no harm.
For a tutorial see. Note however, that the tutorial strictly adhere to ANSI standards, and the MinGW CGG compiler that DevC++ uses is rather strict about compliance. The guys at can help you with this, but mostly it is a case of removing the .h extension from standard C++ headers, and declareing "using namespace std ;" after the includes. The tutorial also discusses C style strings and the C string library, but not the C++ string class.
My preferred tutorial is the electrionic one bundled with Visual C++ 6.0SE. It is base on Ivor Horton's Getting Started with Visual C++, but despite the title covers only pute ANSI C++ console mode apps. so does not obfuscate things by diving into GUI applications.
With DevC++ you get no visual development tools, not even a resource editor. You can get these tools from third parties on the web. You also get no GUI class library like MFC. wxWindows is an alternative, otherwise you are stuck with Petzold style Win API programming, but that is good for the soul, and you will at least get a better understanding of what is going on under the hood.
Try for electronic books and tutorials that can be downloaded.
Clifford.
|
http://forums.devshed.com/programming-42/1st-language-learn-78011.html
|
CC-MAIN-2018-17
|
refinedweb
| 600 | 69.92 |
0
Hello Everyone,
I need to add functionality to store the guesses the user makes in an array up to a maximun number of guesses stored in a constant. It must display a list of the previous guesses before the user guesses a number each time (excluding their first guess). Once the user reaches the max number of guesses i must display a message and end the loop.
I am not feeling too good about this part of the program. I just don't know where to start on this portion.
Here is my current code:
#include <iostream> // Used to produce input and output information. #include <cstdlib> // This header is used to produce the random number generator function. #include <ctime> // Header used to help with the production of random numbers. using namespace std; // Allows the use of cout and cin without having to type std in front of them everytime. int ReviewGuess(int secretRandom, int userGuess) // Function I created to check against certain conditions. { if (cin.fail ()) // This "IF" statement rules out entries that do not follow the rules of the games. { cin.clear(); cin.ignore(100,'\n'); return -2; } else if (userGuess < 1 || userGuess > 100) // This "ELSE IF" statement keeps integer guesses between 1 and 100. return -2; else if (secretRandom == userGuess) // this "ELSE IF" statement checks if the users guess matches the random number. return 0; else if (secretRandom < userGuess) // This "ELSE IF" statement checks if the user guess is higher than the random number. return 1; else if (secretRandom > userGuess) // This "ELSE IF" statement checks if the user guess is lower than the random number. return -1; } int main () { bool playAgain=true; // Boolean expression used to offer the ability to play the game again. while(playAgain) { int secretRandom = 0; int userGuess = 0; const int MAX = 100, MIN = 1; // Sets limits on the random number generator and the range of guesses allowed by the user. // Create random number srand(time(NULL)); // Part one of random number generator. secretRandom = (rand() % (MAX - MIN + 1)) + MIN; // Part two of random number generator. cout << "Welcome to My Number Generator Game" << endl; // output cout << "The object of the game is to guess a number between 1 and 100" << endl << endl; // output // Loops forever until user finds the number while (userGuess != secretRandom) { cout << "Please enter your guess : " ; // output cin >> userGuess; // Input - User to enter a guess between 1 and 100 int returnValue; returnValue=ReviewGuess(secretRandom, userGuess); switch (returnValue) // Switch statement with the directions for the user, based on the users guess. { case 0: cout << " Congratulations, you are CORRECT with your guess of " << userGuess << " !" << endl << endl; break; case 1: cout << "Your guess of " << userGuess << " is too high. Please guess a LOWER number." << endl << endl; break; case -1: cout << "Your guess of " << userGuess << " is too low. Please guess a HIGHER number." << endl << endl; break; case -2: cout << "ERROR!! Please enter a NUMBER between 1 and 100." << endl << endl; break; default: cout << "Your guess is not within the guidelines of this game. Please enter a NUMBER between 1 and 100." << endl << endl; } } // This next section gives the user the opportunity to play again char again; cout << " Do you want to play again? Enter y or n: " << endl; cin >> again; if(again!='y') { playAgain = false; cout << endl << " Thank you for playing My Number Generator Game! " << endl << endl; } } char yourName; cout << "Please type your first name and press enter." << endl << endl; // output cin >> yourName; // Input - User to enter in their first name return 0; }
|
https://www.daniweb.com/programming/software-development/threads/343959/how-do-i-add-array-to-guessing-game
|
CC-MAIN-2017-17
|
refinedweb
| 575 | 72.16 |
We’ve introduced a new logo for EDN as part of our standard header. With that minor redesign, I had a "duh!" moment and realized we could also create a "home page" link for the specific EDN application you’re currently using, such as Blogs, Chat, Discussion Forums, CodeCentral, Member Services, QualityCentral, and so on.
The EDN "knowledge base" is the ‘home page" of EDN, and every EDN web site has a link back to the EDN home page. Every EDN application label now has a link to the application "home page" as well. The following graphic shows this for member services:
Note: the discussion forums is missing its application label and link right now. We’ll introduce that application label and link for discussion forums soon.
Share This | Email this page to a friend
As I mentioned in this blog post, I’ll be attending Delphi Live this week. If you want to catch up with me, probably the best place to find me is in Embarcadero area of the exhibit hall on Thursday from approximately 1:15pm-2:30pm and 6:45-7:30pm (at the "Beer Bash" before the "Meet the Team").
See you there!
Shortly after my blog post about finally displaying MD5 hash values for CodeCentral downloads, Jorge Almeida asked about SHA1 hash values instead because of the known collision problems with MD5. So, we now are displaying not only MD5 hash values but also SHA1 hash values for each CodeCentral download that has an attachment, as illustrated (once again) in the MD5/SHA1 Hash Generator upload.
When you go to that item, you will now see in the details section:
Updated on Tue, 25 Sep 2007 13:26:55 GMTOriginally uploaded on Tue, 25 Sep 2007 07:51:10 GMTSHA1 Hash: 4A6F1A4808A1E295D309F5F15E20336FAB08D6BCMD5 Hash: 7ACEF4E7E2A223B59F92070039FD1947
Hopefully, we won’t have to rehash the hash values in CodeCentral again.
I’ll be attending Delphi Live! in San Jose, California May 13 – 16, 2009. Thomas Pfister is staying nearby in Capitola, California and has graciously offered to chauffeur me to and from the conference in the handy-dandy convertible he’ll have while visiting. Since I’m completely buried in EDN work until then, I’m luckily not speaking at the conference this year, so I can attend sessions, and gather informal feedback from everyone there on what they’d like to see on EDN, instead of scrambling from session to session, preparing for my next talk.
It’s not often I get to go to a conference only as an attendee, and I’m really looking forward to this one! There are lots of great sessions lined up.
I hope to see you there!
All internal stored downloads in CodeCentral now have an MD5 hash value, so you can use that value to validate your download.
In the Details section of the download, you’ll see something like this:
Updated on Tue, 25 Sep 2007 13:26:55 GMTOriginally uploaded on Tue, 25 Sep 2007 07:51:10 GMTMD5 Hash: 7ACEF4E7E2A223B59F92070039FD1947
If you don’t already have an MD5 utility, you should be able to use this CodeCentral Delphi download to compare the hash value against.
This request was made long ago on our newsgroups. I’m glad to finally mark this one "Done".
We’re working on "named lists" for QualityCentral. This will allow any logged-in user to create a list of QualityCentral (QC) reports, name the list, and share it with varying visibility rules, such as private, public, invitation only, etc.
I want to get your feedback on some of the options for named lists. This is not an exhaustive design spec, and each of these options have implications for how the lists are managed internally. What I’d really like to get is what you expect for the user experience, without worrying about the internal implementation of the list.
Consider the following "named list" scenario:
Here’s what I’d like your feedback on:
1) When you look at "My QC items", what do you see?
1a) The combined QC reports from the referenced lists
1b) A list containing links to each of the referenced lists
1c) Something else entirely
2) When you remove a report reference from the list "My QC Items", should:
2a) the report reference be removed from the list originally containing it?
2b) you be prompted to remove it from the original list?
2c) it only be removed from "My QC Items" because "My QC Items" should be a snapshot of the other lists at the time you create the list "My QC Items"
(Status updates and other modifications to a specific item are not an issue, because all lists link to their original QC items.)
3) When you add items to "My QC Items", should:
3a) it be added as a new QC report link only for "My QC items"
3b) you be required to choose the referenced list that should contain the reference
3c) you only be allowed to add another list to a list of lists
Please let me know what you think. Thanks!
Since I started following the public beta in mid-2008, I’ve been eagerly awaiting the release of ASP.NET MVC. Now that ASP.NET MVC 1.0 is released, I’ve been diving into it more, and fiddling with some DataSnap tooling to quickly generate the strongly typed models MVC works likes best. The EDN team is working on upgrades (replacements, really) to existing web applications, and also some new web applications based on ASP.NET MVC.
If you’re not familiar with ASP.NET MVC, my top recommendation is to read Scott Guthrie’s free 185 page tutorial. (This tutorial is one of the best tutorials I’ve ever read on the process of writing any application. There are many gems in there that go beyond just ASP.NET MVC.)
I have some friends using Developer Express XPO to develop both a WinForms GUI and an MVC interface. One of the things they were trying to figure out was how to page an XPCollection, which supports IEnumerable, and is similar to a strongly typed dataset. Paging a collection is something we definitely need for our EDN MVC applications as well, so I decided to investigate this. I used code from the MVCContrib project to implement collection paging for XPCollection (and other IEnumerable collections) in a generic but highly customizable and reusable way.
MVCContrib includes a PaginationHelper class for converting an enumerable collection to an interface called IPagination.For further information, please read Jeremy Skinner’s discussion of his excellent work on GridModels and Html.Pager().
PaginationHelper
IPagination
Here’s a pattern to use to quickly make your IEnumerable collection pageable.
IEnumerable
First, implement support for a nullable int page number in your controller action:
using MvcContrib.Pagination;
public ActionResult Index(int? page)
{
var pageNo = page?? 1; // default to page 1
var Customers = GetCustomers(); // returns your Enumerable collection
var CustPage = PaginationHelper.AsPagination<Customer>(Customers, pageNo);
return View(“Index”, CustPage);
}
Then, use MvcContrib.UI.Pager’s html helper for generating the paging control:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IPagination<Customer>>" %>
<%@ Import Namespace="MvcContrib.UI.Pager" %>
…
(your standard MVC code for iterating the collection, now a subset)
…
<%= Html.Pager(Model) %>
PaginationHelper.AsPagination casts Customers to an IPagination interface. One important change I had to make to this ascx code was to replace System.Web.Mvc.ViewUserControl<IEnumerable<Customer>> with System.Web.Mvc.ViewUserControl<IPagination<Customer>>. Once you do that, the call to Html.Pager() will automatically generate the paging UI for you, which defaults to using a URL parameter called "page" for indicating which page to select out of the collection.
PaginationHelper.AsPagination
Customers
System.Web.Mvc.ViewUserControl<IEnumerable<Customer>>
System.Web.Mvc.ViewUserControl<IPagination<Customer>>
Html.Pager()
The total number of items in the collection, the range of selected items, going to the first, previous, next, and last page of the collection are all automatically supported by Html.Pager().
Update: it was so late last night, I forgot to mention this post about XPO and LINQ support.
I was just having a Skype chat with Jonathan Benedicto, one of the developers on the Developer Network team, and he pointed out a very valuable and relevant link to me regarding the "Top 25 most dangerous programming errors" all software developers should address in their code.
This isn’t a funny David Letterman Top 10 list. This is a list put together by more than 30 organizations, including the US National Security Agency, the Department of Homeland Security, Microsoft, and Symantec.You can see the news article Jon mentioned to me on the BBS web site. (It’s nice to see the industry work together on broad issues like this.)
For the "meat" of the errors and ways to address them, see the official list, including fixes.
And start plugging any holes you find in your own code!
Update: Blog server maintenance is now completed. Thank you for your patience.
After 11am Pacific Time, our blog server will be temporarily down as it gets moved to our new network infrastructure. We expect the down time to be 5 to 30 minutes. We apologize for the inconvenient timing, but we’re in the middle of migrating all our servers to our new infrastructure, and not all of it can be done in the middle of the night! (Or the weekend.)
We appreciate your patience as we migrate all our servers to our greatly improved infrastructure. I hope you’ve been noticing the improved performance in the last couple weeks, as we’ve been migrating portions of it over.
We’ll be all done by January 1, 2009. What a great way to usher in the new year!
This is a quick post to point out some cool new features on the Developer Network.
We recently launched a major upgrade to our search engine. In addition to all the features you’d expect from a robust search engine, it also adds support for searching for specific source code snippets in articles and on CodeCentral (QualityCentral attachments will be indexed soon as well). We even have a "SearchInsight" feature to provide suggestions while you type in your search string. Read Unified search theory for more information. If you would like to learn how to do something similar for your own applications, read the article Implementing a Lucene search engine.
We raised the visibility of our links in member services, and also simplified the login form. Our new member services includes direct links to your specific registered user downloads, your personal discussion forums page, your personal QualityCentral page, and improved UI for our other membership services.
Whenever we introduce new features or services on the Developer Network, we do our best to document them in a timely fashion. There are many features available to you, and the list is constantly growing. The best place to learn about the services available is the Developer Network Help section. You can also subscribe to our news feeds, which are available on every Developer Network page, so you can get as specific as you want for news alerts. You can even subscribe to custom search results.
Server Response from: blogs2.codegear.com
|
http://blogs.embarcadero.com/johnk/
|
crawl-002
|
refinedweb
| 1,874 | 61.46 |
Mediator/Python
I'll confess right now and tell you that I'm a newbie to Linux, having moved into a UNIX environment when I changed jobs almost two years ago. Before that I was an embedded systems programmer who worked primarily in a Windows environment. If you can find it in your heart to forgive me, I'd like to say the UNIX/Linux philosophy has been steadily winning me over. In addition to learning this amazing OS, I've had the opportunity to be exposed to the Python language. Not only do I find Python to be a powerful and expressive tool, but with the addition of wxPython as a GUI extension, I won't be going back to programming the Win32 API.
One of the things I did regularly in my GUI work was develop dialog boxes. Part of my design goal was to make the controls on the dialog boxes interactive, so the behavior of the controls would help my users get their work done. You've probably seen applications that do this, where one or more controls will change state depending on the state of some other control. This kind of interaction can be created by placing code in the event handlers of these controls. However, you'll end up writing a great deal of code in these event handlers to do all of this well. Plus, coding the interaction into the event handler couples the controls together. This means they have to know about each other in order to interact. If your dialog box gets at all complicated, it can lead to a maintenance nightmare. Just picture all of those controls making decisions about what their current state means to all the other controls on the dialog box. Talk about spaghetti code!
When I was creating this kind of dialog box I could see it would lead to a mess, so I wanted to decouple the controls from one another. I also wanted to centralize the interaction code in one place, so changes would have to be updated in only one place. The trick was to decide how to do this. One thing I tried, and I'm sure many others do this as well, was to search the Web to see if anyone had done something similar. What I found were discussions of design patterns and, specifically, the book Design Patterns: Elements of Reusable Object-Oriented Software, which I highly recommend to anyone who takes their code seriously. The examples in the book are based on C++, but the concepts apply to many OO-based languages, including Python. The pattern we're going to use as a solution to our dialog box problem is called the Mediator pattern. This pattern encapsulates the interactions of a set of objects.
From an OO point of view, there is one Mediator object containing all the objects that we want to have interact with one another; they are called Colleagues. The Colleagues have a weak reference to the Mediator object and none to each other. The Mediator has strong reference to the Colleague objects and can update them directly in order to create the desired behavior for all Colleague objects. The benefits of this pattern are what we're looking for; it centralizes the interaction of objects and reduces the coupling between them.
The Mediator/Colleague pattern is implemented as an interface that can build actual class objects. The Mediator interface has a method called ColleagueChanged(), which is what all Colleagues call to inform the Mediator that a change has occurred. The Colleague interface has only one required method, called Changed(), which each derived object calls to inform the Mediator that a change in state has occurred. In addition, the Colleague base class has a public data member called mediator, which is a reference to the Mediator object that contains it.
All of that's very nice, but how do we actually implement a dialog box that uses the Mediator/Colleague pattern? We'll do this using Python's OO features and using wxPython as the GUI interface for a window. First things first, though; let's create a Mediator base class:
class Mediator: def __init__(self): pass def ColleagueChanged(self, control, event): self._ColleagueChanged(control, event) def _ColleagueChanged(self, control, event): pass
In this example the Mediator class is implemented as a Template pattern. This pattern allows us to separate the interface and implementation of the class. Users of this class call the CreateColleagues() method but override the _CreateColleagues() method in their derived classes. I won't discuss the Template pattern further, but it's another very useful pattern to know.
Now let's create our Colleague base class:
class Colleague: def __init__(self, mediator): self.mediator = mediator def Changed(self, colleague, event): self._Changed(colleague, event) def _Changed(self, colleague, event): self.mediator.ColleagueChanged(colleague, event)
The Colleague base class is also implemented as a Template pattern. As before, users call the Changed() method but override the _Changed() method, if necessary. In addition, the Colleague has a data member, self.mediator, which is a reference to the containing Mediator instance. This reference is passed into the constructor of the Colleague.
Since our example program is intended to show the utility of the Mediator/Colleague pattern, it's somewhat contrived. To make the example a little simpler I've based the one window of the example on wxFrame from the wxPython library, rather than wxDialog. Otherwise, the code is the same. Because our example program uses wxFrame as the container of the controls, it's the logical choice to be the Mediator. In order to give wxFrame the interface of the Mediator class, we'll create a new class MainFrame that looks like this:
class MainFrame(wxFrame, Mediator): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 300)) Mediator.__init__(self)
In this code we've created a new class, MainFrame, that inherits from both wxFrame and Mediator base classes. For this to work in Python we have to call explicitly the constructor of both the parent classes. This call is made in the __init__() method of the MainFrame class.
In order for our MainFrame class to interact with its controls as Colleagues, those controls have to be derived from the Colleague base class. As an example, let's create a text control that is also a Colleague object. We do this by creating a new class, myTextCtrl, that looks like this:
class myTextCtrl(wxTextCtrl, Colleague): def __init__(self, mediator, *_args, **_kwargs): apply(wxTextCtrl.__init__, (self,) + _args, _kwargs) Colleague.__init__(self, mediator)
Here we've created a new class that inherits from both wxTextCtrl and Colleague base classes. Again, in order for this to work in Python we have to call explicitly the constructor of both the parent classes. This is done in the __init__() method of myTextCtrl. In order to get all the optional parameters of the wxTextCtrl class properly passed to its constructor, I'll use the apply() function to call its __init__() method and pass in the parameters. The __init__() method of the Colleague base class is called directly, passing mediator as a parameter.
Now we have a class that is both a Colleague and a wxTextCtrl. An instance of this class will receive all the events generated by a wxTextCtrl and also has the behavior of the Colleague class. When an event occurs that our MainFrame object cares about, the event handler calls the Changed() method and passes the self reference and the event as parameters. As defined in the Colleague class, the Changed() method calls the ColleagueChanged() method of the control's Mediator reference. In this way the MainFrame object (which is a Mediator object) is informed of all changes occurring in its contained controls.
So how do we tie all this together in our MainFrame window? First, as we did with myTextCtrl, we must create derived classes of all the controls that will interact on our window that also derive from the Colleague base class. Then, as in most wxPython windows, we must create our controls in the window's constructor; in this case MainFrame's __init__() method. Each time a control is created, MainFrame passes itself as a parameter to the derived control. You'll see this in the complete example program that accompanies this article [available at]. Don't be dismayed by the amount of code in the MainFrame.__init__() method; a great deal of it calls layout functionality provided by wxPython and is not strictly necessary for our example. It just makes it look nicer.
One thing you should notice I've done in the MainFrame.__init__() method is create a dictionary object called self.__colleagueMap. I've placed sets of key/value pairs into this dictionary consisting of a reference to the created Colleague controls and a method of the MainFrame class. I've done this because Python does not have a switch/case construct like C/C++ has. This dictionary provides an elegant mechanism to call the correct method whenever a Colleague object has changed, without resorting to a lengthy if/elseif construct. You'll see this in the example program in the implementation of the _ColleagueChanged() method, as shown below:
def _ColleagueChanged(self, colleague, event): if self.__inProcess != true: self.__inProcess = true if self.__colleagueMap.has_key(colleague): self.__colleagueMap[colleague](event) self.__inProcess = false
In this code the parameter, colleague, is used as the lookup into the dictionary. If the colleague exists as a key, then the corresponding method is called and the event is passed as a parameter. This is a very slick way to implement a multiway branch like the switch/case construct.
Now our Mediator and Colleague objects exist and are connected together. The Mediator object (MainFrame) will be notified of any relevant event generated by a Colleague object (control). So what's left to do? We have to provide the centralized code that will create the desired interaction between our controls. This work is done in the methods we've placed into the self.__colleagueMap dictionary. Into each method we place the code that reacts to that controls event. Since these methods are part of our Mediator (MainFrame) object, they know about and have access to all other controls on the window.
The example program has been tested under Python versions 2.1 and 2.2, along with their respective wxPython versions. When the example program is run you should see a window open up that looks like the one pictured in Figure 1.
The interaction on the displayed window involves most of the controls. When you type a character in the text box, the program does some simple speed selection and highlights the first entry in the list box that matches. In addition, the Select and Clear buttons become enabled. If you select either a city or state, the complementary selection is made in the other list box. If you select a different region with the radio buttons, that action re-initializes the lists boxes, clears the text box and disables the Select and Clear buttons. Clicking on the Clear button alone clears the text box and disables itself. All of the interaction code is in the MainFrame class, and the controls are not coupled to one another.
Our wxFrame window doesn't do anything very useful, but it does demonstrate how the Mediator pattern can orchestrate the behavior of controls on a window. The real payoff for this effort comes when you apply this pattern to a more involved dialog box, where the interaction complexity can grow at a shocking rate. To manage it, all we have to do is add another control that is derived from the Colleague class and add the corresponding interaction code to our ColleagueChanged() method, and the complexity is handled.
|
http://www.linuxjournal.com/article/5858?quicktabs_1=0
|
CC-MAIN-2018-05
|
refinedweb
| 1,973 | 62.27 |
Greetings,
I have this program that runs w/o any errors but I am curious why its output looks like this. My input is 1 2.2 3 4.4 5 6.6 w/o any characters. I would think it woould print 1 (space, since there is no char) then 2,2 etc... I am curious if anyone can explain to me why it does this.
Code:
#include <iostream> // cin, cout, >>, <<
#include <string> // used for char
using namespace std;
int main()
{
int i1, i2, i3;
char c1, c2, c3;
double r1, r2, r3;
cin >> noskipws
>> i1 >> c1 >> r1
>> i2 >> c2 >> r2
>> i3 >> c3 >> r3;
cout << i1 << c1 << r1
<< i2 << c2 << r2
<< i3 << c3 << r3;
return 0;
}
|
http://cboard.cprogramming.com/cplusplus-programming/25773-i-need-help-problem-printable-thread.html
|
CC-MAIN-2013-48
|
refinedweb
| 117 | 91.21 |
This patchset introduces a system log namespace.
It is the 2nd version. The link of the 1st version is.
In that version, syslog_
namespace was added into nsproxy and created through a new
clone flag CLONE_SYSLOG when cloning a process.
There were some discussion in last November about the 1st
version. This version used these important advice, and
referred to Serge's patch().
Unlike the 1st version, in this patchset, syslog namespace
is tied to a user namespace. Add.
Rui Xiang (9):
netfilter: use ns_printk in iptable context
fs/proc/kmsg.c | 17 +-
include/linux/printk.h | 5 +-
include/linux/syslog.h | 79 ++++-
include/linux/user_namespace.h | 2 +
include/net/netfilter/xt_log.h | 6 +-
kernel/printk.c | 642
++++++++++++++++++++++++-----------------
kernel/sysctl.c | 3 +-
kernel/user.c | 3 +
kernel/user_namespace.c | 4 +
net/netfilter/xt_LOG.c | 4 +-
10 files changed, 493 insertions(+), 272 deletions(-)
--
1.8.2.2
|
http://article.gmane.org/gmane.linux.kernel/1533621
|
CC-MAIN-2016-40
|
refinedweb
| 146 | 64.98 |
Spring Boot Support in Spring Tool Suite 3.6.4
Spring Boot STS Tutorial
Spring Tool Suite 3.6.4 was just released last week. This blog post is a tutorial demonstrating some of the new features STS provides to create and work with Spring Boot applications.
In this tutorial you’ll learn how to:
- create a Simple Spring Boot Application with STS
- launch and debug your boot application from STS
- use the new STS Properties editor to edit configuration properties.
- use @ConfigurationProperties in your code to get the same editor support for your own configuration properties.
Creating a Boot App
We use the “New Spring Starter” wizard to create a basic spring boot app.
Spring boot provides so called ‘starters’. A starter is set of classpath dependencies, which, together with Spring Boot auto configuration lets you get started with an app without needing to do any configuration. We pick the ‘web’ starter as we’ll build a simple ‘Hello’ rest service.
The wizard is a GUI frontend that, under the hood, uses the web service at start.spring.io to generate some basic scaffolding. You could use the web service directly yourself, download the zip it generates, unpack it, import it etc. Using the STS wizard does all of this at the click of a button and ensures the project is configured correctly so you can immediately start coding.
After you click the finish button, your workspace will look something like this:
The
HelloBootApplication Java-main class generated by start.spring.io is the only code in our app at the moment. Thanks to the ‘magic’ of spring boot, and because we added the ‘web’ starter to our dependencies, this tiny piece of code is already a fully functional web server! It just doesn’t have any real content yet. Before adding some content, let’s learn how to run the app, and verify it actually runs in the process.
Running a Boot App in STS
Spring boot apps created by the wizard come in two flavors ‘jar’ or ‘war’. The Starter wizard let’s you choose between them in its ‘packaging’ option. A great feature of spring-boot is that you can easily create standalone ‘jar’ packaged projects that contain a fully functional embedded web server. All you need to do to run your app, is run its Java Main type, just like you do any other plain Java application. This is a huge advantage as you don’t have to mess around with setting up local or remote Tomcat servers, war-packaging and deploying. If you really want to do things ‘the hard way’ you can still choose ‘war’ packaging. However there’s really no need to do so because:
- you can convert your ‘jar’ app to a ‘war’ app at any time
- the Cloud Foundry platform directly supports deploying standalone Java apps.
Note: We won’t cover how to deploy apps to Cloud Foundry here, but in this article you can learm more about using Cloud Foundry Eclipse to do that directly from your IDE.
Now, if you understood what I just said, then you probably realize you don’t actually need any ‘special’ tooling from STS to run the app locally. Just click on the Java Main type and select “Run As >> Java Application” and voila. Also all of your standard Eclipse Java debugging tools will ‘just work’. However, STS provides a dedicated launcher that does basically the same thing but adds a few useful bells and whistles. So let’s use that instead.
Your app should start and you should see some output in the console view:
You can open your app running locally at. All you’ll get is a
404 error page, but that is exactly as expected since we haven’t yet added any real content to our app.
Now, what about the bells and whistles I promised? “Run As >> Boot App” is pretty much a plain Java launcher but provides some extra options to customize the launch configurations it creates. To see those options we need to open the “Launch Configuration Editor”, accessible from the
or
toolbar button:
If you’ve used the Java Launch Configuration Editor in Eclipse, this should look familiar. For a Boot Launch Configuration, the ‘Main’ tab is a little different and has some extra stuff. I won’t discuss all of the extras, you can find out more in the STS 3.6.4 release notes. So let’s just do something simple, for example, override the default http port
8080 to something else, like
8888. You can probably guess that this can be done by setting a system property. In the ‘pure’ Java launcher you can set such properties via command-line arguments. But what, you might wonder, is the name of that property exactly “spring.port”, “http.port”, “spring.server.port”? Fortunately, the launch configuration editor helps. The Override Properties table provides some basic content assist. You just type ‘port’ and it makes a few suggestions:
server.port add the value
8888 in the right column and click “Run”.
If you followed the steps exactly up to this point, your launch probably terminates immediately with an exception:
Error: Exception thrown by the agent : java.rmi.server.ExportException: Port already in use: 31196; nested exception is: java.net.BindException: Address already in use
This may be a bit of a surprise, since we just changed our port didn’t we? Actually the port conflict here is not from the http port but a JMX port used to enable “Live Bean Graph Support” (I won’t discuss this feature in this Blog post, see STS 3.6.4 release notes).
There are a few things we could do to avoid the error. We could open the editor again and change the JMX port as well, or we could disable ‘Live Bean Support’. But probably we don’t really want to run more than one copy of our app in this scenario. So we should just stop the already running instance before launching a new one. As this is such a common thing to do, STS provides a
Toolbar Button for just this purpose. Click the Button, the running app is stopped and restarted with the changes you just made to the Launch Configuration now taking effect. If it worked you should now have a
404 error page at instead of
8080. (Note: the Relaunch button won’t work if you haven’t launched anything yet because it works from your current session’s launch history. However if you’ve launched an app at least once, it is okay to ‘Relaunch’ an app that is already terminated)
Editing Properties Files
Overriding default property values from the Launch Configuration editor is convenient for a ‘quick override’, but it probably isn’t a great idea to rely on this to configure many properties and manage more complex configurations for the longer term. For this it is better to manage properties in a properties file which you can commit to SCM. The starter Wizard already conveniently created an empty
application.properties for us.
To help you edit
application.properties STS 3.6.4 provides a brand new Spring Properties Editor. The editor provides nice content assist and error checking:
The above screen shot shows a bit of ‘messing around’ with the content assist and error checking. The only property shown that’s really meaningful for our very simple ‘error page App’ right now is
server.port. Try changing the port in the properties file and it should be picked up automatically when you run the app again. However be mindful that properties overridden in the Launch Configuration take priority over
application.properties. So you’ll have to uncheck or delete the
server.port property in the Launch Configuration to see the effect.
Making Our App More Interesting
Let’s make our app more interesting. Here’s what we’ll do:
- Create a ‘Hello’ rest service that returns a ‘greeting’ message.
- Make the greeting message configurable via Spring properties.
- Set up the project so user-defined properties get nice editor support.
Create a Simple Hello Rest Service
To create the rest service you could follow this guide. Hover we’re doing something even simpler and more direct.
Go ahead and create a controller class with this code:
package demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello(@RequestParam String name) { return "Hello "+name; } }
Try this out by Relaunching (
) your app. The URL should return a text message “Hello Kris”.
Making the Greeting Configurable
This is actually quite easy to do, and you might be familiar with Spring’s @Value annotation. However, using
@Value you won’t be able get nice content assist. Spring Properties Editor won’t be aware of properties you define that way. To understand why, it is useful to understand a little bit about how the Spring Properties Editor gets its information about the known properties.
Some of the Spring Boot Jars starting from version 1.2.x contain special JSON meta-data files that the editor looks for on your project’s classpath and parses. These files contain information about the known configuration properties. If you dig for a little, you can find these files from STS. For example, open “spring-boot-autoconfigure-1.2.2.RELEASE.jar” (under “Maven Dependencies”) and browse to “META-INF/spring-configuration-metadata.json”. You’ll find properties like
server.port being documented there.
For our own user-defined properties to be picked-up by the editor we have to create this meta data. Fortunately this can be automated easily provided you define your properties using Spring Boot @ConfigurationProperties. So define a class like this:
package demo; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("hello") public class HelloProperties { /** * Greeting message returned by the Hello Rest service. */ private String greeting = "Welcome "; public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } }
The
@ConfigurationProperties("hello") tells Boot to take configuration properties starting with
hello. and try to inject them into corresponding Bean properties of the
HelloProperties Bean. The
@Component annotation marks this class so that Spring Boot will pick up on it scanning the classpath and turn it into a Bean. Thus, if a configuration file (or another property source) contains a property
hello.greeting then the value of that property will be injected into
setGreeting of our
HelloProperties Bean.
Now, to actually use this property all we need is a reference to the bean. For example to customize the message returned by the rest service, we can add a
@Autowired field to the
HelloController and call its
getGreeting method:
@RestController public class HelloController { @Autowired HelloProperties props; @RequestMapping("/hello") public String hello(@RequestParam String name) { return props.getGreeting()+name; } }
Relaunch your app again and try to access. You should get the default “Welcome yourname” message.
Now go ahead and try editing
application.properties and change the greeting to something else. Allthough we already have everything in place to correctly define the property at run-time, you’ll notice that the editor is still unaware of our newly minted property:
What’s still missing to make the editor aware is the
spring-configuration-metadata.json file. This file is created at build-time by the
spring-boot-configuration-processor which is a Java Annotation Processor. We have to add this processor to our project and make sure it is executed during project builds.
Add this to the
pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
Then perform a “Maven >> Update Project” to trigger a project configuration update. A Maven project configurator provided by STS will configure JDT APT and activate the processor for Eclipse builds. The warning will immediately disappear from the editor. You’ll also get proper Hover Info:
Now that the annotation processor has been activated, any future changes to your
HelloProperties class will trigger an automatic update of the json metadata. You can try it out by adding some extra properties, or renaming your
greeting property to something else. Warnings will appear / disappear as appropriate. If you are curious where your metadata file is, you can find it in
target/classes/META-INF. The file is there, even though Eclipse does its best to hide it from you. Eclipse does this with all files in a project’s output folder. You can get around this though by using the
Navigator view which doesn’t filter files as much and shows you a more direct view on the actual resources in your workspace. Open this view via “Window >> Show View >> Other >> Navigator”:
Note: We know that the manual step of adding the processor seems like an unnecessary complication. We have plans to automate this further in the future.
The End
I hope you enjoyed this Tutorial. Comments and questions are welcome. In another post, coming soon, I will show you more adanced uses of
@ConfigurationProperties and how the STS properties editor supports that.
Links
- Spring Tool Suite
- STS 3.6.4 release notes
- Cloud Foundry Eclipse
- Service Management Through Cloud Foundry Eclipse
- Java Buildpack for Cloud Foundry
- Spring Boot
- Getting Started Guide: Converting Boot project from Jar to War
- start.spring.io A Boot App to Generate ‘Getting Started’ Boot Apps
- Getting Started Guide: Building A Rest Service
- @ConfigurationProperties JavaDoc
|
http://spring.io/blog/2015/03/18/spring-boot-support-in-spring-tool-suite-3-6-4
|
CC-MAIN-2018-05
|
refinedweb
| 2,248 | 55.95 |
Hi Mark,
May be you can use the containers getNamedComponent method. Sample app is attached.
Regards Karel
-----Original Message-----
From: Ripgiblet [mailto:[email protected]]
Sent: Wednesday, January 22, 2014 4:06 AM
To: [email protected]
Subject: RE: in java how can i reference the instance define in a nested bxml's "bxml:id..."
This does not fix it, since property bindings still need to be in the same variable space
as the included .bxml files.
Not sure on the relevance of this link,
Karel Hübl wrote
> The model instance can be shared between parent and nested bxml files
> and you bound the gui control properties to shared model. It is little
> more complex, but you can see description of application archtecture
> we use
> here:
>
> cationArchitecture
Thanks anyway for the application example, might have some useful stuff in it, but it does
not access an included bxml file.
And I don't think it can since unless you use inline, you cannot access the main model space...
I am trying to use Pivot to move GUI layout etc. into the xml file (with Style defined in
the .json file) and all program logic etc. in JAVA. (Which I suspect is the core concept behind
pivot.) What I need to be able to do is access the nested objects:
mUsernameTextInput = (TextInput)namespace.get("usernameTextInput");
and for a nested object maybe something like...
mUsernameTextInput = (TextInput)namespace.get("tab2.usernameTextInput");
This is so I can use generic .bxml in different parts of the application, with the same id's...
or allow id's to be set by variables, like bxml:id="$TextInputTab".
Anyway I have since done a work arround, by changing the .bxml files so that no TextInput
fields are in generic bxml files and are in the same variable space, and then manually set
them to have unique ID's.
But its a bit messy...
Thanks for your response.
regards,
Mark.
--
View this message in context:
Sent from the Apache Pivot - Users mailing list archive at Nabble.com.
|
http://mail-archives.apache.org/mod_mbox/pivot-user/201401.mbox/%[email protected]%3E
|
CC-MAIN-2018-22
|
refinedweb
| 339 | 66.03 |
The if-else statement is the most basic of all the control flow statements. It tells the program to execute a certain block of code only if a particular test evaluates to
true.
1. If-else statement – Syntax
The format of an if-else statement is :
if (condition) { statement-1 } else { statement-2 }
The condition must be a boolean expression. That is, it must evaluate to
true or
false. If the condition evaluates to true,
statement-1 is executed. Otherwise,
statement-2 is executed.
2. else block is optional
The else part is optional. We may write a statement as :
if (condition) { statement-1 }
3. Java if-else statement example
Let’s see an example of if-else statement in Java.
public class JavaExample { public static void main(String[] args) { boolean condition = true; if(condition) { System.out.println("Condition is true"); } else { System.out.println("Condition is false"); } } }
Program output.
Condition is true
4. Nested if-else statement example
The if-else statements can be nested as well. They will be executed based on condition associated with them.
public class JavaExample { public static void main(String[] args) { int i = 10; if(i > 10) { System.out.println("Condition is greater than 10"); } else if(i < 10) { System.out.println("Condition is less than 10"); } else { System.out.println("Condition is equal to 10"); } } }
Program output.
Condition is equal to 10
5. Curly braces is needed if there are two or more statements to execute
Consider below program:
int num1, num2, num3 = 10; if (num1 > 40) num2 = num2 + 10; num3 = num3 + 10; else num2 = num2 - 10; num3 = num3 - 10;
Above program will not compile. What’s wrong with above program? Answer is that we can place only one statement between if and else, in any if-else statement.
Here, we want to execute two statements when
num1 is greater than 50. In this case, you need to bundle two statements into one block statement using curly braces, like so:
if (num1 > 40) { num2 = num2 + 10; num3 = num3 + 10; } else { num2 = num2 - 10; num3 = num3 - 10; }
6. Use ternary operator to replace simple if-else statement
We can also use the ternary operator in place of simple if-else statement. It can be used as java if-else short-hand.
For example,
// Use of an if-else statement if (num1 < num2) calc(num1); else calc(num2); // Use of a ternary operator calc(num1 < num2 ? num1 : num2)
Similar example could be for a case where you want to print the message “k is 15” if the value of an int variable k is equal to 15. Otherwise, you want to print the message “k is not 15”.
System.out.println(k == 15 ? "k is 15" : "k is not 15");
That’s all for if-else control flow statement in Java
Happy Learning !!
Ask Questions & Share Feedback
|
https://howtodoinjava.com/java/basics/if-else-statement-in-java/
|
CC-MAIN-2019-18
|
refinedweb
| 472 | 66.44 |
Class which manages topology outside of the one-hop and two-hop neighborhood in the OLSR domain. More...
#include <topology.hh>
A multimap providing lookup of topology entries by destination.
Used by TC updates.
A multimap providing lookup of topology entries by last hop.
Used by ANSN processing.
Internal method to: assert that the ANSNs for all TC entries originated by the node origin_addr are identical.
A full linear search of the TC record space is performed. Stubbed out if DETAILED_DEBUG is not defined.
TODO: Eliminate this function by refactoring the data structures; we SHOULD be able to check if the last ANSN from origin was empty, currently we don't do that.
Callback method to: delete an expiring TopologyEntry.
Given an address possibly corresponding to a MID entry, return the main address to which it would map.
Used by the protocol simulator. Requires a linear search of MID space, returns first match, there should be no other matches; no invariant.
Retrieve the Advertised Neighbor Set (ANS) for a given OLSR peer.
Typically used by protocol simulator.
Given the address of a node in the topology, retrieve the addresses from all TC entries originated by that node. Assumes that the "all entries for origin have same ANSN" invariant holds.
TODO: Also return the per-link ETX information.
Push topology set to the RouteManager for SPT computation.
Section 10: Route computation.
In ascending order, we push the rest of the known network topology, starting with the TC entries which would have been originated by two-hop neighbors. If we encounter incomplete TC information for the network topology, that is, there are no known nodes at a particular distance, we stop pushing topology to RouteManager.
TODO: Use ETX measurements for edge choice.
Update a Multiple Interface Declaration (MID) entry.
The entry will be created if it does not exist.
|
http://xorp.org/releases/current/docs/kdoc/html/classTopologyManager.html
|
CC-MAIN-2019-22
|
refinedweb
| 307 | 59.3 |
To use this renderer, the SLS file should contain a function called
run
which returns highstate data.
The highstate data is a dictionary containing identifiers as keys, and execution dictionaries as values. For example the following state declaration in YAML:
common_packages: pkg.installed: - pkgs: - curl - vim
translates to:
{'common_packages': {'pkg.installed': [{'pkgs': ['curl', 'vim']}]}}
In this module, a few objects are defined for you, giving access to Salt's execution functions, grains, pillar, etc. They are:
__salt__ - Execution functions (i.e.
__salt__['test.echo']('foo'))
__grains__ - Grains (i.e.
__grains__['os'])
__pillar__ - Pillar data (i.e.
__pillar__['foo'])
__opts__ - Minion configuration options
__env__ - The effective salt fileserver environment (i.e.
base). Also
referred to as a "saltenv".
__env__ should not be modified in a pure
python SLS file. To use a different environment, the environment should be
set when executing the state. This can be done in a couple different ways:
Using the
saltenv argument on the salt CLI (i.e.
salt '*' state.sls
foo.bar.baz saltenv=env_name).
By adding a
saltenv argument to an individual state within the SLS
file. In other words, adding a line like this to the state's data
structure:
{'saltenv': 'env_name'}
__sls__ - The SLS path of the file. For example, if the root of the base
environment is
/srv/salt, and the SLS file is
/srv/salt/foo/bar/baz.sls, then
__sls__ in that file will be
foo.bar.baz.
When writing a reactor SLS file the global context
data (same as context
{{ data }}
for states written with Jinja + YAML) is available. The following YAML + Jinja state declaration:
{% if data['id'] == 'mysql1' %} highstate_run: local.state.apply: - tgt: mysql1 {% endif %}
translates to:
if data['id'] == 'mysql1': return {'highstate_run': {'local.state.apply': [{'tgt': 'mysql1'}]}}
|
https://docs.saltstack.com/en/develop/ref/renderers/all/salt.renderers.py.html
|
CC-MAIN-2019-35
|
refinedweb
| 290 | 58.99 |
Output Window
This window can display status messages for various features in the integrated development environment (IDE). To display the Output window, select Output from the View menu. To close the Output window and shift focus back to the Editor, press the Escape (ESC) key.
Toolbar
- Show output from
Displays one or more output panes to view. Several panes of information might be available, depending upon which tools in the IDE have used the Output window to deliver messages to the user.
- Find Messsage in Code
Moves the insertion point in the Code Editor to the line that contains the selected build error.
- Go to Previous Message
Changes the focus in the Output window to the previous build error and moves the insertion point in the Code Editor to the line that contains that build error.
- Go to Next Message
Changes the focus in the Output window to the next build error and moves the insertion point in the Code Editor to the line that contains that build error.
- Clear all
Clears all text from the Output pane.
- Toggle Word Wrap
Turns the Word Wrap feature on and off in the Output pane. When Word Wrap is on, text in longer entries that extends beyond the viewing area is displayed on the following line.
Output Pane
The Output pane chosen in the Show output from list displays output from the source indicated.
Routing Messages to the Output Window
To display the Output window whenever you build a project, select the Show Output window when build starts option in the General, Projects and Solutions, Options Dialog Box., normally displayed in the DOS window, is routed to an Output pane when you select the Use Output Window option in the External Tools Dialog Box. Many other types of messages can be displayed in Output panes as well. For example, when TSQL syntax in a stored procedure is checked against a target database, the results are displayed in the Output window.
You can also program your own applications to write diagnostic messages at runtime to an Output pane. To do this, use members of the Debug class or Trace class in the System.Diagnostics namespace of the .NET Framework Class Library Reference. Members of the Debug class display output when you build Debug configurations of your solution or project; members of the Trace class display output when you build either Debug or Release configurations. For further information, see Diagnostic Messages in the Output Window.
In Visual C++, you can create custom build steps and build events whose warnings and errors are displayed and counted in the Output pane. Pressing F1 on a line of output will display an appropriate help topic. For further information, see Formatting the Output of a Custom Build Step or Build Event.
|
http://msdn.microsoft.com/en-us/library/3hk6fby3(v=vs.80).aspx
|
crawl-003
|
refinedweb
| 463 | 61.16 |
#include <ConnPolicy.hpp>
A connection policy object describes how a given connection should behave. Various parameters are available:
the connection type: DATA, BUFFER, CIRCULAR_BUFFER or UNBUFFERED. On a data connection, the reader will have only access to the last written value. On a buffered connection, a size number of elements can be stored until the reader reads them. BUFFER drops newer samples on full, CIRCULAR_BUFFER drops older samples on full. UNBUFFERED is only valid for output streaming connections..
the buffer policy, which controls how multiple connections to the same input or output port are handled in case of concurrent or subsequent read and write operations. See BufferPolicy to see all available options. Not all combinations of buffer policies and the pull flag are valid and non-standard transports can have additional restrictions.
if the connection is mandatory. Mandatory connections will let the write() call fail if the new sample cannot be successfully written. Default connections are not mandatory.
the transport type. Can be used to force a certain kind of transports. The number is a RTT transport id. When the transport type is zero, local in-process communication is used, unless one of the ports is remote. If the transport type deviates from the default remote transport of one of the ports, an out-of-band transport is setup using that type.
the data size. Some protocols require a hint on big the data will be, especially if the data is dynamically sized (like std::vector<double>). If you leave this empty (recommended), the protocol will try to guess it. The unit of data size is protocol dependent.
Definition at line 107 of file ConnPolicy.hpp.
Constructs a new ConnPolicy instance based on the current default settings as returned by ConnPolicy::Default().
Definition at line 109 of file ConnPolicy.cpp.
Constructs a new ConnPolicy instance based on the current default settings as returned by ConnPolicy::Default(), but overrides the type. You should not use this contructor anymore and prefer the static methods ConnPolicy::data(), ConnPolicy::buffer(), etc. instead.
Definition at line 122 of file ConnPolicy.cpp.
Constructs a new ConnPolicy instance based on the current default settings as returned by ConnPolicy::Default(), but overrides the type and lock_policy. You should not use this contructor anymore and prefer the static methods ConnPolicy::data(), ConnPolicy::buffer(), etc. instead.
Definition at line 135 of file ConnPolicy.cpp.
Definition at line 58 of file ConnPolicy.cpp.
Create a policy for a (lock-free) fifo buffer connection of a given size.
Definition at line 77 of file ConnPolicy.cpp.
Create a policy for a (lock-free) circular fifo buffer connection of a given size.
Definition at line 88 of file ConnPolicy.cpp.
Create a policy for a (lock-free) shared data connection of a given size.
Definition at line 99 of file ConnPolicy.cpp.
Returns the process-wide default ConnPolicy that serves as a template for new ConnPolicy instances.
This method returns a non-const reference and you can change the defaults. This is not thread-safe and should only be done very early in the deployment phase, before the first component is loaded and before connecting ports.
Definition at line 71 of file ConnPolicy.cpp.
Definition at line 112 of file ConnPolicy.hpp.
The policy on how buffer elements will be installed for this connection, which influences the behavior of reads and writes if the port has muliple connections. See BufferPolicy enum for possible options.
Definition at line 216 of file ConnPolicy.hpp.
Definition at line 113 of file ConnPolicy.hpp.
Definition at line 111 of file ConnPolicy.h 248 203 of file ConnPolicy.hpp.
Definition at line 117 of file ConnPolicy.hpp.
This is the locking policy on the connection
Definition at line 196 of file ConnPolicy.hpp.
Definition at line 116 of file ConnPolicy.hpp.
Whether the connection described by this connection policy is mandatory, which means that write operations will fail if the connection could not be served, e.g. due to a full input buffer or because of a broken remote connection. By default, all connections are mandatory.
Definition at line 232 of file ConnPolicy.hpp.
The maximum number of threads that will access the connection data or buffer object. This only needs to be specified for lock-free data structures. If 0, the number of threads will be determined by a simple heuristic depending on the read and write policies of the connection.
Definition at line 224 of file ConnPolicy.hpp. 256 of file ConnPolicy.hpp.
Definition at line 120 of file ConnPolicy.hpp.
If true, then the sink will have to pull data. Otherwise, it is pushed from the source. In both cases, the reader side is notified that new data is available by base::ChannelElementBase::signal()
Definition at line 209 of file ConnPolicy.hpp.
Definition at line 119 of file ConnPolicy.hpp.
If the connection is a buffered connection, the size of the buffer
Definition at line 193 of file ConnPolicy.hpp.
The prefered transport used. 0 is local (in process), a higher number is used for inter-process or networked communication transports.
Definition at line 238 of file ConnPolicy.hpp.
DATA, BUFFER or CIRCULAR_BUFFER
Definition at line 190 of file ConnPolicy.hpp.
Definition at line 110 of file ConnPolicy.hpp.
Definition at line 115 of file ConnPolicy.hpp.
|
http://docs.ros.org/en/lunar/api/rtt/html/classRTT_1_1ConnPolicy.html
|
CC-MAIN-2022-40
|
refinedweb
| 882 | 51.34 |
A C# Feature Request: Extension Classes
April 10, 2008 — c-sharp, code
As you may have noticed, I’m a big fan of extension methods in C# 3.0, but they aren’t without their limitations. The first one you notice when you use them is the lack of extension properties. Since I like properties more than I like extension methods, this really bummed me out. So for kicks, I’d like to propose a C# feature request: Extension classes.
What’s An Extension Class?
An extension class is a class that adds methods, properties, etc. to another
class. Given some class
Foo:
public class Foo { public int Value { get { return 3; } } }
My proposed syntax is:
public class FooExtensions this Foo { public int DoubledValue { get { return Value * 2; } } public void Hi() { Console.WriteLine("hi."); } }
The magic bit up there is the “
this Foo”. That basically says, “the ‘
this’
reference inside this class is actually of this other type ‘
Foo’”. As you
can see in the implementation of
DoubledValue, it’s accessing the
Value
property, which is defined in
Foo.
So, this solves the syntax problem for how to define an extension property. It makes sense, too, because if you’ve used extension methods, you’ve noticed that you always have to define them inside a “special” extension class anyway. This just moves the “extension-ness” indicator from the method level up to the containing class level.
What It’s Not
Just to be clear, this isn’t the same as inheriting, partial classes, or
open classes. There is no way to have a reference of type
FooExtensions,
because that class is not directly instantiable. It’s just decorating another
class. Likewise,
FooExtensions does not have priveleged access to
Foo.
It can only use public members just like outside code. And, of course,
FooExtensions can’t replace any methods in Foo. No open classes.
And Then?
OK, so we’ve got properties in the mix, is there anything else we could add?
public class FooExtensions this Foo { public static SomeMethod() { /* ... */ } }
How about static methods and properties? You could say there’s no value in doing this since you have to access statics through the class name anyway, but I disagree.
A design guideline that’s been floating around in C++ land for a long
time is “prefer non-member functions over member functions”. The idea is
that coupling and priveleged access to a class are bad, so if you can
implement something outside of the class, that’s better. However, if doing
that changes the calling convention, you’ve affected all your call sites with
what should be an implementation detail. I don’t want users to have to know
that
SomeMethod() was implemented outside of
Foo. That way, if I later
need to move it into
Foo (or vice versa), they aren’t affected.
Where This Is Going
So, if you can move more and more out of
Foo, what’s left in it? The
answer: data and validation.
Foo itself is the only class that can have
fields. In my world, the way I’d like to design classes is like this: the core
class
Foo contains its fields and provides accessors and mutators to prevent
it from being put in a bad state.
Foo basically is state and state change.
Almost everything else, the “things you can do with a
Foo” would be pulled
out into extension classes, likely in different namespaces. If you want to
format a
Foo for display,
UI.FooExtensions will have methods for that.
Need to serialize it?
Serialization.FooExtensions.
Aside from being crazy about decoupling, there’s some more reasoning behind this. It turns out that state is actually one of the trickiest parts of programming. Computer scientists have been wrestling with its implications since the dawn of programming, and have tried all sorts of ways to get around it, up to the point of trying to abolish it completely (sort of) in “pure” functional languages.
Now the lack of real-world use of languages like that kind of hints that state is inevitable. One of the most useful things about computers is that they remember things. However, isolating and minimizing where and how they remember things, I think, will encourage us to write software that’s easier to reason about and maintain.
|
http://journal.stuffwithstuff.com/2008/04/10/a-c-feature-request-extension-classes/
|
CC-MAIN-2014-49
|
refinedweb
| 720 | 64.71 |
-P: set compression to ZIP, (default is GZIP)
-C: set bytecode validation, see
-V for more info,
-d: decompile bytecodes from the memory in the specified swf
-u: decompile bytecodes from the loaded SWF file
-x: decompile bytecodes from the local filesystem, (swf file from the path)
-w: decompile all the swfs in the current project
-c: read a different set of default compilers, you can specify an.xsd file
-j: specify a keymap file to be used instead of the default one
-i: specify a swf file to be used instead of the current file
-a: specify a swf file for the input swf, (if the input swf is not specified the current file is used)
-m: specifies a macrofile, (which is a binary format that contains macrodefinitions and macrodata)
-o: specify an output SWF filename
-r: specify the base directory of the output directory,
-h: show help
-v: show version info.
.dfunc This command shows the type of the function used as return value for given function name. The command is pretty smart, it is able to handle multiple argument types. The list of the supported functions is build in when the command is run.
-h: show help
-?: show this help
-v: show version
-a: show all functions available
.dfunc is part of a utility called.funk, which is a simple AWK like file processing language. It can be used to filter huge amount of log files or filter large text files, extracting the lines you need.
This is an example of how you could filter the logs of a Tomcat server, by checking if the server started or not.
#!/usr/bin/env python
#
# $Id$
#
import sys
from functools import partial
def filterfunc(func):
def func_wrapper(filename, line, func_name):
try:
return func(func_name, filename, line)
except:
return 45cee15e9a
Decipher Textmessage Full Version 28
rescatando al soldado ryan latino 720p or 1080p
iVRy Driver for SteamVR (PSVR Premium Edition) Torrent Download [Torrent]
ESysBMWCodingv324364bit
mdaemon pro v13 0 4 crack 11
18 Wheels Of Steel Extreme Trucker 2 Authorization Code
donkey kong country 4 download
Download Keygen propresenter 5 register and unlock code hit
Full Version Scriptcase 6 Serial Number
dn dwivedi managerial economics pdf free
schritte international 1 tests pdf download
Animal Kingdom (2010) 720p BrRip X264 – 700MB – YIFY
HACK Comfy Photo Recovery v3.2 with Key [TorDigger]
EaseUS Data Recovery 13.6 {Crack Torrent} Serial key Latest 2019!
Burning Paper Logo After Effects Template (motion Array) Rarl
Gta 4 Setup1cbin
ESET NOD32 Antivirus Smart Security v 10.1.235.1 – CrackzSoft Serial Key keygen
creative emu10k1x-dbq sound driver for windows 7 free 19
Ileana Sararoiu O Batrana Intro Gara Download Zippy
3D SEXvILLA 2.0 the klub v9.1 Content Full Surprise
KeyMate is a software program that enables you to manage, create and recover USB Flash Drives using your computer’s keyboard. With KeyMate, you can easily create new USB drives on your PC. You can also recover USB keys that have been deleted, formatted, or have had their data corrupted.
Features:
It can be used to create or recover USB Flash Drive, including FAT12, FAT16, FAT32 and NTFS.
Ability to create USB Flash Drive can be done quickly and easily.
Supports 256-bit encryption.
USB Flash Drive can be encrypted with a password.
Ability to support virtually any file system, including NTFS, FAT16, FAT32 and FAT.
Ability to create any number of USB drives on one PC.
Ability to add a password on the USB Flash Drive.
Create bootable USB Flash Drive quickly and easily.
Easy-to-use interface.
Create new FAT16 USB Flash Drive, FAT32 USB Flash Drive and NTFS USB Flash Drive.
Incorporate password into the USB Flash Drive.
The program supports realtime and batch creation of USB Flash Drive.
Ability to change the size of USB Flash Drive (VFD), including small, medium, large and extra large.
Ability to change the name of USB Flash Drive.
No need to reboot your computer in order to access USB Flash Drive created by the program.
Easy to use.
Simplify the keystroke to create and recover USB Flash Drive.
Easy to learn.
One key to activate USB Flash Drive.
1. Open your computer and add KeyMate to the Add/Remove Programs of your computer.
2. Connect your USB Flash Drive to your computer.
3. When you finish to create the USB Flash Drive, press “Remove” and the software will close.
4. Open your computer and use the USB Flash Drive that was created by KeyMate to recover files, photos, data, etc.
FINAL BUY…
…what type of payment is the best and the fastest?
Basically, what are my options?
I know that there are a few companies that specialize in this.
I’m looking to establish myself and build a good reputation and business.
One person I know uses Paypal and the others use the Braintree Gateway.
A little more info about myself:
I’m currently 18, male, an american living in Germany
|
https://enricmcatala.com/tective-conan-watch-online-2k-subtitles-blu-ray-movies/
|
CC-MAIN-2022-27
|
refinedweb
| 826 | 62.88 |
Components and supplies
Necessary tools and machines
Apps and online services
About this project
About
It's Halloween night, and trick-or-treaters are walking through the neighborhood. Looking for something fun to do, they find a laser maze! In this competitive showdown, kids carefully navigate the laser beams while their parents plan their own strategy to win. One at a time, each person gets a chance to move through the maze without hitting any beams. If a beam gets hit, red flashing lights and an alarm signal that the game is over. If the person makes it to the end and hits the huge stop button, the win is accompanied by green flashing lights.
History
My original laser maze began in 2014, when I was just getting started with Arduino. The maze consisted of a single laser and multiple mirrors. While it was a fun experience, the many mirrors caused quite a bit of frustration. I knew I could improve, so I decided to replace the many mirrors with 15 laser modules. Each laser now corresponds to its own sensor, so any issue is now isolated much better. In addition to this improvement, the latest version features LED strips, DMX lighting, game-play music, sound effects, and Bluetooth control with the Arduino Manager app.
Pan/Tilt Brackets for Lasers
Each laser module is embedded into its own pan/tilt bracket. The brackets are made of scrap wood and contain three parts as seen in these pictures. The laser module is hot glued into the recessed hole and a barrel jack connection allows for easy setup.
Sensor Housings
In order for Arduino to detect when someone breaks a beam, photo-resistors are used to read the light intensity. Once the level drops below a certain threshold set by Arduino Manager, the fail sequence is triggered. Each of the 15 photo-resistors is hot glued within its own plastic container and covered with plastic wrap to diffuse the laser beam. Diffusing the laser beam once it reaches the sensor housing makes the aiming process much easier, because the beam does not have to be precisely focused on the photo-resistor.
Laser / Sensor Posts & Clusters
Each corner of the maze contains a wooden post with multiple lasers and sensors. The posts are cemented into buckets for stability. In addition to the 4 posts, lasers and sensors are fixed to the back, left, and right sides of the maze using pieces of wood. This creates even more possibilities for beam angles.
Wiring using Cat5 Cable
In order to make things easy, each post / cluster uses its own cat5 cable instead of having a separate cable for each sensor and laser. The pairs are color coded for each location, and all cables lead back to the central hub in the back of the garage. To save pins on Arduino, the sensors are divided into 4 groups and wired in series. The lasers are so bright when on, that even when multiple photo-resistors are wired in series, a broken beam can be easily detected.
Central Hub (aka mess of wires)
All of the cat5 cables feed to the central hub in the back of the garage. Since this project involves two shields (DMX and BLE) that compete for Arduino pins, two separate Arduinos are used, connected using I2C and the Wire library. Arduino Uno (master) uses the BLE shield to connect with Arduino Manager on an iPad. It also receives sensor data, controls laser status, reads button pushes, and sends messages to Arduino Pro Mini (slave). Since shields do not fit Arduino Pro Mini, each needed pin from the board is connected to the DMX shield with jumper wires. Arduino Uno sends lighting commands through the Wire Library, and Arduino Pro Mini receives them and fires the appropriate lighting cues via DMX. This project uses a large DMX LED wash light and LED strips for lighting.
Arduino Manager
An iPad controls the entire experience with Arduino Manager. The "LASER" button toggles laser visibility and enables game mode. The "aim" button can disable the the alarm and lights. S0-S3 are sensor values and T0-T3 are the respective thresholds, meaning if any of the sensor values goes below its threshold, the alarm and lights trigger. The threshold values can be changed on the fly from Arduino Manager. The "sound" icon represents the "sound" variable in the sketch. If any of the sensors go below their thresholds, sound = 1, and the alarm is played.
The iPad is also connected to a Bluetooth speaker which plays game music from Spotify. Check out my playlist here!
Code
Master (Arduino Uno)Arduino
/*2016 Halloween Laser Maze created by Sam Horne. * * Note: This sketch is a work in progress and contains a few redundant variables and declarations. * While it worked correctly for the maze, I will definetely improve it in the future. */ //#include <RBL_nRF8001.h> //#include <SPI.h> //#include <boards.h> #include <IOSControllerBLE.h> //Initialize Arduino Manager library. #include <Wire.h> //Initialize Wire library to connect both Arduinos. #define LASERPIN 6 //Lasers connected with transistor to Digital pin6. #define SENSOR0 0 //Four sensor groups, each containing photoresistors wired in series #define SENSOR1 2 #define SENSOR2 1 #define SENSOR3 3 boolean laservalue; //State of laser int buttonPin = 2; //Stop button int buttonState = 0; //Sensor variables. int S0; int S1; int S2; int S3; //Threshold variables int T0; int T1; int T2; int T3; int sound; //Variable controls audio widget in Arduino Manager int aim; //Allows lights and alarm to be disabled from Arduino Manager int laserState; int LASER = 0; byte x = 0; //For wire library transmission IOSControllerBLE iosController(&doWork,&doSync,&processIncomingMessages,&processOutgoingMessages,&processAlarms,&deviceConnected,&deviceDisconnected); //Necessary for Arduino Manager void setup() { ble_begin(); Wire.begin(); Serial.begin(115200); // pinMode(CONNECTIONPIN,OUTPUT); pinMode(buttonPin , INPUT); //Stop button pinMode(LASERPIN,OUTPUT); //Laser pinMode(SENSOR0, INPUT); pinMode(SENSOR1,INPUT); pinMode(SENSOR2, INPUT); pinMode(SENSOR3, INPUT); laservalue = 0; /Set the laser value. digitalWrite(LASERPIN,laservalue); //Set the laser value. } void loop() { iosController.loop(); buttonState = digitalRead(buttonPin); if(buttonState == HIGH) { //User presses stop button to win game. Wire.beginTransmission(9); //Begin transmitting on channel 9. Wire.write(9); //Send a single byte (9) which triggers the win sequence on the Pro Mini. Wire.endTransmission(); LASER = LOW; //Laser turns off if someone wins. aim = HIGH; //This prevents the alarm from sounding when the sensor values drop due to the inactive laser. iosController.writeMessage("aim", HIGH); //Sync switch positions. digitalWrite(LASERPIN,LOW); //Laser turns off if someone wins. iosController.writeMessage("laserState", LOW); //Sync switch positions. delay(1000); } if (S0 < T1 < T2 < T3 < T { sound = 0; //If no sensor events occur, no sound will happen. } } void doWork() { //Read the sensor group values from the analog pins. delay(5); S1 = analogRead(SENSOR1); delay(5); S2 = analogRead(SENSOR2); delay(5); S3 = analogRead(SENSOR3); delay(5); S0 = analogRead(SENSOR0); iosController.writeMessage("S0",S0); } void doSync (char *variable) { } void processIncomingMessages(char *variable, char *value) { if (strcmp(variable,"LASER")==0) { //Process incoming messages from Arduino Manager laservalue = atoi(value); laserState = atoi(value); digitalWrite(LASERPIN,laservalue); //If LASER switch goes HIGH, turn on laser } if (strcmp(variable,"T0")==0) { T0 = atoi(value); } if (strcmp(variable,"T1")==0) { T1 = atoi(value); } if (strcmp(variable,"T2")==0) { T2 = atoi(value); } if (strcmp(variable,"T3")==0) { T3 = atoi(value); } if (strcmp(variable,"aim")==0) { //Sync aim value. aim = atoi(value); } } void processOutgoingMessages() { //Sync sensor values to Arduino Manager. iosController.writeMessage("S0",S0); iosController.writeMessage("S1",S1); iosController.writeMessage("S2",S2); iosController.writeMessage("S3",S3); iosController.writeMessage("sound", sound); iosController.writeMessage("x",x); } void deviceConnected () { } void deviceDisconnected () { } #ifdef ALARMS_SUPPORT void processAlarms(char *alarm) { iosController.log("Alarm fired: "); iosController.logLn(alarm); } #endif float getVoltage(int pin) { return (analogRead(pin) * .004882813); // converting from a 0 to 1023 digital range // to 0 to 5 volts (each 1 reading equals ~ 5 millivolts }
Slave (Arduino Pro Mini)Arduino
This code is not essential to the project, and the project can function without the second Arduino (lighting).
#include <DmxSimple.h> #include <Wire.h> #include <wiring.h> int DE = 2; //DMX enable int x = 0; //Wire transmission variable int v = 15; // brightness value void setup() { /* The most common pin for DMX output is pin 3, which DmxSimple ** uses by default. If you need to change that, do it here. */ DmxSimple.usePin(4); pinMode(DE, OUTPUT); digitalWrite(DE, HIGH); //DMX enable DmxSimple.write(1, 0); //Startup scene DmxSimple.write(2, 0); DmxSimple.write(3, 0); DmxSimple.write(27, 10); Wire.begin(9); Wire.onReceive(receiveEvent); Serial.begin(115200); DmxSimple.maxChannel(27); } void receiveEvent(int bytes) { x = Wire.read(); // read one character from the I2C } void loop() { Serial.println(x); if (x == 9) { //Flashing green sequence DmxSimple.write(6, 0); DmxSimple.write(18, 0); DmxSimple.write(15, 0); DmxSimple.write(27, 0); DmxSimple.write(5, 255); DmxSimple.write(8, 255); DmxSimple.write(11, 255); DmxSimple.write(14, 255); DmxSimple.write(17, 255); DmxSimple.write(20, 255); DmxSimple.write(23, 255); DmxSimple.write(26, 255); DmxSimple.write(41, 255); delay(100); DmxSimple.write(5, 0); DmxSimple.write(8, 0); DmxSimple.write(11, 0); DmxSimple.write(14, 0); DmxSimple.write(17, 0); DmxSimple.write(20, 0); DmxSimple.write(23, 0); DmxSimple.write(26, 0); DmxSimple.write(41, 0); delay(100); } if (x == 0) { //Flashing red sequence. DmxSimple.write(6, 0); DmxSimple.write(9, 0); DmxSimple.write(12, 0); DmxSimple.write(15, 0); DmxSimple.write(18, 0); DmxSimple.write(21, 0); DmxSimple.write(24, 0); DmxSimple.write(27, 0); DmxSimple.write(42, 0); DmxSimple.write(4, 255); DmxSimple.write(7, 255); DmxSimple.write(10, 255); DmxSimple.write(13, 255); DmxSimple.write(16, 255); DmxSimple.write(19, 255); DmxSimple.write(22, 255); DmxSimple.write(25, 255); DmxSimple.write(40, 255); delay(100); DmxSimple.write(4, 0); DmxSimple.write(7, 0); DmxSimple.write(10, 0); DmxSimple.write(13, 0); DmxSimple.write(16, 0); DmxSimple.write(19, 0); DmxSimple.write(22, 0); DmxSimple.write(25, 0); DmxSimple.write(40, 0); delay(100); } delay(10); }
Schematics
Author
Published onJanuary 15, 2017
Members who respect this project
you might like
|
https://create.arduino.cc/projecthub/samhorne/halloween-laser-maze-2128f6
|
CC-MAIN-2019-43
|
refinedweb
| 1,664 | 60.92 |
Network Configuration
TL;DR
When Docker starts, it creates a virtual interface named
docker0 on
the host machine. It randomly chooses an address and subnet from the
private range defined by RFC 1918
that are not in use on the host machine, and assigns it to
docker0.
Docker made the choice
172.17.42.1/16 when I started it a few minutes
ago, for example — a 16-bit netmask providing 65,534 addresses for the
host machine and its containers. The MAC address is generated using the
IP address allocated to the container to avoid ARP collisions, using a
range from
02:42:ac:11:00:00 to
02:42:ac:11:ff:ff.
Note: This document discusses advanced networking configuration and options for Docker. In most cases you won't need this information. If you're looking to get started with a simpler explanation of Docker networking and an introduction to the concept of container linking see the Docker User Guide.
But
docker0 is no ordinary interface. It is a virtual Ethernet
bridge that automatically forwards packets between any other network
interfaces that are attached to it. This lets containers communicate
both with the host machine and with each other. Every time Docker
creates a container, it creates a pair of “peer” interfaces that are
like opposite ends of a pipe — a packet sent on one will be received on
the other. It gives one of the peers to the container to become its
eth0 interface and keeps the other peer, with a unique name like
vethAQI2QT, out in the namespace of the host machine. By binding
every
veth* interface to the
docker0 bridge, Docker creates a
virtual subnet shared between the host machine and every Docker
container.
The remaining sections of this document explain all of the ways that you can use Docker options and — in advanced cases — raw Linux networking commands to tweak, supplement, or entirely replace Docker's default networking configuration.
Quick Guide to the Options
Here is a quick list of the networking-related Docker command-line options, in case it helps you find the section below that you are looking for.
Some networking command-line options can only be supplied to the Docker server when it starts up, and cannot be changed once it is running:
-b BRIDGEor
--bridge=BRIDGE— see Building your own bridge
--bip=CIDR— see Customizing docker0
--fixed-cidr— see Customizing docker0
--fixed-cidr-v6— see IPv6
-H SOCKET...or
--host=SOCKET...— This might sound like it would affect container networking, but it actually faces in the other direction: it tells the Docker server over what channels it should be willing to receive commands like “run container” and “stop container.”
--icc=true|false— see Communication between containers
--ip=IP_ADDRESS— see Binding container ports
--ipv6=true|false— see IPv6
--ip-forward=true|false— see Communication between containers and the wider world
--iptables=true|false— see Communication between containers
--mtu=BYTES— see Customizing docker0
There are two networking options that can be supplied either at startup
or when
docker run is invoked. When provided at startup, set the
default value that
docker run will later use if the options are not
specified:
--dns=IP_ADDRESS...— see Configuring DNS
--dns-search=DOMAIN...— see Configuring DNS
Finally, several networking options can only be provided when calling
docker run because they specify something specific to one container:
-h HOSTNAMEor
--hostname=HOSTNAME— see Configuring DNS and How Docker networks a container
--link=CONTAINER_NAME_or_ID:ALIAS— see Configuring DNS and Communication between containers
--net=bridge|none|container:NAME_or_ID|host— see How Docker networks a container
--mac-address=MACADDRESS...— see How Docker networks a container
-p SPECor
--publish=SPEC— see Binding container ports
-Por
--publish-all=true|false— see Binding container ports
The following sections tackle all of the above topics in an order that moves roughly from simplest to most complex.
Configuring DNS.
-h HOSTNAMEor
--hostname=HOSTNAME— sets the hostname by which the container knows itself. This is written into
/etc/hostname, into
/etc/hostsas the name of the container's host-facing IP address, and is the name that
/bin/bashinside the container will display inside its prompt. But the hostname is not easy to see from outside the container. It will not appear in
docker psnor in the
/etc/hostsfile of any other container.
--link=CONTAINER_NAME_or_ID:ALIAS— using this option as you
runa container gives the new container's
/etc/hostsan extra entry named
ALIASthat points to the IP address of the container identified by
CONTAINER_NAME_or_ID. This lets processes inside the new container connect to the hostname
ALIASwithout having to know its IP. The
--link=option is discussed in more detail below, in the section Communication between containers. Because Docker may assign a different IP address to the linked containers on restart, Docker updates the
ALIASentry in the
/etc/hostsfile of the recipient containers.
--dns=IP_ADDRESS...— sets the IP addresses added as
serverlines to the container's
/etc/resolv.conffile. Processes in the container, when confronted with a hostname not in
/etc/hosts, will connect to these IP addresses on port 53 looking for name resolution services.
--dns-search=DOMAIN...— sets the domain names that are searched when a bare unqualified hostname is used inside of the container, by writing
searchlines into the container's
/etc/resolv.conf. When a container process attempts to access
hostand the search domain
example.comis set, for instance, the DNS logic will not only look up
hostbut also
host.example.com. Use
--dns-search=.if you don't wish to set the search domain.
Note that Docker, in the absence of either of the last two options
above, will make
/etc/resolv.conf inside of each container look like
the
/etc/resolv.conf of the host machine where the
docker daemon is
running. You might wonder what happens when the host machine's
/etc/resolv.conf file changes. The
docker daemon has a file change
notifier active which will watch for changes to the host DNS configuration. or
--dns-search) have been used to modify the
default host configuration, then the replacement with an updated host's
/etc/resolv.conf will not happen as well..
Communication between containers and the wider world
Whether a container can talk to the world is governed by two factors.
Is the host machine willing to forward IP packets? This is governed by the
ip_forwardsystem parameter. Packets can only pass between containers if this parameter is
1. Usually you will simply leave the Docker server at its default setting
--ip-forward=trueand Docker will go set
ip_forwardto
1for you when the server starts up. To check the setting or turn it on manually:
$ cat /proc/sys/net/ipv4/ip_forward 0 $ echo 1 > /proc/sys/net/ipv4/ip_forward $ cat /proc/sys/net/ipv4/ip_forward 1
Many using Docker will want
ip_forwardto be on, to at least make communication possible between containers and the wider world.
May also be needed for inter-container communication if you are in a multiple bridge setup.
Do your
iptablesallow this particular connection? Docker will never make changes to your system
iptablesrules if you set
--iptables=falsewhen the daemon starts. Otherwise the Docker server will append forwarding rules to the
DOCKERfilter (on Ubuntu, by editing the
DOCKER_OPTS variable in
/etc/default/docker and restarting the Docker server). Docker has more documentation on
this subject — see the linking Docker containers
page for further details..
Binding container ports to the host
By default Docker containers can make connections to the outside world,
but the outside world cannot connect to containers. Each outgoing
connection will appear to originate from one of the host machine's own
IP addresses thanks to an
iptables masquerading rule on the host
machine that the Docker server creates when it starts:
# ...
But if you want containers to accept incoming connections, you will need
to provide special options when invoking
docker run. These options
are covered in more detail in the Docker User Guide
page. There are two approaches.
First, you can supply
-P or
--publish-all=true|false to
docker run
which is a blanket operation that identifies every port with an
EXPOSE
line in the image's
Dockerfile and maps it to a host port somewhere in
the range 49153–65535. This tends to be a bit inconvenient, since you
then have to run other
docker sub-commands to learn which external
port a given service was mapped to.
More convenient is the
-p SPEC or
--publish=SPEC option which lets
you be explicit about exactly which external port on the Docker server —
which can be any port at all, not just those in the 49153-65535 block — (on
Ubuntu, by editing
DOCKER_OPTS in
/etc/default/docker) and add the
option
--ip=IP_ADDRESS. Remember to restart your Docker server after
editing this setting.
Again, this topic is covered without all of these low-level networking details in the Docker User Guide document if you would like to use that as your port redirection reference instead.
IPv6
As we are running out of IPv4 addresses the IETF has standardized an IPv4 successor, Internet Protocol Version 6 , in RFC 2460. Both protocols, IPv4 and IPv6, reside on layer 3 of the OSI model.
IPv6 -d - daemon via the gateway
fe80::1 on
eth0:::/80 with a range from
2001:db8:23:42:0:0:0:0
to
2001:db8:23:42:0 the host via its
docker0 interface whereas it level 2 switch with a level
/68 subnets for the hosts and
/80 for the containers. This way you can use 4096 hosts with 16
/80 subnets
each.
Every configuration in the diagram that is visualized.
Customizing.
Docker configures
docker0 with an IP address, netmask and IP
allocation range. The host machine can both receive and send packets to
containers connected to the bridge, and gives it an MTU — the maximum
transmission unit or largest packet length that the interface will
allow — of either 1,500 bytes or else a more specific value copied from
the Docker host's interface that supports its default route. These
options are configurable at server startup:
--bip=CIDR— supply a specific IP address and netmask for the
docker0bridge, using standard CIDR notation like
192.168.1.5/24.
--fixed-cidr=CIDR— restrict the IP range from the
docker0subnet, using the standard CIDR notation like
172.167.1.0/28. This range must be and IPv4 range for fixed IPs (ex: 10.20.0.0/16) and must be a subset of the bridge IP range (
docker0or set using
--bridge). For example with
--fixed-cidr=192.168.1.0/25, IPs for your containers will be chosen from the first half of
192.168.1.0/24subnet.
--mtu=BYTES— override the maximum packet length on
docker0.
On Ubuntu you would add these to the
DOCKER_OPTS setting in
/etc/default/docker on your Docker host and restarting the Docker
service.
Once you have one or more containers up and running, you can confirm
that Docker has properly connected them to the
docker0 bridge by
running the
brctl command on the host machine and looking at the
interfaces column of the output. Here is a host with two different
containers connected:
# Display bridge info $ sudo brctl show bridge name bridge id STP enabled interfaces docker0 8000.3a1d7362b4ee no veth65f9 vethdda6
If the
brctl command is not installed on your Docker host, then on
Ubuntu you should be able to run
sudo apt-get install bridge-utils to
install it.
Finally, the
docker0 Ethernet bridge settings are used every time you
create a new container. Docker selects a free IP address from the range
available on the bridge each time you
docker run a new container, and
configures the container's
eth0 interface with that IP address and the
bridge's netmask. The Docker host's own IP address on the bridge is
used as the default gateway by which each container reaches the rest of
the Internet.
# The network, as seen from a container $ sudo docker run -i -t --rm base /bin/bash $$ ip addr show eth0 24: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 32:6f:e0:35:57:91 brd ff:ff:ff:ff:ff:ff inet 172.17.0.3/16 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::306f:e0ff:fe35:5791/64 scope link valid_lft forever preferred_lft forever $$ ip route default via 172.17.42.1 dev eth0 172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.3 $$ exit
Remember that the Docker host will not be willing to forward container
packets out on to the Internet unless its
ip_forward system setting is
1 — see the section above on Communication between
containers for details.
Building your own bridge
If you want to take Docker out of the business of creating its own
Ethernet bridge entirely, you can set up your own bridge before starting
Docker and use
-b BRIDGE or
--bridge=BRIDGE to tell Docker to use
your bridge instead. If you already have Docker up and running with its
old
docker0 still configured, you will probably want to begin by
stopping the service and removing the interface:
# Stopping Docker and removing docker0 $ sudo service docker stop $ sudo ip link set dev docker0 down $ sudo brctl delbr docker0 $ sudo iptables -t nat -F POSTROUTING
Then, before starting the Docker service, create your own bridge and
give it whatever configuration you want. Here we will create a simple
enough bridge that we really could just have used the options in the
previous section to customize
docker0, but it will be enough to
illustrate the technique.
# Create our own bridge $ sudo brctl addbr bridge0 $ sudo ip addr add 192.168.5.1/24 dev bridge0 $ sudo ip link set dev bridge0 up # Confirming that our bridge is up and running $ # Tell Docker about it and restart (on Ubuntu) $ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker $ sudo service docker start # Confirming new outgoing NAT masquerade is set up $ sudo iptables -t nat -L -n ... Chain POSTROUTING (policy ACCEPT) target prot opt source destination MASQUERADE all -- 192.168.5.0/24 0.0.0.0/0
The result should be that the Docker server starts successfully and is now prepared to bind containers to the new bridge. After pausing to verify the bridge's configuration, try creating a container — you will see that its IP address is in your new IP address range, which Docker will have auto-detected.
Just as we learned in the previous section, you can use the
brctl show
command to see Docker add and remove interfaces from the bridge as you
start and stop containers, and can run
ip addr and
ip route inside a
container to see that it has been given an address in the bridge's IP
address range and has been told to use the Docker host's IP address on
the bridge as its default gateway to the rest of the Internet.
How Docker networks a container
While Docker is under active development and continues to tweak and improve its network configuration logic, the shell commands in this section are rough equivalents to the steps that Docker takes when configuring networking for each new container.
Let's review a few basics.
To communicate using the Internet Protocol (IP), a machine needs access
to at least one network interface at which packets can be sent and
received, and a routing table that defines the range of IP addresses
reachable through that interface. Network interfaces do not have to be
physical devices. In fact, the
lo loopback interface available on
every Linux machine (and inside each Docker container) is entirely
virtual — the Linux kernel simply copies loopback packets directly from
the sender's memory into the receiver's memory.
Docker uses special virtual interfaces to let containers communicate with the host machine — pairs of virtual interfaces called “peers” that are linked inside of the host machine's kernel so that packets can travel between them. They are simple to create, as we will see in a moment.
The steps with which Docker configures a container are:
Create a pair of peer virtual interfaces.
Give one of them a unique name like
veth65f9, keep it inside of the main Docker host, and bind it to
docker0or whatever bridge Docker is supposed to be using.
Toss the other interface over the wall into the new container (which will already have been provided with an
lointerface) and rename it to the much prettier name
eth0since, inside of the container's separate and unique network interface namespace, there are no physical interfaces with which this name could collide.
Set the interface's MAC address according to the
--mac-addressparameter or generate a random one.
Give the container's
eth0a new IP address from within the bridge's range of network addresses, and set its default route to the IP address that the Docker host owns on the bridge. If available the IP address is generated from the MAC address. This prevents ARP cache invalidation problems, when a new container comes up with an IP used in the past by another container with another MAC.
With these steps complete, the container now possesses an
eth0
(virtual) network card and will find itself able to communicate with
other containers and the rest of the Internet.
You can opt out of the above process for a particular container by
giving the
--net= option to
docker run, which takes four possible
values.
--net=bridge— The default action, that connects the container to the Docker bridge as described above.
--net=host— Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick
ip addrcommand will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces.. You should use this option with caution.
--net=container:NAME_or_ID— Tells Docker to put this container's processes inside of the network stack that has already been created inside of another container. The new container's processes will be confined to their own filesystem and process list and resource limits, but will share the same IP address and port numbers as the first container, and processes on the two containers will be able to connect to each other over the loopback interface.
--net=none— Tells Docker to put the container inside of its own network stack but not to take any steps to configure its network, leaving you free to build any of the custom configurations explored in the last few sections of this document.
To get an idea of the steps that are necessary if you use
--net=none
as described in that last bullet point, here are the commands that you
would run to reach roughly the same configuration as if you had let
Docker do all of the configuration:
# At one shell, start a container and # leave its shell idle and running $ sudo docker run -i -t --rm --net=none base /bin/bash root@63f36fc01b5f:/# # At another shell, learn the container process ID # and create its namespace entry in /var/run/netns/ # for the "ip netns" command we will be using below $ sudo docker inspect -f '{{.State.Pid}}' 63f36fc01b5f 2778 $ pid=2778 $ sudo mkdir -p /var/run/netns $ sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid # Check the bridge's IP address and netmask $ ip addr show docker0 21: docker0: ... inet 172.17.42.1/16 scope global docker0 ... # Create a pair of "peer" interfaces A and B, # bind the A end to the bridge, and bring it up $ sudo ip link add A type veth peer name B $ sudo brctl addif docker0 A $ sudo ip link set A up # Place B inside the container's network namespace, # rename to eth0, and activate it with a free IP $ sudo ip link set B netns $pid $ sudo ip netns exec $pid ip link set dev B name eth0 $ sudo ip netns exec $pid ip link set eth0 address 12:34:56:78:9a:bc $ sudo ip netns exec $pid ip link set eth0 up $ sudo ip netns exec $pid ip addr add 172.17.42.99/16 dev eth0 $ sudo ip netns exec $pid ip route add default via 172.17.42.1
At this point your container should be able to perform networking operations as usual.
When you finally exit the shell and Docker cleans up the container, the
network namespace is destroyed along with our virtual
eth0 — whose
destruction in turn destroys interface
A out in the Docker host and
automatically un-registers it from the
docker0 bridge. So everything
gets cleaned up without our having to run any extra commands! Well,
almost everything:
# Clean up dangling symlinks in /var/run/netns find -L /var/run/netns -type l -delete
Also note that while the script above used modern
ip command instead
of old deprecated wrappers like
ipconfig and
route, these older
commands would also have worked inside of our container. The
ip addr
command can be typed as
ip a if you are in a hurry.
Finally, note the importance of the
ip netns exec command, which let
us reach inside and configure a network namespace as root. The same
commands would not have worked if run inside of the container, because
part of safe containerization is that Docker strips container processes
of the right to configure their own networks. Using
ip netns exec is
what let us finish up the configuration without having to take the
dangerous step of running the container itself with
--privileged=true.
Tools and Examples
Before diving into the following sections on custom network topologies, you might be interested in glancing at a few external tools or examples of the same kinds of configuration. Here are two:
Jérôme Petazzoni has created a
pipeworkshell script to help you connect together containers in arbitrarily complex scenarios:
Brandon Rhodes has created a whole network topology of Docker containers for the next edition of Foundations of Python Network Programming that includes routing, NAT'd firewalls, and servers that offer HTTP, SMTP, POP, IMAP, Telnet, SSH, and FTP:
Both tools use networking commands very much like the ones you saw in the previous section, and will see in the following sections.
Building a point-to-point connection
By default, Docker attaches all containers to the virtual subnet
implemented by
docker0. You can create containers that are each
connected to some different virtual subnet by creating your own bridge
as shown in Building your own bridge, starting each
container with
docker run --net=none, and then attaching the
containers to your bridge with the shell commands shown in How Docker
networks a container.
But sometimes you want two particular containers to be able to communicate directly without the added complexity of both being bound to a host-wide Ethernet bridge.
The solution is simple: when you create your pair of peer interfaces, simply throw both of them into containers, and configure them as classic point-to-point links. The two containers will then be able to communicate directly (provided you manage to tell each container the other's IP address, of course). You might adjust the instructions of the previous section to go something like this:
# Start up two containers in two terminal windows $ sudo docker run -i -t --rm --net=none base /bin/bash root@1f1f4c1f931a:/# $ sudo docker run -i -t --rm --net=none base /bin/bash root@12e343489d2f:/# # Learn the container process IDs # and create their namespace entries $ sudo docker inspect -f '{{.State.Pid}}' 1f1f4c1f931a 2989 $ sudo docker inspect -f '{{.State.Pid}}' 12e343489d2f 3004 $ sudo mkdir -p /var/run/netns $ sudo ln -s /proc/2989/ns/net /var/run/netns/2989 $ sudo ln -s /proc/3004/ns/net /var/run/netns/3004 # Create the "peer" interfaces and hand them out $ sudo ip link add A type veth peer name B $ sudo ip link set A netns 2989 $ sudo ip netns exec 2989 ip addr add 10.1.1.1/32 dev A $ sudo ip netns exec 2989 ip link set A up $ sudo ip netns exec 2989 ip route add 10.1.1.2/32 dev A $ sudo ip link set B netns 3004 $ sudo ip netns exec 3004 ip addr add 10.1.1.2/32 dev B $ sudo ip netns exec 3004 ip link set B up $ sudo ip netns exec 3004 ip route add 10.1.1.1/32 dev B
The two containers should now be able to ping each other and make
connections successfully. Point-to-point links like this do not depend
on a subnet nor a netmask, but on the bare assertion made by
ip route
that some other single IP address is connected to a particular network
interface.
Note that point-to-point links can be safely combined with other kinds
of network connectivity — there is no need to start the containers with
--net=none if you want point-to-point links to be an addition to the
container's normal networking instead of a replacement.
A final permutation of this pattern is to create the point-to-point link
between the Docker host and one container, which would allow the host to
communicate with that one container on some single IP address and thus
communicate “out-of-band” of the bridge that connects the other, more
usual containers. But unless you have very specific networking needs
that drive you to such a solution, it is probably far preferable to use
--icc=false to lock down inter-container communication, as we explored
earlier.
Editing networking config files
Starting with Docker v.1.2.0, you can now edit
/etc/hosts,
/etc/hostname
and
/etc/resolve.conf in a running container. This is useful if you need
to install bind or other services that might override one of those files.
Note, however, that changes to these files will not be saved by
docker commit, nor will they be saved during
docker run.
That means they won't be saved in the image, nor will they persist when a
container is restarted; they will only "stick" in a running container.
|
https://docs.docker.com/articles/networking/
|
CC-MAIN-2015-14
|
refinedweb
| 4,392 | 54.66 |
07-20-2011 10:44 AM
The results of the Delay, Timer, and Sleep functions in Lab Windows 2010 seem to vary greatly. This experiment was done on a Windows XP SP3 32-bit system and a WIndows 7 64-bit system using this code right at the start of main():
double time1;
double time2;
char s[100];
time1 = Timer ();
sprintf (s, "Time = %f, 0 sec", time1);
MessagePopup ("first", s);
time1 = Timer ();
Delay(5.0);
time2 = Timer ();
sprintf (s, "Time = %f (%f - %f), 5 sec with Delay()",
time2 - time1, time2, time1);
MessagePopup ("second", s);
time1 = Timer ();
Sleep(5000);
time2 = Timer ();
sprintf (s, "Time = %f (%f - %f), another 5 sec with Sleep()",
time2 - time1, time2, time1);
MessagePopup ("third", s);
Reading the popups and measuring elapsed time with a stopwatch (between clicking OK and display of the next popup):
Windows XP SP3 32-bit:
useDefaultTimer registry setting = False (the default setting)
Delay: measured 24 sec, Timer delta: 5.001004
Sleep: measured 5 sec, Timer delta: 1.040915
useDefaultTimer = True
Delay: measured 3 sec, Timer delta: 4293204.328125 (this varies)
Sleep: measured 5 sec, Timer delta: 705.031250 (this is fairly consistent)
Windows 7 64-bit:
useDefaultTimer registry setting = False (the default setting)
Delay: measured 5 sec, Timer delta: 5.001004
Sleep: measured 5 sec, Timer delta: 4.994530
useDefaultTimer = True
Delay: measured 3 sec, Timer delta: 2532.000000 (this varies wildly)
Sleep: measured 5 sec, Timer delta: 705.032704 (this is fairly consistent)
What could be happening here?
Thanks,
Brian
07-20-2011 02:40 PM - edited 07-20-2011 02:42 PM
Delay() NI function has had curious behavior noted before, there are a couple of threads on this forum about it.
NI told me that Delay() incorporates a "ProcessSystemEvents" at least some of the time (?) and others have claimed it simply spinlocks.
Some of us wind up creating a delay function using the WinAPI Sleep() or SleepEx() function as it's more reliable (as your data shows) since the OS is simply putting the thread to sleep and there's nothing else that can come into play, though the Windows OS has the final say as to when your thread gets rescheduled - you are vulnerable to cheduling activity decisions made by the OS.
I almost never use Delay().
Having said that, you shouldn't be seeing these types of errors on Delay() unless you've got something going on that a ProcessSystemEvents call (which is maybe embedded in the NI Delay() function) gets hung up and spends a lot of time processing.
Do the times you measure correspond to how long you wait before clicking the OK popup button?
07-20-2011 03:16 PM
Yes, the "measured" times are the approximate time in seconds (as manually measured with a stopwatch) from one "OK" click until the next dialog box appears. This test code is before the main panel is loaded or displayed so hopefully there isn't too much else going on to skew the results.
Using Sleep() sounds like a good idea anyway. Timer() doesn't seem all too useful on the XP machine. It is very curious that on XP with useDefaultTimer = false that Delay() appears to conform to Timer() in that they're both off by about a factor of 5.
07-21-2011 02:33 AM
Hi Brian,
I ran your code in Interactive Execution window on CVI 6.0 (only version I have on this computer) and the results don't vary at all, let alone by those wild figures.
Delay results in 5.001 sec and Sleep results in 4.988 seconds as the Timer() difference measures.
These are also consistent with my iPod's stopwatch.
Did you loop them some large number of times and picked the wildest results or do they act so weird each time you call them?
Did I understand your experiment setup wrong or were you missing something?
07-21-2011 08:09 AM
No, the same behavior occurs every single time. I didn't do anything special in the experiment; the program just has that code sitting in "main()" and that's all.
Since yesterday I asked someone else to run the same code on a different but similar computer to my XP SP3 32-bit machine. The other computer works correctly and doesn't show the same results that I see.
Another thing that may or may not be significant is that I had LabWindows/CVI 8.5 installed before installing 2010, so both of these are installed on my machine. I tried building and running the same code under 8.5 and got the same bad results for the various cases (Delay and Sleep and useDefaultTimer True and False). But the other computer that worked correctly is also in the same state; 8.5 was installed and then 2010 was installed after.
I have not yet tried to uninstall anything, but I was thinking about uninstalling everything and reinstalling only version 2010, especially since now the problem appears isolated to the one computer.
08-02-2011 06:53 AM
PROBLEM SOLVED!
Reinstalling LabWindows didn't help, but I tried the "counter.cws" sample program and still got poor results. This uses QueryPerformanceCounter() and I saw that its values were off right along with Delay(). This pointed to a problem with this specific computer, not with LabWindows. Some research showed someone else having a similar result using QueryPerformanceCounter() on a computer similar to mine, but not on other computers they tried.
A BIOS upgrade did the trick. Now for the default setting (useDefaultTimer = False) everything works great!
The other setting (useDefaultTimer = True) still works poorly; on all machines I've tried, a 5-second Delay() is only 3 seconds, and the Timer() values don't make any sense. But I have no reason not to use the default setting, so all is well.
08-08-2011 04:49 PM
Sleep? what library is this in?
08-08-2011 05:03 PM
Sleep() and SleepEx() are part of the Windows API, sometimes called the WinAPI, and if you're on a 32 bit Windows OS it's called the Win32API.
You include windows.h as the first include (so that the NI header files can accommodate the windows.h definitions)
#include <windows.h>
These functions are described in the Win32 SDK included with the full version of CVI, but they are also described on the MSDN website. Just google SleepEx and you'll get a link to the Microsoft documentation for these.
Remember that a Sleep() call may not return for a longer period than what you ask for: if a higher priority thread is running or available for scheduling, your thread won't run right away after finishing the Sleep(). But, the NI Delay() function has the same issue - if there's a higher priority thread than the thread Delay() is running on, it will run instead of your thread, potentially making the delay longer than you want.
I guess I'd look at Delay(), Sleep(), and SleepEx() as being functions that guarantee that your thread will sleep at least as long as you ask for. Sleep() and SleepEx() are simpler than Delay() in that they just ask the OS to suspend the calling thread and then wake it up - there's nothing else happening behind the scenes.
NI provides the SyncWait() function to try and overcome this - this function tries to accommodate variable execution times and still yield a consistent delay or more correctly a consistent elapsed time.
08-08-2011 05:17 PM
There is no fp for the Sleep() or the SleepEx() at least when I #include "windows.h" still does not show a function callback on the open/close printhisis... so what's up?
ChipB
08-08-2011 11:53 PM
Function panels are not present for Win API functions: simply copy the definition from the interface to the API shiped with CVI or from MSDN and use it.
|
http://forums.ni.com/t5/LabWindows-CVI/Delay-Timer-and-Sleep-values-are-wildly-off/td-p/1641546
|
CC-MAIN-2016-50
|
refinedweb
| 1,327 | 70.13 |
Debugging Code Efficiently in Visual Studio with the DebuggerDisplay Attribute
It is sometime difficult when you have a bunch of properties exposed from a class and you just need few of them while debugging a code block. Sometimes it becomes even more complex when you have a collection of that class.
Is there any easiest way to improve the code debugging in Visual Studio? Yes, there is. In this post we are going to learn this technique if you have never used it yet.
Code debugging is not a child’s play and it’s becomes difficult when debugging a code written by someone else. In such case, if your boss assigns a bug to you and asks to fix as priority basis, it may come as thunderstorm. While debugging the code, you notice that it’s an issue in a collection where the values are not properly assigned, you have to break your head pinning the items in the Visual Studio debugger and checking individual properties/variables in multiple levels. Just think about a scenario like this:
In the above scenario, you have to go thru individual items to check whether the collection has proper data assigned to it. Isn’t it a difficult job? Yes it is. So, what’s the approach? Can’t we simplify this in Visual Studio? Have you ever think these when you debugged through your code?
Ok, let’s see how we can simplify this. To begin with, we will first go and create a simplest class called “Person” with three properties in it named “Firstname”, “Lastname” and “Age” as mentioned in the following code snippet:
Once your class is ready, create an instance of the class and populate the values in it. Now let’s debug through the code and see how we generally debug the Person object here:
As shown above, we are expanding the object to check the property values. As it’s a simple object, we might find it good but think about a scenario having multiple properties and variables inside it. Debugging that becomes very difficult that you already know.
To solve this problem, there is an attribute named “DebuggerDisplay” present in the “System.Diagnostics” namespace which determines how a class of field displays in the debugger window. You need to add this attribute to the class level with properly formatted with the values that you want to display.
Here is an example of what we want to display for the class:
The value inside the { } defines the property that you want to show in the debugger window. Thus running the code now will display the Firstname, Lastname and Age properties formatted properly in the class level and you don’t have to dig through the object to find out the actual value.
Here is a snapshot of what you will see after running this code with DebuggerDisplay attribute set:
As I mentioned earlier, it is quite helpful when debugging a collection of objects where you want to check few properties without digging each individual objects. Debugging a collection of objects now inside the debugger window will display them well structured in proper format as shown below:
This way, you don’t have to check out each and individual object by expanding it. You will see them all aligned properly. This now made my life easy in the breakpoints. I hope that the post was useful and will help you while debugging your code inside Visual Studio IDE.
|
https://dzone.com/articles/debugging-code-efficiently?mz=110215-high-perf
|
CC-MAIN-2015-35
|
refinedweb
| 580 | 68.5 |
Applies to: RTX51 Real-time Kernel
Information in this article applies to:
I am using the RTX51 Full RTOS and I need to implement a RAM memory check that writes and verifies every memory cell by writing a pattern (for example 0xAA and 0x55) on every RAM cell. The problem is that I have other tasks (fast and standard) and interrupts during this memory verification. Can you suggest a way to implement this memory check?
You may temporarily disable all interrupts even in a RTX51 application. This is allowed unless you disable the interrupt system for more than 10.000 cycles. If the interrupt disable time is longer than this (or if it exceeds the system timer tick value), you will lose interrupts in your system, which may yield to unpredictable behavior.
Therefore, the following function allows you to perform the memory test required in your system. You may call this function from a low priority task.
#include <absacc.h> unsigned char TestLoc (unsigned int adr) { unsigned char XRAMerr = 0; EA = 0; // disable interrupts -> lock task (critical section) SaveVal = XBYTE[adr]; XBYTE[adr] = 0x55; if (XBYTE[adr] != 0x55) XRAMerr = 1; XBYTE[adr] = 0xAA; if (XBYTE[adr] != 0xAA) XRAMerr = 1; EA = 1; // enable interrupts -> unlock task (critical section) return (XRAMerr); }
Article last edited on: 2007-01-18 11:35:09
Did you find this article helpful? Yes No
How can we improve this article?
|
http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka10963.html
|
CC-MAIN-2017-43
|
refinedweb
| 233 | 61.26 |
Intro: HackerBox 0026: BioSense
BioSense - This month, HackerBox Hackers are exploring operational amplifier circuits for measuring physiological signals of the human heart, brain, and skeletal muscles. This Instructable contains information for working with HackerBox #0026, which you can pick up here while supplies last. Also, if you would like to receive a HackerBox like this right in your mailbox each month, please subscribe at HackerBoxes.com and join the revolution!
Topics and Learning Objectives for HackerBox 0026:
- Understand theory and applications of op-amp circuits
- Use instrumentation amplifiers to measure tiny signals
- Assemble the exclusive HackerBoxes BioSense Board
- Instrument a human subject for ECG and EEG
- Record signals associated with human skeletal muscles
- Design electrically safe human interface circuits
- Visualize analog signals over USB or via OLED display
HackerBoxes is the monthly subscription box service for DIY electronics and computer technology. We are hobbyists, makers, and experimenters. We are the dreamers of dreams. HACK THE PLANET!
Step 1: HackerBox 0026: Box Contents
- HackerBoxes #0026 Collectable Reference Card
- Exclusive HackerBoxes BioSense PCB
- OpAmp and Component Kit for BioSense PCB
- Arduino Nano V3: 5V, 16MHz, MicroUSB
- OLED Module 0.96 inch, 128x64, SSD1306
- Pulse Sensor Module
- Snap-Style Leads for Physiological Sensors
- Adhesive Gel, Snap-Style Electrode Pads
- OpenEEG Electrode Strap Kit
- Shrink Tubing - 50 Piece Variety
- MicroUSB Cable
- Exclusive WiredMind Decal
Some other things that will be helpful:
- Soldering iron, solder, and basic soldering tools
- Computer for running software tools
- 9V Battery
- Stranded hook-up wire: Operational Amplifiers
An operational amplifier (or op-amp) is a high-gain voltage amplifier with a differential input. An op-amp produces an output potential that is typically hundreds of thousands of times larger than the potential difference between its two input terminals. Operational amplifiers had their origins in analog computers, where they were used to perform mathematical operations in many linear, non-linear, and frequency-dependent circuits. Op-amps are among the most widely used electronic devices today, being used in a vast array of consumer, industrial, and scientific devices.
An ideal op-amp is usually considered to have the following characteristics:
- Infinite open-loop gain G = vout / vin
- Infinite input impedance Rin (thus, zero input current)
- Zero input offset voltage
- Infinite output voltage range
- Infinite bandwidth with zero phase shift and infinite slew rate
- Zero output impedance Rout
- Zero noise
- Infinite common-mode rejection ratio (CMRR)
- Infinite power supply rejection ratio.
These ideals can be summarized by the two "golden rules":
- In a closed loop the output attempts to do whatever is necessary to make the voltage difference between the inputs zero.
- The inputs draw no current.
Additional Op-Amp Resources:
Detailed Video Tutorial from EEVblog
Step 3: Instrumentation Amplifiers
An instrumentation amplifier is a type of differential amplifier combined with input buffer amplifiers. This configuration eliminates the need for input impedance matching and thus makes the amplifier particularly suitable for use in measurement and test equipment. Instrumentation amplifiers are used where great accuracy and stability of the circuit are required. Instrumentation amplifiers have very high common-mode rejection ratios making them suitable for measuring small signals in the presence of noise.
Although the instrumentation amplifier is usually shown schematically as being identical to a standard op-amp, the electronic instrumentation amp is almost always internally composed of THREE op-amps. These are arranged so that there is one op-amp to buffer each input (+,−), and one to produce the desired output with adequate impedance matching.
PDF Book: Designer's Guide to Instrumentation Amplifiers
Step 4: HackerBoxes BioSense Board
The HackerBoxes BioSense Board features a collection of operational and instrumentation amplifiers to detect and measure the four physiological signals described below. The tiny electrical signals are processed, amplified and fed to a microcontroller where they can be relayed to a computer via USB, processed, and displayed. For microcontroller operations, the HackerBoxes BioSense Board employs an Arduino Nano module. Note that the next couple of steps focus on readying the Arduino Nano module for use with the BioSense Board.
Pulse Sensor modules feature a light source and a light sensor. When the module is in contact with body tissue, for example a fingertip or earlobe, changes in the reflected light are measured as blood pumps through the tissue.
ECG (Electrocardiography), also called EKG, records. ECG is a very commonly performed cardiology test. [Wikipedia]
EEG (Electroencephalography) is an electrophysiological monitoring method to record electrical activity of the brain. Electrodes are placed along the scalp while EEG measures voltage fluctuations resulting from ionic current within the neurons of the brain. [Wikipedia]
EMG (Electromyography) measures electrical activity associated with skeletal muscles. An electromyograph detects the electric potential generated by muscle cells when they are electrically or neurologically activated. [Wikipedia]
Step 5: Arduino Nano Microcontroller Platform
The included Arduino Nano module comes with header pins, but they are not soldered to the module. Leave the pins off for now. Perform these initial tests of the Arduino Nano module separately from the BioSense Board and 7: Arduino Nano Header Pins
Now that your development computer has been configured to load code to the Arduino Nano and the Nano has been tested, disconnect the USB cable from the Nano and get ready to solder.
If..
Step 8: Components for BioSense PCB Kit
With the microcontroller module ready to go, it is time to assemble the BioSense Board.
Component List:
- U1:: 7805 Regulator 5V 0.5A TO-252 (datasheet)
- U2:: MAX1044 Voltage Converter DIP8 (datasheet)
- U3:: AD623N Instrumentation Amplifier DIP8 (datasheet)
- U4:: TLC2272344P OpAmp DIP8 DIP8 (datasheet)
- U5:: INA106 Differential Amplifier DIP8 (datasheet)
- U6,U7,U8:: TL072 OpAmp DIP8 (datasheet)
- D1,D2:: 1N4148 Switching Diode Axial Lead
- S1,S2:: SPDT Slide Switch 2.54mm Pitch
- S3,S4,S5,S6:: Tactile Momentary Button 6mm X 6mm X 5mm
- BZ1:: Passive Piezo Buzzer 6.5mm Pitch
- R1,R2,R6,R12,R16,R17,R18,R19,R20:: 10KOhm Resistor [BRN BLK ORG]
- R3,R4:: 47KOhm Resistor [YEL VIO ORG]
- R5:: 33KOhm Resistor [ORG ORG ORG]
- R7:: 2.2MOhm Resistor [RED RED GRN]
- R8,R23:: 1KOhm Resistor [BRN BLK RED]
- R10,R11:: 1MOhm Resistor [BRN BLK GRN]
- R13,R14,R15:: 150KOhm Resistor [BRN GRN YEL]
- R21,R22:: 82KOhm Resistor [GRY RED ORG]
- R9:: 10KOhm Trimmer Potentiometer “103”
- R24:: 100KOhm Trimmer Potentiometer “104”
- C1,C6,C11:: 1uF 50V Monolithic Cap 5mm Pitch “105”
- C2,C3,C4,C5,C7,C8:: 10uF 50V Monolithic Cap 5mm Pitch “106”
- C9:: 560pF 50V Monolithic Cap 5mm Pitch “561”
- C10:: 0.01uF 50V Monolithic Cap 5mm Pitch “103”
- 9V Battery Clips with Wire Leads
- 1x40pin FEMALE BREAK-AWAY HEADER 2.54mm Pitch
- Seven DIP8 Sockets
- Two 3.5mm Audio-Style, PCB-Mount Sockets
Step 9: Assemble the BioSense PCB
RESISTORS: There are eight different values of resistors. They are not interchangeable and must be carefully placed exactly where they belong. Start by identifying the values of each type of resistor using the color codes shown in the component list (and/or an ohmeter). Write the value on the paper tape attached the the resistors. This makes it a lot harder to end up with resistors in the wrong place. Resistors are not polarized and can be inserted in either direction. Once soldered into place, closely trim the leads form the rear of the board.
CAPACITORS: There are four different values of capacitors. They are not interchangeable and must be carefully placed exactly where they belong. Start by identifying the values of each type of capacitor using the number markings shown in the component list. Ceramic capacitors are not polarized and can be inserted in either direction. Once soldered into place, closely trim the leads form the rear of the board.
POWER SUPPLY: The two semiconductor components that make up the power supply are U1 and U2. Solder these next. When soldering U1, note that the flat flange is the device ground pin and heat sink. It must be soldered completely to the PCB. The kit includes DIP8 sockets. However, for the voltage converter U2, we strongly recommend carefully soldering the IC directly to the board without a socket.
Solder on the two slide switches and the 9V battery clip leads. Note that if your battery clip came with a connector plug on the leads, you can just snip the connector off.
At this time, you can plug on a 9V battery, flip the power switch on and use a volt meter to verify that your power supply is creating a -9V rail and a +5V rail from the supplied +9V. We now have three voltage supplies and a ground all from one 9V battery. REMOVE THE BATTERY TO CONTINUE ASSEMBLY.
DIODES: The two diodes D1 and D2 are small, axial-leaded, glassy-orange components. They are polarized and should be oriented so that the black line on the diode package lines up with the thick line on the PCB silkscreen.
HEADER SOCKETS: Separate the 40 pin header into three sections of 3, 15, and 15 positions each. To cut the headers to length, use small wire cutters to snip through the position ONE PAST where you want the socket strip to end. The pin/hole that you cut through is sacrificed. The three pin header is for the pulse sensor at the top of the board with pins labeled "GND 5V SIG". The two fifteen pin headers are for the Arduino Nano. Remember that the six pin ICSP (in-circuit serial programming) connector of the Nano is not used here and does not need a header. We also do not suggest connectorizing the OLED display with a header. Solder the headers into place and leave them empty for now.
DIP SOCKETS: The six amplifier chips U3-U8 are all in DIP8 packages. Solder a DIP8 chip socket into each of those six positions being sure to orient the notch in the socket to align with the notch on the PCB silkscreen. Solder the sockets without the chip inserted into them. Leave them empty for now.
REMAINING COMPONENTS: Finally solder the four push buttons, the two trimpots (note that they are two different values), the buzzer (note that it is polarized), the two 3.5mm audio-style jacks, and lastly the OLED display.
SOCKETED COMPONENTS: Once all of the soldering is complete, the six amplifier chips may be inserted (minding the orientation of the notch). Also, the Arduino Nano may be inserted with the USB connector at the edge of the BioSense Board.
Step 10: Electrical Safety and Power Supply Switches
In the schematic diagram for the HackerBoxes BioSense Board, note that there is a HUMAN INTERFACE (or ANALOG) section and also a DIGITAL section. The only trances that cross between these two sections are the three analog input lines to the Arduino Nano and the +9V battery supply which can be opened up using the USB/BAT switch S2.
Out of an abundance of caution, it is common practice to avoid having any circuit connected to a human body powered by wall power (line power, mains power, depending upon where you live). Accordingly, the HUMAN INTERFACE portion of the board is only powered by a 9V battery. However unlikely it may be that the computer suddenly puts 120V onto the connected USB cord, this is a little extra insurance policy. An added benefit to this design is that we can power the entire board from the 9V battery if we do not need a computer connected.
ON/OFF SWITCH (S1) serves to disconnect the 9V battery from the circuit entirely. Use S1 to turn the analog portion of the board completely off when not in use.
USB/BAT SWITCH (S2) serves to connect the 9V battery to the digital supply of the Nano and OLED. Leave S2 in the USB position when the board is connected to a computer via the USB cable and the digital supply will be provided by the computer. When the Nano and OLED are to be powered by the 9V battery, just switch S2 to the BAT position.
NOTE ON SUPPLY SWITCHES: If S1 is ON, S2 is in USB, and there is no USB power provided, the Nano will try to power itself through the analog input pins. While not a human safety issue, this is an undesirable condition for the delicate semiconductors and it should not be prolonged.
Step 11: OLED Display Library
Step 12: BioSense Demo Firmware
Shall we play a game, Professor Falken?
There is also a cool Arkanoid game in the SSD1306 examples. For it to work with the BioSense board however, the code that initializes and reads the buttons must be modified. We have taken the liberty to make those changes in the "biosense.ino" file attached here.
Duplicate the arkanoid folder from the SSD1306 examples to a new folder that you have named biosense. Delete the arkanoid.ino file from that folder and drop in the "biosense.ino" file. Now compile and upload biosense to the nano. Hitting the rightmost button (button 4) will launch the game. The paddle is controlled by button 1 to the left and button 4 to the right. Nice shot there, BrickOut.
Hit the reset button on the Arduino Nano to go back to the main menu.
Step 13: Pulse Sensor Module
A Pulse Sensor Module may interface to the BioSense Board using the three pin header at the top of the Board.
The Pulse Sensor Module uses an LED light source and an APDS-9008 ambient light photo sensor (datasheet) to detect LED light reflected through a fingertip or earlobe. A signal from the ambient light sensor is amplified and filtered using an MCP6001 op-amp. The signal may then be read by the microcontroller.
Pressing Button 3 from the main menu of the biosense.ino sketch will relay samples of the pulse sensor output signal over the USB interface. Under the TOOLS menu of the Arduino IDE, select the "Serial Plotter" and make sure that the baud rate is set to 115200. Gently place your fingertip over the light on the pulse sensor.
Additional details and projects associated with the Pulse Sensor Module may be found here.
Step 14: Electromyograph (EMG)
Plug the electrode cable into the lower 3.5mm jack labeled EMG and position the electrodes as shown in the diagram.
Pressing Button 1 from the main menu of the biosense.ino sketch will relay samples of the EMG output signal over the USB interface. Under the TOOLS menu of the Arduino IDE, select the "Serial Plotter" and make sure that the baud rate is set to 115200.
You can test out the EMG on any other muscle groups - even the eyebrow muscles in your forehead.
The EMG circuit of the BioSense Board was inspired by this Instructable from Advancer Technologies, which you should definitely check out for some additional projects, ideas, and videos.
Step 15: Electrocardiograph (ECG)
Plug the electrode cable into the upper 3.5mm jack labeled ECG/EEG and position the electrodes as shown in the diagram. There are two basic options for ECG electrode placement. The first is on the inside of the wrists with the reference (red lead) on the back of one hand. This first option is easier and more convenience but is often a little noisier. The second option is across the chest with the reference on the right abdomen or upper leg.
Pressing Button 2 from the main menu of the biosense.ino sketch will relay samples of the ECG output signal over the USB interface. Under the TOOLS menu of the Arduino IDE, select the "Serial Plotter" and make sure that the baud rate is set to 115200.
The ECG/EEG circuit of the BioSense Board was inspired by the Heart and Brain SpikerShield from Backyard Brains. Check out their site for some additional projects, ideas, and this cool ECG video.
Step 16: Electroencephalograph (EEG)
Plug the electrode cable into the upper 3.5mm jack labeled ECG/EEG and position the electrodes as shown in the diagram. There are many options for EEG electrode placement with two basic options shown here.
The first is on the forehead with the reference (red lead) on the earlobe or mastoid process. This first option can simply use the same snap-style leads and gel electrodes used for ECG.
The second option at the back of the head. If you happen to be bald, the gel electrodes will also work here. Otherwise, forming electrodes that can "poke through" hair is a good idea. A lock-washer style solder lug is a good option. Use needlenose pliers on the small tabs (six in this case) inside the washer to bend then all to protrude in the same direction. Placement under an elastic headband will gently force these protrusions through hair and into contact with the scalp below. As necessary, conductive gel can be used to improve the connection. Simply mix table salt with a thick liquid such as petroleum jelly or a slurry of water and starch or flour. Salty water alone will also work but will need to be contained within a small sponge or cotton ball.
Pressing Button 2 from the main menu of the biosense.ino sketch will relay samples of the EEG output signal over the USB interface. Under the TOOLS menu of the Arduino IDE, select the "Serial Plotter" and make sure that the baud rate is set to 115200.
Additional EEG projects and resources:
This Instructable uses a similar design as the BioSense EEG and also demonstrates some additional processing and even how to play EEG Pong!
Backyard Brains also has a nice video for EEG measurements.
EEG signals can measure stroboscopic brainwave effects (e.g. using Mindroid).
Step 17: Challenge Zone
Can you display the analog signal traces on the OLED in addition to the Serial Plotter?
As a starting point, check out this project from XTronical.
It may also be useful to have a look at the Tiny Scope project.
How about adding text indicators for signal rates or other interesting parameters?
Step 18: BioBox Monthly Subscription Box
Applied Science Ventures, the parent company of HackerBoxes, is involved in an exciting new subscription box concept. BioBox will inspire and educate with projects in the life sciences, bio hacking, health, and human performance. Keep an optical sensor out for news and charter member discounts by following the BioBox Facebook Page.
Step 19:!
gregtich made it!
PaulT253 made it!
bitanalyst made it!
TimGTech made it!
MichaelH887 made it!
See 1 More
51 Discussions
Question 8 weeks ago
Arduino: 1.8.5 (Mac OS X), Board: "Arduino Nano, ATmega328P"
/Users/Strex/Documents/Programming/Arduino/HackerBoxes26/arkanoid/arkanoid.ino:37:39: fatal error: intf/i2c/ssd1306_i2c_wire.h: No such file or directory
#include "intf/i2c/ssd1306_i2c_wire.h"
^
compilation terminated.
exit status 1
Error compiling for board Arduino Nano.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
ssd1306_i2c_wire.h does not exist in:
Answer 5 weeks ago
Try using this verssion of the github release:
Question 8 weeks ago
2 months ago
I made a 3D printable case for the Biosense board. You can find it here:
10 months ago
I was wondering where is the link for the arduino code that we will need for the complete assembly. To Upload
Reply 10 months ago
If you look at the example code, it is just reading from one of the ADC pins and sending it right back out the Serial. This is a great project to get going on the analog data handling, graphing, data scaling, peak detection... lots of good things.
Here is my take on it:
I used some of the examples provided by article. I don't have proper attribution, sorry to original authors, and some of the comments are invisible. I was coding for me, late at night.
Reply 10 months ago
I can't seem to get your code to compile. There are errors that reference the FIR library. I'm not so sure that I have the right library installed. I downloaded one for Arduino which I located on a google search but it doesn't seem to pan out. I'm guessing that you are using the FIR library to smooth out the very noisy signal that this circuit is producing. Maybe you could provide a link to the library that you used? I'd love to try it out!
Reply 4 months ago
In the Arduino IDE, go to Sketch, Include Library, Manage Libraries. Then install the FIR Filter library, Adafruit ssd1306 Library, and the Adafruit GFX Library, I used all the newest versions and the program compiles and runs.
Reply 4 months ago
I just now tried it again. Thanks for the advice! That took care of the problem. It overwrote whatever effed up library I had installed and replaced it with the correct version. Now it compiles juuuuust fine. Now I'll go see if I can find the hackebox from 5 months ago and try it out.
Reply 10 months ago
There isn't one, really. Although it's strait forward putting the codebase together. You just have to take your time and really follow the instructions.
First you have to download the display driver library, and install that. Once you've done that, pop into the examples folder that you just installed and copy out all the files in the arknoid example.
Then make your own folder called "biosense" and paste the arknoid files into that. Once done, delete the arknoid.ino file, download the biosense.ino file from above and put it into that folder.
If you've done everything right, you should now be able to build and upload.
Question 5 months ago
This is my first hackerbox and the first involved soldering project. I had trouble inserting the AD623N DIP8 chip into the DIP socket and broke off one of the pins. On this instructable it says AD623N, on the top of the chip it says "AD623AN #1641 2943908". If I order a replacement chip, what exactly do I need to order? I found several similarly named chips but not the exact one?
Answer 5 months ago
Any AD623AN in an 8pin DIP package should work fine. Before you spend the $10-15 buying one, shoot an email to [email protected] and see if they can find one to send to you.
7 months ago
finally getting around to this project, and the tinyscope link now has me thinking... I wonder what hardware changes to the board would be necessary to turn the Biosense PCB into a pocket oscilloscope. Since both are designed to measure and record voltage changes over time, it should be possible. Would probably be handy for reading digital signals on arduinos and such.
Question 7 months ago
This is my first Hackerbox and I'm having a great time. It is assembled and working so now I'm starting to explore how to clean up the 60 hz interference, make better use of the OLED, etc.
Question: There are a few parts in the kit that seem unrelated such as the heat shrink tubing and the TRRS breakout. What are those for?
Answer 7 months ago
I see! Gives me an idea for converting the ECG leads to alligator clips for different electrode pads I have access to. I'm now in the process of getting the wave form to the OLED and having some success. Now just need to figure out how to filter out the 60 Hz noise. What a great box!
Answer 7 months ago
Hey Greg. We are glad that you are enjoying HackerBox #0026. Use of the TRRS breakout is shown in Step 16 for the EEG interface. The tubing is for your supply bin and is useful for many projects. Your use of the phrase "a few parts in the kit" points to the confusion here. HackerBoxes are not kits. A particular HackerBox may include one or more kits, or even no kits. In this case, most of the box is related to one project so it may feel like a kit. That is usually not the case. A HackerBox is a bunch of stuff each month for electronics hobbyists and there is a general educational/entertaining theme for each box, however the entire box is not intended to be singular in purpose.
7 months ago
There have been recent changes to the ssd1036 library that lead to biosense.ino compile errors like: "biosense:279: error: 'ssd1306_setRamBlock' was not declared in this scope"
To resolve, either roll back to version 1.4.12 of the ssd1306 library, or add
#include "lcd/lcd_common.h"
and replace all instances of
ssd1306_sendData
with
ssd1306_sendPixels
8 months ago
Having issues finding "ssd1306.h" in the github folder. Downloaded the whole folder and installed as directed, but not sure where to point to for the library install. Help please?
Reply 8 months ago
Disregard, managed to get the library installed and Arkanoid to run. However, the touch buttons aren't working for some reason. I'll have to take a look at that. Solder contacts look good though.
Question 9 months ago on Step 11
added linked driver from get hub to library manager which allows me to bring up snowflake example but the oled never comes on. Is the driver installed by simple adding library or is there a run command somewhere in the 1306 master file to allow me to install driver???
|
https://www.instructables.com/id/HackerBox-0026-BioSense/
|
CC-MAIN-2018-47
|
refinedweb
| 4,239 | 63.59 |
. Today, however, we are doing something practical - we are making a progressively enhanced slideshow with a fancy transitioning effect, which is perfectly functional in older browsers as well.
Update: Per popular demand, you can now download an auto-advancing version of this slideshow. Read more in this short tutorial.
The Idea
With JavaScript, we are going to apply a special filter to every image in the slideshow. We will create a new version of the images, with higher contrast and more vivid colors, and store it in a canvas elements.
When the user chooses to proceed to another slide, the canvas is shown with a fadeIn animation, creating a smooth lighting effect.
The HTML
The first step in creating the slideshow, is laying down the HTML markup of the page.
html5-slideshow.html
<!DOCTYPE html> <html> <head> <meta http- <title>An HTML5 Slideshow w/ Canvas & jQuery | Tutorialzine Demo</title> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <div id="slideshow"> <ul class="slides"> <li><img src="img/photos/1.jpg" width="620" height="320" alt="Marsa Alam" /></li> <li><img src="img/photos/2.jpg" width="620" height="320" alt="Turrimetta Beach" /></li> <li><img src="img/photos/3.jpg" width="620" height="320" alt="Power Station" /></li> <li><img src="img/photos/4.jpg" width="620" height="320" alt="Colors of Nature" /></li> </ul> <span class="arrow previous"></span> <span class="arrow next"></span> </div> <script src=""></script> <script src="script.js"></script> </body> </html>
First we have the HTML5 doctype, followed by the head section of the document. After the title tag and the stylesheet we move on with the body.
You can see that the markup for the slideshow is really simple. The main containing div, #slideshow, holds an unordered list and the previous and next arrows. The unordered list holds the slides, with each defined as a
LI element. As shown in the illustration above, this is where the canvas elements with the modified versions of the images are inserted.
Lastly we include jQuery and our script.js, to which we are going to get back to in the last step of this tutorial.
The CSS
All the styles for the slideshow reside in styles.css. I've used the #slideshow id of the main containment element as a namespace, so you can easily append these styles to your stylesheet without worrying about conflicts.
styles.css
#slideshow{ background-color:#F5F5F5; border:1px solid #FFFFFF; height:340px; margin:150px auto 0; position:relative; width:640px; -moz-box-shadow:0 0 22px #111; -webkit-box-shadow:0 0 22px #111; box-shadow:0 0 22px #111; } #slideshow ul{ height:320px; left:10px; list-style:none outside none; overflow:hidden; position:absolute; top:10px; width:620px; } #slideshow li{ position:absolute; display:none; z-index:10; } #slideshow li:first-child{ display:block; z-index:1000; } #slideshow .slideActive{ z-index:1000; } #slideshow canvas{ display:none; position:absolute; z-index:100; } #slideshow .arrow{ height:86px; width:60px; position:absolute; background:url('img/arrows.png') no-repeat; top:50%; margin-top:-43px; cursor:pointer; z-index:5000; } #slideshow .previous{ background-position:left top;left:0;} #slideshow .previous:hover{ background-position:left bottom;} #slideshow .next{ background-position:right top;right:0;} #slideshow .next:hover{ background-position:right bottom;}
We can split our visitors, which will interact with the slideshow, in three main groups:
- People with JavaScript switched off. These users will only see the first slide, and will be unable to switch to a different one;
- People with JavaScript switched on, but with no support for canvas. For visitors from this group, the slides will change instantaneously, without transitioning effects;
- People with JavaScript enabled and canvas support. These are people who use the latest versions of Firefox, Safari, Chrome, Opera and the soon to be released IE9. They will enjoy the slideshow in its full glory;
To account for the first two groups, a number of rules are applied to the stylesheet. With the help of the first-child selector, only the first slide is shown by default. Also a number of overflow:hidden rules are applied in a number of places just in case.
The JavaScript
Moving on to the last part of the tutorial - the JavaScript and jQuery code. As we already explained the basic principles behind the effect, lets move straight to the execution.
script.js - Part 1
$(window).load(function(){ // We are listening to the window.load event, so we can be sure // that the images in the slideshow are loaded properly. // Testing wether the current browser supports the canvas element: var supportCanvas = 'getContext' in document.createElement('canvas'); // The canvas manipulations of the images are CPU intensive, // this is why we are using setTimeout to make them asynchronous // and improve the responsiveness of the page. var slides = $('#slideshow li'), current = 0, slideshow = {width:0,height:0}; setTimeout(function(){ if(supportCanvas){ $('#slideshow img').each(function(){ if(!slideshow.width){ // Saving the dimensions of the first image: slideshow.width = this.width; slideshow.height = this.height; } // Rendering the modified versions of the images: createCanvasOverlay(this); }); } $('#slideshow .arrow').click(function(){ var li = slides.eq(current), canvas = li.find('canvas'), nextIndex = 0; // Depending on whether this is the next or previous // arrow, calculate the index of the next slide accordingly. if($(this).hasClass('next')){ nextIndex = current >= slides.length-1 ? 0 : current+1; } else { nextIndex = current <= 0 ? slides.length-1 : current-1; } var next = slides.eq(nextIndex); if(supportCanvas){ // This browser supports canvas, fade it into view: canvas.fadeIn(function(){ // Show the next slide below the current one: next.show(); current = nextIndex; // Fade the current slide out of view: li.fadeOut(function(){ li.removeClass('slideActive'); canvas.hide(); next.addClass('slideActive'); }); }); } else { // This browser does not support canvas. // Use the plain version of the slideshow. current=nextIndex; next.addClass('slideActive').show(); li.removeClass('slideActive').hide(); } }); },100);
With
document.createElement(), you can create any DOM element that you like. So to test whether the browser really supports canvas (and doesn't just create a generic element), we use the
in operator to check for the
getContext() method, which is an integral part of the standard. The result of this check is used throughout the code to account for users with browsers that do not yet support canvas.
Notice that the calls to the createCanvasOverlay function (which we will discuss in the second part of the code) are enclosed in a setTimeout statement. This is done because the function is processor intensive and might cause the browser window to stall. setTimeout breaks out of the main execution path and runs the code asynchronously, maximizing the responsiveness of the page.
script.js - Part 2
// This function takes an image and renders // a version of it similar to the Overlay blending // mode in Photoshop. function createCanvasOverlay(image){ var canvas = document.createElement('canvas'), canvasContext = canvas.getContext("2d"); // Make it the same size as the image canvas.width = slideshow.width; canvas.height = slideshow.height; // Drawing the default version of the image on the canvas: canvasContext.drawImage(image,0,0); // Taking the image data and storing it in the imageData array: var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height), data = imageData.data; // Loop through all the pixels in the imageData array, and modify // the red, green, and blue color values. for(var i = 0,z=data.length;i<z;i++){ // The values for red, green and blue are consecutive elements // in the imageData array. We modify the three of them at once: data[i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) : (255 - 2 * (255 - data[i]) * (255 - data[i]) / 255)); data[++i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) : (255 - 2 * (255 - data[i]) * (255 - data[i]) / 255)); data[++i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) : (255 - 2 * (255 - data[i]) * (255 - data[i]) / 255)); // After the RGB channels comes the alpha value, which we leave the same. ++i; } // Putting the modified imageData back on the canvas. canvasContext.putImageData(imageData,0,0,0,0,imageData.width,imageData.height); // Inserting the canvas in the DOM, before the image: image.parentNode.insertBefore(canvas,image); } });
This is where the magic happens. The canvas element is basically one big piece of paper on which you can draw with JavaScript. The code above creates a blank canvas element and imports the image, which was passed as a parameter, with the
drawImage() method. After this, we use the
getImageData() method to export the contents of all the pixels of the canvas into the imageData array.
What is more, for each pixel of the image we have four entries in the array - one for the red, green and blue colors, and the alpha channel (the transparency). These are all numbers from 0 to 255. The main for loop has to go through all the pixels and apply a special filter equation that lightens the lighter colors and darkens the dark ones. It is the same effect that you get by using the overlay blending mode in photoshop.
The main for loop has to do an incredible amount of work - for a 600x400 pixel image it does 240 000 iterations! This means that your code must be as optimal as possible. This is why, in the loop, I copied the formula three times instead of calling a function. By removing the function calls the loop became nearly three times faster.
Be aware that the rendering time will grow proportionally, if you decide to include more slides, or use larger images.
With this our HTML5 Canvas Slideshow is complete!
Final words
The canvas element opens a whole new way of building rich internet applications. For those of you who are curious, on a relatively new PC, it takes Firefox 1.2 seconds to generate all four canvas images, while Chrome is faster at 0.67s. Considering the amount of work that is done, this is a really impressive achievement.
Presenting Bootstrap Studio
a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.
Thank you for this extraordinary tutorial!!!
An excellent tutorial, well done and thanks
Awesome sauce! I was literally thinking how to make a simple slideshow/gallery with HTML5 and CSS3, and this is great! Thanks for being on the ball, Martin!
O.o! cool! ^^
Thanks for the tutorial. I just tried this myself but I couldn't get it to run on IE9 beta. I also tried downloading your files and running in the extracted folder. Still no luck. Any known issues with IE9 beta?
I fixed the bug with IE9 beta and implemented one more optimization in the main loop. The demo zip is updated with the new code.
Hi Martin, thanks for this!
I made some changes for a friend (f.ex. dynamically sizing the images) and added basic PHP code to read out a directory.
Demo:
Source:
Cheers!
wow! html5~ nice ~~Share it~
Thanks~
Looks nice. Thanks for sharing it :)
Is any of the content in the slider list indexable? I like the concept, but canvas might not be the best option.
The canvas elements are created on top of the regular slideshow content, so it is visible to search engines.
great tutorial once again. nice work!
I'm using firefox 3.6.10. The online demo run fine but the source code gives me a security error: Security error" code: "1000 var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
When I typed everything and saved in localhost, I get this:
uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: :: createCanvasOverlay :: line 100" data: no]
There are some security limitations when using canvas on localhost. You will have to upload it somewhere to test it.
@Ibrahim
Replace (line100):
canvasContext.drawImage(image,0,0);
With:
try {
try {
canvasContext.drawImage(image,0,0);
}
catch (e) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
canvasContext.drawImage(image,0,0);
}
}
catch (e) {
throw new Error("unable to access image data: " + e)
}
Replace (line 117):
var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
data = imageData.data;
With:
try {
try {
var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
data = imageData.data;
}
catch (e) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
data = imageData.data;
}
}
catch (e) {
throw new Error("unable to access image data: " + e)
}
This is only a localhost issue though :)
Hi, This is a fantastic slider and tutorial. I have a bit of an issue though.. the slider seems to be working fine in Firefox but not in Chrome or IE8.
Any ideas on how to fix that? :)
Very Good, :)
Thanks!!!
That´s really great tip!
Wow, yet another great article. I'm not sure wherer you guys find the time to create all these brilliant scripts. Keep up the good work Tutorialzine!
Thank you for the awesome comments guys! Glad you find it useful.
Hi, love the tutorial. Great work, One question i have, is there aline of code that i can add so that the slides go automatically rather than having to click on the arrows? and the images loop? this would be great if it can be done.
Keep up the great articles.
Yes, you can try this short tutorial.
From there you can download an auto-advancing version of this slideshow.
A fantastic tutorial/script. I think this will come handy.
aw aw aw...this is real know...
xoxoxoxo ^_^'
thank you for tutor :)
Great Work! Very useful. I like HTML5 Tutorials :)
Awesome, keep up the good work.
Very cool! I'll have to make use of this in an upcoming projects. Thanks!
An old flash trick to speed up the loop even more, is replacing data.length by a variable you've filled with the length before the loop (checking how long an array is 240.000 times seems like a waste ;))
Thumbs up for the great post!
I agree, Eric. It does make a difference in such an intensive loop.
The length is, however, cached in the z variable, so the data.length is not looked up on every iteration.
Great script! I will read the tut and want to use the gallery.
wanting to implement on my site
but getting a java script error in FF 3.6.10 as Security error" code: "1000 var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
but don't know how to remove this
any suggestion
You are probably trying to run it on your local PC. There are some security restrictions imposed from the browsers in this situation.
You'd have to upload it to your host to make it work.
This looks like an excellent HTML5/jQuery slideshow! I have run into a problem, however. I cannot get the images to actually change when clicking on the next/prev buttons. I downloaded the zipped files and uploaded them to my server, but even without modifications, it does not function. I'm using the latest version of Chrome. Same problem w/ FF.
Any Ideas?
Thanks!
It sounds to me that the jQuery library was not being loaded. You could have been temporarily unable to connect to Google's CDN (where jQuery is hosted).
If the problem persists, try downloading the library directly from jquery.com and uploading it along with the rest of the scripts (remember to change the include address in html5-slideshow.html).
Martin,
Thanks for your response. There were two issues. The first being exactly like you said -- a problem with connecting to the Google CDN.
A second problem I found was that using the script as-is, you cannot place any ul elements above the slideshow . (I am already using a ul in my nav section in the page header.
Is there a way to modify the JS so that it targets the slideshow ul and ignores all others?
Thanks again for your great help and tutorial!
Nevermind, here is the modification (if anyone else needs it):
var slides = $(‘#slideshow ul li’),
Thanks again for this great slideshow!
Thank you for the fix, Eric, I ported it to the tutorial & demo. Hopefully nobody would run into this problem again.
Excellent tutorial and file .. one quick question .. is there any way this should change images automatically and with arrows as well? anyone please advice.
This is great!! Exactly what I've been looking for for a while now! I'm still pretty new at all of this and I'm also interested in making the slide show auto advance. Any advice on how to do this or at least somebody who can point me in the right direction where I could find this info? Thanks.
I'm totally in for that as well. I really like the to have a slideshow like this but which advances to the next slide automatically..
So without the arrows and just an automatic slideshow looping through the pictures.
Is there a line of code which I can add so that this happens?
Cheers for any comments..
Yes, you can try this short tutorial.
From there you can download an auto-advancing version of this slideshow.
Great tutorial and good to see the possibilities HTML5 will bring once it has been adopted by all major browsers. Thanks for the share!
great it's quite usefull!
Hi guys, awesome job. I've downloaded the zip but don't work @all. I've tested on Firefox 4 and Chrome 10 on Ubuntu and Windows 7 and the HTML example looks good but simply doesn't slide the images. Any ideas? Thx in advance!
There are security restrictions in place that prevent it from working directly with the file system. You will need to upload it to a external web host, or run it through xampp.
Hey Great work, I love it. But i need a script which can fade automatically ? Can anyone help ?
very nice tutorial, i used it in my site and i wanted the changes over 7 sec , the problem now is in IE that i do not see the first image now for 7 sec. Help please (ellen from holland)so now i have it now on 3sec, but it is not what i want
Hey, nice work with the tutorial.
I created a small banner for a website. The problem is that I can't find a way to make it work in two different slideshows in the same page at the same time.
Any suggestions?
I guess I should modify the JavaScript, but I don't know what exactly.
Did you have any luck with this? Im trying to do a similar function...?
Thanks for sharing. Easy to follow and very useful.
This is a GREAT option for my flash slide shows.... since they can't be viewed on smart phones.. I ran into one problem though. It works great on a regular computer no matter how many slides... but on smart phone if I have more than 14 slides it will not work... any ideas????
Hi Martin,
I have implemented this on a site I am building which is not live atm. I have an overlay using a negative margin over the images... which is fine, but when switching between pics the next pic will stay on top for just a sec until in place and then fall in place. I would like to show you what it is doing to see if you can help, but I can not post the link publicly. Would you mind helping? Thank you!
Hello,
I was wondering if there was a way to have more than 1 slider on the page and not have it slide through both sliders at once when the arrow is clicked? It would be an amazing addition to my site if there was a way to implement this.
Great Slideshow but i have one problem.
I'd like to use a different size of images. But when i change it, the Canvas image still has your original size. You wrote, that it will all be done in the css. And it looks like the script.js is getting the right size. The canvas is size is like mine, but the image not. What am I doing wront. Thx for help.
Thanks.. I've given it a shot but ran into the security error in createCanvasOverlay which I am pretty sure I can work around.
Thanks!
I am trying to use this with JqueryMobile using content-primary and content-secondary classes to automatically change from single column on handheld device to 2 column on tablets and desktops, and I cannot get the icon arrows to appear. The link area where the arrows should be is there and works, as does the slideshow (sweet), but no arrows. Any ideas
Ran across this tutorial when I was checking out the auto advancing tutorial. (Really glad I found that, thank you!)
I implemented this tutorial on a site, but now I want to remove the canvas manipulation, but keep the fade transition. I've tried a few combinations of code, but end up breaking the code. Any guidance on what to remove to stop the canvas, but keep the fade?
Thanks!
@Yazmin,
I had the same problem, and I found out that by taking out the three color calculation (the data[i]) will remove the canvas function but still have the fade in/out function. Hope this helps.
I try this demo on my host but I'm getting security error on this line -> var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height);
How can I fix this?
Great work Martin...
Hi!
Thank you for a nice slideshow that I can use in my website!
One question though; I have two slideshows in the same page, as the images are grouped under different headlines. It seems that the slideshow gets confused if you have two instances of the slideshow in the same screen and starts to occasionally show only white images.
Any idea how to fix that? Should I use class attribute for the slideshow instead of id, as there are two instances...?
Ok, I solved the issue by making two instances of slideshow; with their own style and javascripts files. Maybe not the most elegant way but it works :-).
(Actually I guess the two instances could work well with same id, if the amount of slides is same in both).
But thanks again of a nice slideshow code!
Great slider, very useful and easy to follow along. Is there anyway to incorporate any captions in the slideshow? That would really be a useful feature.
Thanks again, great work and thanks very much for sharing.
Awesome tutorial.
Can it be used to slide texts too without converting the text into image format?
If it can then it will solve my problem :)
Great slider, really like it. Is anyone else having an issue with the size of the new image? I have resized the slider but when it generate the new image with the colour change it seems to make it smaller in width than the original?
What am I doing wrong?
Thanks in advance!!!
Very nice work Martin. But i'm getting a wired bug/issue with your material. I'm trying to create a slide slow using your code and every thing is working fine except this one. whenever i try to move to next slide then code tries to zoom at that top left part of image and then moves to next slide and same happens with every click either on next or previous. How to get rid of this bug? Imp: original pic dims are: 708x1005 and in html code i have set them to width="450" height="480".
Make sure your pictures are set to 72 dpi.
great.thanks for sharing
How I solve this, that do not have to click on the arrows, but when I moved over the mouse detect and move in that direction?
First Thank you for such a great tutorial... Second I could make the slideshow works on all the browsers except Firefox 10.0.2, it does not give me any error, but I am not sure why it is not working..
Hi guys. Does anyone know why my arrows don't appear on the slideshow? the slideshow actually works when I click on it but the arrows arn't showing. Any ideas?
I'm having the same problem as Paul. Not sure why they won't appear.
Phil,
Same thing with me - no arrows :( I would very much like to know why..
Wow, such an indepth tutorial. I am going to try it out myself. If it works, I will get back yo you.
Hey,
The Slideshow is working RIDICULOUSLY AWESOME. I am having 1 problem - it is not working in Chrome. After reading through the comments, i added this to the .js:
var slides = $('#slideshow ul li'),
but it is still not working - any ideas??
Hi,
I also have the problem with Chrome.
Do you have a solution for this yet?
Really great tutorial otherwise.
The slideshow works perfectly in the Demo, but when I downloaded it and ran it, the slideshow did not work. I am running the latest version of Google Chrome and it gives me the error "Unable to get image data from canvas because the canvas has been tainted by cross-origin data." in the script.js file. Does anyone know how to fix this error?
And still one awesome tutorial! Thanks!
not working i smartphone....
how to make it touchable...and auto play
Hai,
Very Great Tutorial. i need to fade automatically . Can i have any Solution ?
I wrote a few minutes ago about this awesome script not working on my iPhone after it did previously work before installing auto advance. I went to look for answers after finding a "javascript execution exceeded timeout" error while in debug mode in safari (iphone). It appears there may be a bug in safari that is related to line 115 of your javascript where the math may exceed the time safari will allow for the computation.
You may need to break that computation down into multiple steps so that this does not continue to happen. If it does occur, the browser has to be "killed" in order to get javascript working again. :(
Hi, I like this tutorial. But I have a problem substitute img src="img/photos/1.jpg"
into a http url, such as
Any solution?
Hi. This was a great tutorial. But now the latest Google Chrome update (18.0.1025.168) has a bug in the canvas rendering. The fade transition will not work between the slides. There is flickering. It also effects video embedded elsewhere on the same page - causing the videos to reload every time a slide transitions. Has anyone come across any kind of fix for this?
I saw something about alpha not resetting properly to 1 and expressing alpha as rgba (0,0,0,1) or some such - but I'm not sure where or how it applies.
Any help would be appreciated - I have canvas slide shows in a number of my sites and they are all malfunctioning in Chrome.
Paul, Phil & Cathrine:
I had the same issue, you need to amend your CSS file to point towards the arrows. Be aware that if you're using Dreamweaver to add this in to your webpage this gave me some issues, you may be better off doing it manually ala notepad.
I have an issue though;. Any tips?
I have loaded the latest versions of the script.js and autoadvance.js file and the slideshow still does not work in IE9 (9.08112.16421). Update v 9.0.6
Works perfectly in Firefox, Chrome and Safari (for PC)
Thanks in advance for your assistance!
Thanks for the great tutorial. I put the slideshow up on a website and it works great but I can't see the next and previous arrows. They are working fine and I can click on them to move forward and backward throught the slideshow. I just can't see them. Any ideas? Thanks
how can i do to meke this slideshow change pics automatically?
There is a tutorial on that at this link.
that's cool I just have a problem my arrows don't appear on the slideshow
You would need to upload the arrow.png
Then go into the css and fine the part with arrow.png and make sure it's pointing to the correct directory.
Hi,
I'm trying to use this slideshow on my site but i can't get it to appear on ie9.
It works perfectly on Firefox and Chrome but on ie9 it's not showing the first image and the images are showing only half.
Please help!
Hey. Just tried implementing this one for a project of mine.
I think there might be something up with my canvas element, because as it's supposed to do a photoshop kind of "overlay" function, mine just fades to black.
I've tried it out locally and on my server, the markup,css and scripts have all been written according to the tutorial and copied over a second time straight from the page to make sure there was no mistakes made - still no overlay effect.
I'm using Firefox 14.0.1
Hi,
Nice slideshow and awesome tutorial. But I have a question. How do I adapt this to support images of different dimensions. I have some images in landscape and a few in portrait. I have changed the canvas size, but there is a big white space to the left for portrait and underneath for landscape. I want to know if there is a cleaner way to implement it.
Thanks.
For the sake of time and not spending hours on this, I have just created 2 separate slideshows with 2 separate scripts on the same page to allow for both portrait and landscape type photos if that helps anyone looking for a similar solution.
Images are not sliding in Chrome. According to google I have the latest version (21.0.1180.79)
I like this tutorial but not working i smartphone....
how to make it touchable
This is a wonderful tutorial, this is the best transition I have ever seen. Still, as Garry said .". I am working with the bootstrap CSS framework on a wordpress platform. I am desperately trying to adapt the code to bootstrap's slideshow, a more dynamic version of this slideshow would be amazing
I am able to switch from an image to a vimeo video, and then play the video. Once the slider has moved to the video, it will not move to the next (hopefully video) or to the previous slide.
Any Suggestions?
Thanks!
It doesn't seem to work in Chrome (I am only able to see 1 image). How do I fix this?
Thanks.
Can someone help with removing the zoom/overlay function, and just insert a fade when you click onto the next slide?
Brilliant tutorial, very helpful. I am trying to replace the demo images with just simple text instead of an image. doesn't work for me though. I presume this works with text and not just images?
Brilliant article. I really like the functionality of the code. The time it takes to load also is pretty good.
Thats awesome, thanks :)
Works amazing!
I am having difficulty with various sized images auto centring inside a div.
Any suggestions?
Thanks in advance!
Hi, Martin.
Nice piece of code.
I've used in a couple of sites and works like a charm.
But now I'm implementing it in a new one and even if canvas id is display none, I can see the small copies of every image whenever I hit next.
Any clue?
Hi Marty, thanks for sharing, love the simple way this can be implemented. Do you have a version with a pause function on it, like the one on the bbc home page?
I'm wanting to use this for a government website, but accessibility standards means there has to be a pause button on there.
Cheers
Hi,
First of all thanks for the great tutorial!
Second, I want to make the slider responsive but I can't get it to work. What part in the CSS should I edit for making it responsive?
If I try making the positions relative it messes up the layout of the slider.
Please help..
Thanks in advance!
Orhan
I got it! I simply added this
Thanks anyway! :)
Great contribution, truly appreciated.
Hello, Martin!
I'm new to jQuery, HTML5 and CSS3, and I'm sure many of inserting slideshow independent in the same HTML file.
I noticed that it used a div # slideshow, but I think I needed it to be a class. I tried but could not ... I believe we need to change the JS too, but do not know how.
Could you give me a hand?
Thank you!
I couldn't resist commenting. Perfectly written!
|
https://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery
|
CC-MAIN-2017-39
|
refinedweb
| 5,510 | 75.71 |
29370/python-print-variable-and-string-in-same-line
The problem is on my last line. How do I get a variable to work when I'm printing text either side of it?
Here is my code:
currentPop = 12346
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there is a birth every 7 seconds, there would be: " births "births"
For a better understanding you can refer the following link string formatting:
Use comma (,) to separate strings and variables while printing: eg
print "If there is a birth every 7 seconds, there would be: ",births,"births"
, in print statement separtes the items by a single space:
>>> print "abc","bcd","def"
abc bcd def
This can be done using simple string ...READ MORE
You need to double the {{ and }}:
>>> x = ...READ MORE
class Solution:
def firstAlphabet(self, s):
self.s=s
k=''
k=k+s[0]
for i in range(len(s)):
if ...READ MORE
It seems like you're using the wrong ...READ MORE
is is used for identity testing and ...READ MORE
You can try the following and see ...READ MORE
suppose you have a string with a ...READ MORE
You can also use the random library's ...READ MORE
Use , to separate strings and variables while printing:
print ...READ MORE
In cases when we don’t know how ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.
|
https://www.edureka.co/community/29370/python-print-variable-and-string-in-same-line
|
CC-MAIN-2022-21
|
refinedweb
| 282 | 69.72 |
NAME
HTML::Prototype::Js - prototype library, embedded in perl
SYNOPSIS
our $prototype = do { package HTML::Prototype::Js; local $/; <DATA> };
DESCRIPTION
This is the actual Prototype library embedded in a perl __DATA__ section, for easy inclusion in HTML::Prototype.
NEW SYNTAX
The prototype library provides some functions and classes which effectively change the basic syntax of the JavaScript you write.
- $(element)
This function takes an element / element list and gets all string elements using document.getElementbyId. This is probably one of the most common functions when using javascript for web development, so it will save you a lot of typing.
- Class
This uses fucntion references to allow namespace-like Class structures in javascript.
- Object.extend
Simple inheritance for javacsript. Will set all properties of the child in the parent.
- Function.bind
Allow function refs to be full object method references, through the use of extend and apply
- Try.these
Simple try/catch for a list of functions, will return the return value of the first that doesn't throw an exception.
- Array.push
implement push for arrays. returns number of elements in result.
- Function.apply
Call a function on a given object, using eval.
JS OBJECTS
The Prototype library provides a number of classes you can use to improve interaction with the end user.
- Ajax
Provides one useful function, getTransport. This function will return a XMLHttpRequest object suitable for your browser.
- Ajax.Base
An abstract base class for the Ajax objects described below. Sets some common options for Ajax objects; method: http method, defaults to post. asynchronous: process in the background, true/false, defaults to true. parameters: extra parameters, defaults to blank.
- Ajax.Updater
a subclass of Ajax.Base, this class uses Ajax.Request to populate a container in your web page. Takes container, url and Ajax.Base options as paramters.
- Ajax.Request'
- Effect.Appear
Takes an element, and makes that element appear through a fade.
- Effect.ContentZoom
Takes an element, and zooms the content of that element.
- Effect.Fade
Takes an element, and makes that element fade out and disappear.
- Effect.Highlight
Takes an element, and does a highlight of that element.
- Effect.Puff
Takes an element, and makes that element "blow up" and disappear. (As in disappear in a puff of smoke).
- Effect.Scale
Takes an element, and a size, in percent, and scales that element to the given size. If it's a div, the initial size will have to be given in EM. No such restrictions for pictures.
- Effect.Squish
Takes an element, and shrinks that element until it disappears.
- Element)
- Field
Adds some useful functions to HTML Fields with several elements: clear: remove all content. focus: Give the element focus. present: returns true if all arguments are filled in, false otherwise. select(element): Select the given element in a form. activate(element): give the selected element focus, and select it.
- Form.
- Form.Element
Some useful objects for Form Field Elements. These take an element as the sole argument. serialize: url encode the element for use in a URI string. getValue: returns the value of the given element.
- Form.Element.Observer
-
- Form.Element.Serializers
Serializers for various element types. Takes the input element as argument. input: determines the element type, and chooses the right serializer. inputSelector: serialize checkbox/radio.
- Form.Element.Observer
-
- Insertion
This can be used in place of a innerHTML, to insert the content into the dom.
- Insertion.Before
Puts content before a given dom node.
- Insertion.Top
Puts content at the top of a given dom node.
- Insertion.Bottom
Puts content at the bottom of a given dom node.
- Insertion.After
Puts content after a given dom node.
- PeriodicalExecuter
This object takes two parameters, a reference to a callback function, and a frequency in seconds. It will execute the callback every <frequency> second.
SEE ALSO
HTML::Prototype, Catalyst::Plugin::Prototype
AUTHOR
Sebastian Riedel,
[email protected] Marcus Ramberg,
[email protected]
Built around Prototype by Sam Stephenson. Much code is ported from Ruby on Rails javascript helpers.
LICENSE
This library is free software. You can redistribute it and/or modify it under the same terms as perl itself.
|
https://web-stage.metacpan.org/pod/HTML::Prototype::Js
|
CC-MAIN-2021-25
|
refinedweb
| 684 | 52.26 |
I cannot instantiante activex component from vb.net (Cannot create ActiveX component) but in vbs yes
- 29 September 2011 12:28Hi everyone.
I really stuck and I don't know how to fix it.
You see, I create from server (windows Server 2003, service pack 2 ) a com+ application. I am in the domain from the active directory. I connected to the server with another accout, also from the same domain.
once that I created the com+ application proxy, I copied the MSI and cab files to my computer (Windows xp sp 3) and I installed the COM+.
I create a test.vbs, with:
Dim a
Set a = CreateObject("ComProxy.ClasePrueba")
a.funcionDePrueba("hola")
Msgbox "OK"
Here, the vbs works fine, ok.
But, when I try to do the same in vb.net in visual studio 2003, I got the well know 429 error "Cannot create ActiveX component"
I tried a thousand times with little variances int he process, with the same result. This drive me crazy.
Another guy, (also Windows xp sp 3) in his machine can instances the com+ app.
Both accounts haven't permissions to connect to the server (that's why we connect with a generic account)
I watch the dcomcnfg and both have the same configuration, same limits (allow local and remote access to Everyon) , both activate to the same ip address.
Any idea? someone else has had this error?
I tried to clean up the stack of the wrapper, but I don't know how.
I add the the "Imports System.Runtime.InteropServices" in namespace
I put the next line before call the CreateObject statement
Marshal.ReleaseComObject(ComProxy.ClasePrueba)
but is wrong, Does anybody knows how can I clean the heap of the wrapp class?
Thanks in advance!
Any suggestion will be appreciated
Muss ist sein?? ... Ist muss sein!!!!!... Aber, ist konnte auch andere sein.......
Semua Balasan
- 29 September 2011 17:44Did you look in the Event log on the Server (where COM+ is running)? This error should log an event which will provide more information about the ActiveX failure.
Paul ~~~~ Microsoft MVP (Visual Basic)
- 03 Oktober 2011 7:42Moderator
Hi Alexandor,
Welcome to the MSDN Forum.
What's your VB.NET code? please post it here. It will be helpful to us to find the cause.
Best regards,
Mike Feng [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
|
http://social.msdn.microsoft.com/Forums/id-ID/vbinterop/thread/0ec3c812-8132-41f7-96f9-87a977d445a4
|
CC-MAIN-2013-20
|
refinedweb
| 420 | 66.84 |
25 March 2011 17:06 [Source: ICIS news]
LONDON (ICIS)--Here is Friday’s end of day European oil and chemical market summary from ICIS.
CRUDE: May WTI: $105.09/bbl, down $0.51/bbl. May BRENT: $115.53/bbl, down $0.19/bbl
Crude oil futures were relatively unchanged from Thursday as the negative effect of fears over the debt crisis in Europe was countered by supply disruptions in ?xml:namespace>
NAPHTHA: $993-1001/tonne, up $6/tonne
The cargo range climbed from earlier in the day, driven by a stronger crack spread. One trade took place this afternoon. April swaps were assessed at $988-989/tonne.
BENZENE: $1,205-1,215/tonne, up $5-15/tonne
April benzene traded in the afternoon session at $1,210/tonne CIF ARA. March and April were both valued at $1,205-1,215/tonne CIF ARA, following the deal.
STYRENE: $1,467-1,480/tonne, steady
The market was quiet with no deals. March and April prices were unchanged from the morning session.
TOLUENE: $1,040-1,070/tonne, steady
April toluene bids and offers were unchanged. Traders described the market was very quiet owing to the upcoming NPRA meeting in the US.
MTBE: $1,198-1,202/tonne, up by $18-34/tonne
Prices continued to increase more or less in line with gasoline prices. EuroBob gasoline traded at $958-963/tonne, putting the MTBE factor against cash barges at 1.25.
PARAXYLENE: $1,710-1,720/tonne, steady
Spot prices were steady and there were no bids or offers. Product remained tight and
|
http://www.icis.com/Articles/2011/03/25/9447058/evening-snapshot-europe-markets-summary.html
|
CC-MAIN-2014-52
|
refinedweb
| 264 | 76.93 |
Using enzyme with Jest
Configure with Jest
To run the setup file to configure Enzyme and the Adapter with Jest direct
setupTestFrameworkScriptFile in your config file (check Jest's documentation for the possible locations of that config file) to literally the string
<rootDir> and the path to your setup file.
{ "jest": { "setupTestFrameworkScriptFile": "<rootDir>src/setupTests.js" } }
Jest version 15 and up
Starting with version 15, Jest no longer mocks modules by default. Because of this, you no longer have to add any special configuration for Jest to use it with enzyme.
Install Jest, and its Babel integrations, as recommended in the Jest docs. Install enzyme. Then, simply require/import React, enzyme functions, and your module at the top of a test file.
import React from 'react'; import { shallow, mount, render } from 'enzyme'; import Foo from '../Foo';
You do not need to include Jest's own renderer, unless you want to use it only for Jest snapshot testing.
Example Project for Jest version 15+
Jest prior to version 15
If you are using Jest 0.9 – 14.0 with enzyme and using Jest's automocking feature, you will need to mark react and enzyme to be unmocked in your
package.json:
package.json:
{ "jest": { "unmockedModulePathPatterns": [ "node_modules/react/", "node_modules/enzyme/" ] } }
If you are using a previous version of Jest together with npm3, you may need to unmock more modules.
|
http://airbnb.io/enzyme/docs/guides/jest.html
|
CC-MAIN-2018-39
|
refinedweb
| 227 | 51.68 |
Introduction
In previous blog posts [1], [2], we’ve built the Mosquitto MQTT broker on Edison and created a sensor node for sensing motion, temperature, and light level. In this article, we will connect those sensors and actuators to the Mosquitto MQTT server we’ve built to turn those sensors into true IoT sensors.
Using MQTT
Basic MQTT Publish/Subscribe
MQTT is a publish/subscribe protocol built on top of TCP/IP protocol. MQTT is one of the popular protocols being used for M2M (Machine to Machine) communications. The two main components of MQTT are the MQTT clients and the MQTT broker. The MQTT clients publish messages to a particular topic or, subscribe and listen, to a particular topic. The MQTT broker receives all published messages from MQTT publishers and forward the relevant messages to all MQTT subscribers. Subscribers and publishers do not have to be aware of each other, only the topics and messages are relevant. To properly communicate, publishers and subscribers have to agree to use a common topic name and message format.
To publish or subscribe to an MQTT topic, a MQTT client program is needed. In the Mosquitto MQTT distribution, the publishing client is called ‘mosquitto_pub’ and the subscribing client is called‘mosquitto_sub’.
The screenshot below shows the sequence of activities we’ll be describing next. The red window shows outputs of the ‘mosquitto_sub’ commands and the black window shows the ‘mosquitto_pub’ commands. Commands were labeled so that we can refer to them conveniently.
The minimal arguments required for the MQTT clients are: the broker IP address, the topic name and for the publishing clients, the message. Assuming that we already have an MQTT broker running on 127.0.0.1 (localhost), the command below will listen to all messages published to a topic named ‘edison/hello’
1sub 3> mosquitto_sub –h localhost –t edison/hello
To publish to the topic ‘edison/hello’:
1 pub 3> mosquitto_pub –h localhost –t edison/hello –m “Message#1: Hello World!”
When the MQTT broker receives the publication to topic ‘edison/hello’ with the message ‘Message#1: Hello World’ from the publishing client (pub3), it scans for subscribers that was listening to the topic ‘edison/hello’. Having found that the subscribing client, (sub3) was listening to the same topic, the MQTT broker forward the message to (sub3). When subscribing client (sub3) receives the message, it echo the message content to the terminal window. In the (sub 3) and (pub 3) commands, the default MQTT port number was implicitly assumed to be 1883 and was not specificed on the commandline. In (sub 4) and(pub 4) commands, the port number is explicitly provided. In (sub 5) and (pub 5) commands, the option ‘-v’was added to the subscription argument to enable printing of the topic name as well as the message. This will be useful when subscribing to multiple topics using wildcards. The subscription client is persistent, so that additional messages published to the topic ‘edison/hello’ in command (pub 6) will be seen by the subscription client.
The default MQTT broker behavior is to discard the message as soon as it was delivered to subscribing clients. When a new topic ‘edison/hello1’ was published by client (pub 7), subscribing client (sub 5) was listening to the topic ‘edison/hello’, hence was not informed. The subscribing client then subscribes to the new topic (sub 6), the previous message published to the topic ‘edison/hello1’ was already discarded. It will receive subsequent publish to ‘edison/hello1’ topic as shown in command (pub 8). There are additional options to tell the MQTT broker to retain the last message published to a topic as well as other QOS (Quality of Service) directives on how messages should be delivered by the broker. More details on these capabilities can be found at the MQTT Wiki site.
Depending on the configuration of the ports, additional arguments may be needed. We will discuss these later in this document.
Subscribing to multiple MQTT topics
Usually, one would have an MQTT client subscribing to multiple topics from a publisher and perform certain action based on the message received. It is worth a few words discussing how MQTT topic are organized.
MQTT topics are organized in a directory structure with the ‘/’ character used to indicate sub-topics. The listing below are examples of various topics:
1 Temperature/Building1/Room1/Location1
2 Temperature/Building1/Room1/Location2
3 Temperature/Building2/Room2
4 Temperature/Outdoor/West
5 Temperature/Outdoor/East
6 Temperature/Average
A subscribers can subscribe to one single topic, such as ‘Temperature/Outdoor/West’ or to multiple topics using wildcards. There are two wildcard characters in MQTT ‘+’ and ‘#’. The ‘+’ wildcard is used to subscribe to topics at the same hierarchical level. The ‘#’ wildcard is used to subscribe to all sub-topics below the specified topics. For example, subscribing to the topic ‘Temperature/#’ will return result when any of the topics in above list have a new message. Subscribing to ‘Temperature/+’ will return only ‘Temperature/Average’ since all other entries are sub-topic. More details on MQTT data organization can be found on the MQTT wiki site.
Configuring a secured Mosquitto broker
There are basically 4 methods to connect a MQTT client to the Mosquitto server.
Open port or no security. This is a convenient method to develop and test MQTT devices before deployment. Data transmission between broker and client are transmitted in plain text and can be snooped on by anyone with the right tool.
ser and password protection. This is used basically to authenticate a client to the broker. It doesn’t encrypt the data transmission.
TLS-PSK encryption. Clients and broker possess a shared secret key that they used to negotiate a secure connection. This is available in Mosquitto version 1.3.5 or later.
SSL encryption. This is the most advanced encryption and authentication scheme available in the Mosquitto MQTT distribution. With SSL encryption, one needs to obtain a server certificate from a trusted Certificate Authority (CA) such as Verisign or Equifax. Often, for testing, one can create a self-signed certificate that can then be used to sign the server certificate. This encryption method, while more secured, is cumbersome to implement as it requires all client devices to be provisioned with the correct certificates and mechanism for in-the-field upgrade must be developed to keep the certificate versions between clients and broker in sync.
To configure a secure Mosquitto MQTT broker, use the configuration directives shown below. The certificate we used in this case is a self-signed certificate for testing purpose and should not be used in production servers.
01 port 1883
02 password_file /home/mosquitto/conf/pwdfile.txt
03 log_type debug
04 log_type error
05 log_type warning
06 log_type information
07 log_type notice
08 user root
09 pid_file /home/mosquitto/logs/mosquitto.pid
10 persistence true
11 persistence_location /home/mosquitto/db/
12 log_dest file /home/mosquitto/logs/mosquitto.log
13
14 listener 1995
15 # port 1995 is the TLS-PSK secure port, client must provide
16 # --psk-identity and --psk to access
17 psk_file /home/mosquitto/conf/pskfile.txt
18 # psk_hint must be present or port 1995 won't work properly
19 psk_hint hint
20
21 listener 1994
22 # port 1994 is the SSL secure port, client must present
23 # a certificate from the certificate authority that this server trust
24 # e.g. ca.crt
25 cafile /home/mosquitto/certs/ca.crt
26 certfile /home/mosquitto/certs/server.crt
27 keyfile /home/mosquitto/certs/server.key
The file, pwdfile.txt, is a password file, encrypted in similar manner as the Linux password file. It is generated by using the mosquitto_passwd utility that comes with the Mosquitto software. The filepskfile.txt, is the pre-shared password file to be used in a TLS-PSK connection. The format of this file is a text file of one user:password pair per line. The passwords used for TLS-PSK must use only hexadecimal characters and are case insensitive. Sample of the password_file and psk_file is shown below.
1 /* sample Mosquitto password_file */
2 user:$6$Su4WZkkQ0LmqeD/X$Q57AYfcu27McE14/MojWgto7fmloRyrZ7BpTtKOkME8UZzJZ5hGXpOea81RlgcXttJbeRFY9s0f+UTY2dO5xdg==
3 /* sample Mosquitto PSK file */
4 user1:deadbeef
5 user2:DEADBEEF0123456789ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef
Incorporating MQTT into an IoT Sensor
Since the Edison board is really a Linux board that ran an Arduino sketch as one of its processes, we will leverage the existing Mosquitto MQTT package we previously built. Within the Arduino sketch, we will simply use Linux programming facilities to call the ‘mosquitto_sub’ and ‘mosquitto_pub’ programs. There are several advantages to this approach:
We don’t have to rewrite the MQTT clients for Arduino. The Mosquitto MQTT package is a well- accepted and well-tested piece of software. We only need to create a wrapper class to enable usage within an Arduino sketch.
The Mosquitto MQTT clients are capable of secured connections using SSL. The small microcontroller in a generic Arduino, on the other hand, simply cannot handle the computational demands of SSL.
When a different or better MQTT software package is found or a newer version of the existing MQTT software is released, we can re-use most of the existing code and only add new code to leverage new capability of the new package.
The MQTTClient Class
Since the Intel Edison board is a full-fledged Linux operating system, all of the Linux programming facilities are available to our Arduino sketches. We will create a wrapper class called MQTTClient that will be used in the sketch. Within the MQTTClient methods, we will use Linux system calls to invoke themosquitto_sub and mosquitto_pub program that will perform the actual MQTT data transfer for us. Below is the class definition for a minimalist MQTTClient.
01 // File: MQTTClient.h
02 /*
03 Minimalist MQTT Client using mosquitto_sub and mosquitto_pub
04 Assume Mosquitto MQTT server already installed and mosquitto_pub/sub
05 are in search path
06 */
07
08 #ifndef __MQTTClient_H__
09 #define __MQTTClient_H__
10
11 #include <Arduino.h>
12 #include <stdio.h>
13
14 enum security_mode {OPEN = 0, SSL = 1, PSK = 2};
15
16 class MQTTClient {
17
18 public:
19 MQTTClient();
20 ~MQTTClient();
21 void begin(char * broker, int port, security_mode mode,
22 char* certificate_file, char *psk_identity, char *psk);
23 boolean publish(char *topic, char *message);
24 boolean subscribe(char* topic, void (*callback)(char *topic, char* message));
25 boolean loop();
26 boolean available();
27 void close();
28
29 private:
30 void parseDataBuffer();
31 FILE* spipe;
32 char mqtt_broker[32];
33 security_mode mode;
34 char topicString[64];
35 char certificate_file[64];
36 char psk_identity[32];
37 char psk_password[32];
38 int serverPort;
39 char *topic;
40 char *message;
41 boolean retain_flag;
42 void (*callback_function)(char* topic, char* message);
43 char dataBuffer[256];
44 };
45 #endif
To use the class, one starts with creating an MQTTClient object, then use MQTTClient::begin() to initialize various variables that MQTTClient::subscribe() and MQTTClient::publish() will use to connect with the MQTT broker. These variables are:
- mqtt_broker: name of the MQTT broker. This can be an IP address or a DNS name. For this article, we’ll use ‘localhost’ as the broker is running on the same Edison board as the Arduino sketch. If the Edison board was configured to use static IP address, this address can be used instead.
- serverPort: the port to be used. We configured 3 different ports on the Mosquitto broker with different security policy:
1. Port 1883 is the MQTT default port that is open to all clients.
2. Port 1994 is configured as a secured SSL port. User must supply an SSL certificate from the CA that issued the server certificate.
3. Port 1995 is configured as a secured TLS-PSK port. Users access this port with a user identity and a pre-shared password.
- mode: security mode to use. Currently, security mode can be one of OPEN, SSL or PSK. Depending on the selected security mode, the certificate, user identity and pre-shared password are supplied with the rest of the method’s arguments. Arguments that are not applicable to the selected security mode are ignored.
To subscribe to a topic, one calls MQTTClient::subscribe() with a topic name and a callback function to be invoked when a new message is available. To publish to a topic, one calls MQTTClient::publish() and supply a topic name and message to be publish.
For both subscribe and publish method, the appropriate command string to invoke either mosquitto_sub ormosquitto_pub is formed using the method’s arguments and stored parameters. A Linux pipe is then opened and the command string is executed with results piped back to the Arduino sketch. When publishing, the pipe is immediately closed after the message was sent. When subscribing, the pipe need to be kept open so that new data can be received. Within the Arduino sketch, one needs to periodically check the pipe to see if there is any new data. The MQTTClient::loop() method was designed to check for data in the pipe and invoke the callback function to process new messages. Because the Linux pipe will block if the pipe is empty when checked, we’ve made the pipe non-blocking so that the MQTTClient::loop()method will return if the pipe is empty. Pseudo-code below shows typical usage of the MQTTClient class.
01 #include <MQTTClient.h>
02 #define SAMPLING_PERIOD 100
03 #define PUBLISH_INTERVAL 30000
04
05 MQTTClient mqttClient;
06
07 void setup() {
08 mqttClient.begin(“localhost”,1833,PSK,NULL,”psk_user”,”psk_password”);
09 mqttClient.subscribe(“edison/#”,myCallBack);
10 }
11
12 void myCallBack(char* topic, char* message) {
13 // scan for matching topic, scan for matching command, do something useful
14 }
15
16 unsigned long publishTime = millis();
17 void loop() {
18 mqttClient.loop(); // check for new message
19 if (millis() > publishTime) {
20 publishTime = millis() + PUBLISH_INTERVAL;
21 mqttClient.publish(“edison/sensor1”,”sensor1value”);
22 mqttClient.publish(“edison/sensor2”,”sensor2value”);
23 }
24 delay(SAMPLING_PERIOD);
25 }
The variable “SAMPLING_PERIOD” determines the frequency the code will check for new messages and should be chosen such that a new message that will cause some action from the sketch will not arrive too late for meaningful actions. Most of the time, MQTTClient::loop() method will return quickly and there is minimal overhead in sampling the loop frequently. The publication interval is determined by the variable“PUBLISH_INTERVAL” and should be chosen at the appropriate data rate for the given sensor e.g. a temperature sensor may publish its value once a minute if it is merely for informational purpose while a smoke sensor may want to update its result every few seconds so that a subscriber listening to the smoke sensor messages will have a chance to act before it is too late.
An implementation of the MQTTClient class is shown below.
001 // File: MQTTClient.cpp
002 #include "MQTTClient.h"
003 #include <fcntl.h>
004
005 /*======================================================================
006 Constructor/Destructor
007 ========================================================================*/
008 MQTTClient::MQTTClient()
009 {
010 }
011 MQTTClient::~MQTTClient()
012 {
013 close();
014 }
015 void MQTTClient::close()
016 {
017 if (spipe) {
018 fclose(spipe);
019 }
020 }
021 /*========================================================================
022 Initialization. Store variables to be used for subscribe/publish calls
023 ==========================================================================*/
024 void MQTTClient::begin(char *broker, int port, security_mode smode,
025 char* cafile, char *user, char *psk)
026 {
027 strcpy(mqtt_broker, broker);
028 serverPort = port;
029 mode = smode;
030 if (mode == SSL) {
031 strcpy(certificate_file, cafile);
032 }
033 else if (mode == PSK) {
034 strcpy(psk_identity, user);
035 strcpy(psk_password, psk);
036 }
037 Serial.println("MQTTClient initialized");
038 Serial.print("Broker: "); Serial.println(mqtt_broker);
039 Serial.print("Port: "); Serial.println(serverPort);
040
Serial.print("Mode: "); Serial.println(mode);
041 }
042 /*=======================================================================
043 Subscribe to a topic, (*callback) is a function to be called when client
044 receive a message
045 =========================================================================*/
046 boolean MQTTClient::subscribe(char* topic,
047 void (*callback)(char* topic, char* message))
048 {
049 char cmdString[256];
050
051 if (mqtt_broker == NULL) {
052 return false;
053 }
054 if (topic == NULL) {
055 return false;
056 }
057
058 callback_function = callback;
059 switch(mode) {
060 case OPEN:
061 sprintf(cmdString,
062 "mosquitto_sub -h %s -p %d -t %s -v",
063 mqtt_broker, serverPort, topic);
064 break;
065 case SSL:
066 sprintf(cmdString,
067 "mosquitto_sub -h %s -p %d -t %s -v --cafile %s",
068 mqtt_broker, serverPort, topic, certificate_file);
069 break;
070 case PSK:
071 sprintf(cmdString,
072 "mosquitto_sub -h %s -p %d -t %s -v --psk-identity %s --psk %s",
073 mqtt_broker, serverPort, topic, psk_identity, psk_password);
074 break;
075 default:
076 break;
077 }
078 if ((spipe = (FILE*)popen(cmdString, "r")) != NULL) {
079 // we need to set the pipe read mode to non-blocking
080 int fd = fileno(spipe);
081 int flags = fcntl(fd, F_GETFL, 0);
082 flags |= O_NONBLOCK;
083 fcntl(fd, F_SETFL, flags);
084 strcpy(topicString, topic);
085 return true;
086 }
087 else {
088 return false;
089 }
090 }
091 /*====================================================================
092 Check if there is data in the pipe,
093 if true, parse topic and message and execute callback function
094 return if pipe is empty
095 ======================================================================*/
096 boolean MQTTClient::loop()
097 {
098 if (fgets(dataBuffer, sizeof(dataBuffer), spipe)) {
099 parseDataBuffer();
100 callback_function(topic, message);
101 }
102 }
103 /*====================================================================
104 Publish a message on the given topic
105 ======================================================================*/
106 boolean MQTTClient::publish(char *topic, char *message)
107 {
108 FILE* ppipe;
109 char cmdString[256];
110 boolean retval = false;
111 if (this->mqtt_broker == NULL) {
112 return false;
113 }
114 if (topic == NULL) {
115 return false;
116 }
117 switch (this->mode) {
118 case OPEN:
119 sprintf(cmdString,
120 "mosquitto_pub -h %s -p %d -t %s -m \"%s\" %s",
121 mqtt_broker, serverPort, topic, message, retain_flag?"-r":"");
122 break;
123 case SSL:
124 sprintf(cmdString,
125 "mosquitto_pub -h %s -p %d --cafile %s -t %s -m \"%s\" %s",
126 mqtt_broker, serverPort, certificate_file,
127 topic, message, retain_flag?"-r":"");
128 break;
129 case PSK:
130 sprintf(cmdString,
131 "mosquitto_pub -h %s -p %d --psk-identity %s --psk %s -t %s -m \"%s\" %s",
132 mqtt_broker, serverPort, psk_identity, psk_password,
133 topic, message, retain_flag?"-r":"");
134 break;
135 }
136 if (!(ppipe = (FILE *)popen(cmdString, "w"))) {
137 retval = false;
138 }
139 if (fputs(cmdString, ppipe) != EOF) {
140 retval = true;
141 }
142 else {
143 retval = false;
144 }
145 fclose(ppipe);
146 return retval;
147}
148 /*======================================================================
149 Parse data in the data buffer to topic and message buffer
150 delimiter is the first space
151 if there is only one recognizable string, it is assumed a message
152 string and topic is set to NULL
153 ========================================================================*/
154 void MQTTClient::parseDataBuffer()
155 {
156 topic = dataBuffer;
157 message = dataBuffer;
158 while((*message) != 0) {
159 if ((*message) == 0x20) {
160 // replace the first space with the NULL character
161 (*message) = 0;
162 message++;
163 break;
164 }
165 else {
166 message++;
167 }
168 }
169 if (strlen(message) == 0) {
170 topic = NULL;
171 message = dataBuffer;
172 }
173 }
The Sensor Node
In the blog posting “Using Intel Edison: Building an IoT Sensor Node”, we built a sensor node with a few sensors and actuators:
1. A motion sensor to detect motion
2. A temperature sensor to measure ambient temperature
3. A light sensor to measure ambient light level
4. A push button to detect a user action i.e. user pushing the button
5. A red LED to toggle when a button push is sensed
6. A green LED to light up when the motion sensor detects motion
Using MQTT, we will periodically publish various sensor readings to the Mosquitto broker running on the same Edison board and subscribe to all topics, ‘edison/#’. We made slight changes to the operation of the sensor node:
1. The push button no longer toggle the red LED. It has been repurposed as a signal to toggle a boolean variable that will be transmit to MQTT subscribers.
2. The red LED now can only be controlled through MQTT messages. This can be a proxy for an internet controlled lamp that can be turn on or off remotely.
3. The behavior of the green LED can now be controlled through MQTT. It can be programmed to track the motion sensor activity, or disabled.
The main Arduino sketch is shown below.
001 // File: MQTT_IoT_Sensor.ino
002
003 /******************************************************************************
004 Internet of Thing Sensor Node using Intel Edison Development board
005******************************************************************************/
006
007 #include <stdio.h>
008
#include <Arduino.h>
009
010 #include "sensors.h"
011 #include "MQTTClient.h"
012
013 // Global variables
014 unsigned long updateTime = 0;
015 // PIR variables
016 volatile unsigned long activityMeasure;
017 volatile unsigned long activityStart;
018 volatile boolean motionLED = true;
019 unsigned long resetActivityCounterTime;
020
021 // button variables
022 boolean toggleLED = false;
023 volatile unsigned long previousEdgeTime = 0;
024 volatile unsigned long count = 0;
025 volatile boolean arm_alarm = false;
026
027 // MQTT Client
028 #define SECURE_MODE 2
029 MQTTClient mqttClient;
030 char fmtString[256]; // utility string
031 char topicString[64]; // topic for publishing
032 char msgString[64]; // message
033
034 /*****************************************************************************
035 Setup
036 ******************************************************************************/
037 void setup() {
038 Serial.begin(115200);
039 delay(3000);
040 Serial.println("Ready");
041
042 pinMode(RED_LED, OUTPUT);
043 pinMode(GREEN_LED, OUTPUT);
044 pinMode(BUTTON, INPUT_PULLUP);
045 pinMode(PIR_SENSOR, INPUT);
046
047 // Button interrupt. Trigger interrupt when button is released
048 attachInterrupt(BUTTON, buttonISR, RISING);
049
050 // PIR interrupt. We want both edges to compute pulse width
051 attachInterrupt(PIR_SENSOR, pirISR, CHANGE);
052 digitalWrite(RED_LED, HIGH);
053 digitalWrite(GREEN_LED,LOW);
054 resetActivityCounterTime = 0;
055
056 // initializing MQTTClient
057 #if ( SECURE_MODE == 0 )
058 Serial.println("No security");
059 mqttClient.begin("localhost", 1883, OPEN, NULL, NULL, NULL);
060 #elif ( SECURE_MODE == 1 )
061 Serial.println("SSL security");
062 mqttClient.begin("localhost", 1994, SSL,
063 "/home/mosquitto/certs/ca.crt", NULL, NULL);
064 #elif ( SECURE_MODE == 2 )
065 Serial.println("TLS-PSK security");
066 mqttClient.begin("localhost", 1995, PSK, NULL, "user", "deadbeef");
067 #endif
068
069 // subscribe to all topics published under edison
070 mqttClient.subscribe("edison/#", mqttCallback);
071 mqttClient.publish("edison/bootMsg","Booted");
072 digitalWrite(RED_LED, LOW);
073 }
074 /**************************************************************************
075 MQTT Callback function
076 **************************************************************************/
077 void mqttCallback(char* topic, char* message)
078 {
079 sprintf(fmtString, "mqttCallback(), topic: %s, message: %s",topic,message);
080 Serial.print(fmtString);
081 // check for matching topic first
082 if (strcmp(topic,"edison/LED") == 0) {
083 // then execute command as appropriate
084 if (message[0] == 'H') {
085 digitalWrite(RED_LED, HIGH);
086 toggleLED = false;
087 }
088 else if (message[0] == 'L') {
089 digitalWrite(RED_LED, LOW);
090 toggleLED = false;
091 }
092 else if (message[0] == 'B') {
093 toggleLED = true;
094 }
095 }
096 if (strcmp(topic, "edison/motionLED") == 0) {
097 // note that there is an extra carriage return at the end of the message
098 // using strncmp to exclude the last carriage return
099 if (strncmp(message, "OFF", 3) == 0) {
100 digitalWrite(GREEN_LED, LOW);
101 motionLED = false;
102 }
103 else if (strncmp(message, "ON", 2) == 0) {
104 motionLED = true;
105 }
106 }
107 }
108 /***********************************************************************
109 Main processing loop
110 ***********************************************************************/
111 void loop() {
112
113 // check for any new message from mqtt_sub
114 mqttClient.loop();
115
116 if (millis() > resetActivityCounterTime) {
117 resetActivityCounterTime = millis() + 60000;
118 // publish motion level
119
sprintf(msgString,"%.0f",100.0*activityMeasure/60000.0);
120 mqttClient.publish("edison/ActivityLevel",msgString);
121 activityMeasure = 0;
122 }
123 if (millis() > updateTime) {
124 updateTime = millis() + 10000;
125 // publish temperature
126 sprintf(msgString,"%.1f",readTemperature(TEMP_SENSOR));
127 mqttClient.publish("edison/Temperature",msgString);
128
129 // publish light sensor reading
130 sprintf(msgString,"%d",readLightSensor(LIGHT_SENSOR));
131 mqttClient.publish("edison/LightSensor",msgString);
132
133 // publish arm_alarm
134 sprintf(msgString,"%s", (arm_alarm == true)? "ARMED" : "NOTARMED");
135 mqttClient.publish("edison/alarm_status", msgString);
136 }
137
138 if (toggleLED == true) {
139 digitalWrite(RED_LED, digitalRead(RED_LED) ^ 1);
140 }
141 delay(100);
142 }
Much of the code is self-explanatory. We have moved the sensors processing code to separate modules: sensors.h and sensors.cpp to improve readability. We allow for different security modes to be used by setting the SECURE_MODE variable in the main Arduino sketch. The callback function, mqttCallback(), is called whenever there is a new message from the MQTT broker. Subscribed MQTT topic name and message are passed to the callback function where they are scanned and acted upon if any of them match a set of pre-defined action. The callback function is the main mechanism to control the IOT sensor from the internet. In this case, messages published to topic ‘edison/LED’ is used to turn the red LED on, off, or blink and messages published to topic ‘edison/motionLED’ is used to control the behavior of the green LED to either track the motion sensor output or not.
01 // File: sensors.h
02 //
03 #define USE_TMP036 0
04
05 #define RED_LED 10 // Red LED
06 #define GREEN_LED 11 // Green LED
07 #define BUTTON 13 // push button with 10K pull up resistor
08 #define PIR_SENSOR 12 // Infrared motion sensor
09 #define LIGHT_SENSOR A0 // light sensor
10 #define TEMP_SENSOR A1 // TMP36 or LM35 analog temperature sensor
11
12 #define MIN_PULSE_SEPARATION 200 // for debouncing button
13 #define ADC_STEPSIZE 4.61 // in mV, for temperature conversion.
14
15 #if (USE_TMP036 == 1)
16 #define TEMP_SENSOR_OFFSET_VOLTAGE 750
17 #define TEMP_SENSOR_OFFSET_TEMPERATURE 25
18 #else // LM35 temperature sensor
19 #define TEMP_SENSOR_OFFSET_VOLTAGE 0
20 #define TEMP_SENSOR_OFFSET_TEMPERATURE 0
21 #endif
22
23 // Global variables
24 extern unsigned long updateTime;
25 // PIR variables
26 extern volatile unsigned long activityMeasure;
27 extern volatile unsigned long activityStart;
28 extern volatile boolean motionLED;
29 extern unsigned long resetActivityCounterTime;
30
31 // button variables
32 extern boolean toggleLED;
33 extern volatile unsigned long previousEdgeTime;
34 extern volatile unsigned long count;
35 extern volatile boolean arm_alarm;
36 float readTemperature(int analogPin);
37 int readLightSensor(int analogPin);
38 void buttonISR();
39 void pirISR();
01 // File: sensors.cpp
02 #include <Arduino.h>
03 #include "sensors.h"
04 /***********************************************************************************
05 PIR Sensor
06 Each time the sensor detect motion, the output pin goes HIGH and stay HIGH as
07 long as there is motion and goes LOW 2 or 3 seconds after motion ceased
08 We will count the duration when the PIR sensor output is HIGH as a measure of
09 Activity. The main loop will report the activity level as percentage of time in the
10 previous time interval that motion was detected
11 ************************************************************************************/
12 void pirISR()
13 {
14 int pirReading;
15 unsigned long timestamp;
16 timestamp = millis();
17 pirReading = digitalRead(PIR_SENSOR);
18 if (pirReading == 1) {
19 // mark the start of the pulse
20 activityStart = timestamp;
21 }
22 else {
23 int pulseWidth = timestamp-activityStart;
24 activityMeasure += pulseWidth;
25 }
26 // light up GREEN LED when motion is detected
27 if (motionLED == true) {
28 digitalWrite(GREEN_LED, pirReading);
29 }
30 }
31 /************************************************************************
32 return light sensor reading
33 ************************************************************************/
34 int readLightSensor(int sensorPin)
35 {
36 return analogRead(sensorPin);
37 }
38 /***********************************************************************
39 return temperature in Fahrenheit degrees
40 ***********************************************************************/
41 float readTemperature(int sensorPin)
42 {
43 int sensorReading;
44 float temperature;
45 sensorReading = analogRead(sensorPin);
46 // convert to millivolts
47 temperature = sensorReading * ADC_STEPSIZE;
48 // Both LM35 and TMP036 temperature sensor has temperature slope of 10mV
49 // per degrees celsius
50 // LM35 offset voltage is 0 mv, TMP036 offset voltage is 750 mV
51 // LM35 offset temperature is 0 degree C, TMP036 offset temperature is 25 degrees C
52 temperature = (temperature - TEMP_SENSOR_OFFSET_VOLTAGE)/10.0 +
53 TEMP_SENSOR_OFFSET_TEMPERATURE;
54 // convert to fahrenheit
55 temperature = temperature * 1.8 + 32.0;
56 return temperature;
57 }
58 /*************************************************************************
59 Interrupt handler for button press
60 **************************************************************************/
61 void buttonISR()
62 {
63 // if current edge occurs too close to previous edge, we consider that a bounce
64 if ((millis()-previousEdgeTime) >= MIN_PULSE_SEPARATION) {
65 arm_alarm = !arm_alarm;
66 Serial.print("Alarm is: ");
67
if (arm_alarm == true) {
68 Serial.println("ARMED");
69 }
70 else {
71 Serial.println("NOT ARMED");
72 }
73 count++;
74 Serial.print("Count: "); Serial.println(count);
75 }
76 previousEdgeTime=millis();
77 }
Testing
To test the IoT sensor, we’ll need to use an MQTT client to subscribe to the topics published by the sensor, and another MQTT client to publish topics that the sensor will response to. We can use ‘SSH’ to log into the Edison board and use the mosquitto_sub/pub command to observe and control the sensor node locally or we can use a different host that also have the Mosquitto package installed.
To test the sensor node:
On the subscribing client, subscribe to all topics
$> mosquitto_sub –h ipaddr –p 1883 –t edison/# -v
Where ipaddr is the IP address of the Edison board. Substitute “localhost” if running on the Edison board itself. We use the open port, 1883, to connect to the broker in this case. We can also use port 1994 with a certificate or port 1995 with PSK user name and password. After successfully subscribe to topic ‘edison/#’, we should see the sensor readings along with any commands issued through the publishing client.
On the publishing client, publish to topic edison/LED to control the red LED or to Edison/motionLED to enable/disable the green LED
$> mosquitto_pub –h ipaddr –p 1883 –t Edison/LED –m {H, L, B}
$> mosquitto_pub –h ipaddr –p 1883 –t Edison/motionLED –m {ON, OFF}
The red LED should turn ON, OFF or blink when each of the command above was published.
To stop the green LED from tracking the motion sensor, publish to topic ‘edison/motionLED’ with the message ON or OFF.
The attached video shows the screencast of the testing process.
For more such intel IoT resources and tools from Intel, please visit the Intel® Developer Zone
Source:
|
https://www.digit.in/apps/using-the-intel-edison-board-to-securely-connect-sensors-with-mqtt-26066.html
|
CC-MAIN-2018-34
|
refinedweb
| 4,822 | 50.77 |
ICANN's Brand-Named Internet Suffix Application Deadline Looms 197
AIFEX writes with a snippet from the BBC: ".'" Asks AIFEX: "Does anyone else think this is absolutely ridiculous and defeats the logical hierarchy of current URLs?"
If bullshit sells (Score:3, Insightful)
Re: (Score:2, Informative)
What is wrong with selling something if a customer or person likes it?
/. so I'll pose this question:
It's just an address, although I find it similar to a customised number plate, nobody really cares. Not sure about the rest of people on
How often to you manually type a web address like this?
I know that I don't, it is usually copied and pasted, linked in an email, linked from another site or I get automatically redirected. If brands officially register a
.brand address then at least I know the website I
Re: (Score:2)
It confises people for one. Do you know how many people get confused by a [email protected] email address?
It also doesn't match the rest of the somewhat organized hierarchy.
Re: (Score:3)
By that logic, the RMV could start selling licenses to drive the wrong way down one way streets because customers like them. ICANN is not meant to be in the business of offering "innovative and exciting new products". They're in charge of a system that they're supposed to keep operating smoothly. Instead of doing that, they only seem to be interested in exploitation.
No (Score:3)
No.
Re: (Score:3)
While I see a need for
.xxx I do not see a need for .brand suffixes. The best reason I see for top level suffixes is to tell what kind of a site it is. But considering the exhaustion of short names, I understand their pain. Lots of businesses are going with .net or .org or .cc etc simply because they can't find anything usable in under 25 characters. When faced with the best available .com being "ronshorsebarnseattle.com" or "horsebarn.org", the choice becomes obvious. But I think adding more available
Re:No (Score:5, Insightful)
Obvious example of where a brand suffix would make sense: Apple/iPhone/iPad/iOS, Android, etc.. For example:
"Check out our new mobile Tux racing game at or download the Android version at.
Re: (Score:2)
I'd say "go to" would be a far more obvious answer, especially if the app is going cross-platform.
Now, someone like Apple might want to buy say,
.itunes, so if you wanted a particular app, you could go to "pages.itunes" to see the iTunes p
Re: (Score:3)
Good point. What's wrong with "apple.disgruntledpenguins.com" and "android.disgruntledpenguins.com"?
Re:No (Score:4, Insightful)
Re: (Score:2)
You're forgetting that the "page" for an iOS app is produced by Apple, contains reviews from Apple, etc. It's not something that can exist on a website in somebody else's domain. I'm assuming Google has similar functionality in its marketplace.
Also, the point of a domain name, to some extent, is guessability. If every app from Google's store, for example, could easily be found by typing its name dot android, it would be a win.
Re: (Score:2)
You're forgetting that the "page" for an iOS app is produced by Apple, contains reviews from Apple, etc. It's not something that can exist on a website in somebody else's domain. I'm assuming Google has similar functionality in its marketplace.
You can make a website for an iOS app and link that page to the Apple iTunes store page for that app.
Also, the point of a domain name, to some extent, is guessability. If every app from Google's store, for example, could easily be found by typing its name dot android, it would be a win.
So you can guess the TLD, but so what? "angrybirds.apple" is no easier to guess than "angrybirds.com".
Re: (Score:2)
Too late, I already registered those and am putting those to use. However I do have an alternative name which I was going to use but now am not going to, and it is a very desirable name for which I will sell you the domains for only $19999.99 each. The domain names are irritatedavians.apple and irritatedavians.android.
Seriously though - I think "disgruntled penguins" would be an AWESOME name for a made-for-Linux angry birds clone.
Re: (Score:2)
I see little point in using the already-fading-away "www" if you have a brand name TLD though.
However, domains such as "disgruntledpenguins.android" might not sound like an internet domain AT ALL.
Re: (Score:2)
Or even more braindead, just disgruntledpenguins.com and have that redirect to the detected platform subdomain with a chooser if it can't be determined which you belong on. (And a chooser on each page to get to the other one, of course.)
Re: (Score:3)
But I think adding more available suffixes is going to cause more problems by public confusion than it solves for the website owners. I wish there were an option C.
Explain this confusion you worry about?
Most people seldom type in a url anyway. They click links, or book marks.
Or they just type pepsi in the url bar and let the system deal with it, popping up a search with the desired target listed first in most instances
Would not pepsi also own pepsi.com, and pepsi.co.uk so if users fell into old habits they still arrive at the right place?
How long will this confusion last?
Will it in any way be debilitating?
Personally, I fail to see any risk here, as long as the domain
Re: (Score:2)
There are bound to be some corner cases, but it seems to me that pepsi is probably pepsi everywhere on earth.
Beyond that, it may come down to first come first serve like most other things in domain registration.
Re: (Score:2)
Re: (Score:2)
Re:No (Score:5, Interesting).
It's never going to be safe to let your kids out on the wild, wooly
.com internet without supervision. It's a pipe dream by lazy parents, a textbook example of the low-effort thinking that promotes conservatism [sagepub.com].
Re: (Score:2).
I had unused mod points for weeks... now that I need them they are gone. I would have to agree, this is a better approach.
.localhost (Score:5, Funny)
We need a
.localhost
Re: (Score:2)
Re: (Score:2)
Watch it get approved, and the ensuing anarchy
Where is the anarchist milleonair when you need one.
Re: (Score:3)
Seriously. We do need ".local" TLDs reserved officially. But all ICANN does is money grabbing.
.local is for mDNS and similar stuff: [wikipedia.org]
They should also reserve a ".here" TLD for a RFC1918 style usage, for instance if people may want to run their own DNS and area servers so that airconditioner.here to refers to the airconditioners at their current area, and [here] goes to the main page for the current area. While people can do that already, a TLD (or more) should be re
Re: (Score:2)
".localdomain" isn't really standard either, though I have seen it in some places as well. Mainly,
/etc/hosts - I've never seen it in use anywhere.
".here" is pretty clean in that it refers to you current location (room? building?), which I don't really understand the scopt of "localdomain". Is it just this PC? Or the entire subnet?
".local" is standard-ish, and means the entire subnet, use in zeroconf/avahi/bonjour.
Re: (Score:3)
We need a
.localhost
You joke, but that domain is actually reserved per RFC 2606 [ietf.org]. ICANN has no authority to issue it, and the IANA would reject it, even if ICANN attempted to approve it. (The IANA is actually part of ICANN, but only the IANA portion can actual make changes to the root zone. The rest of the organization exists just to create a business model for registrars.)
Seems commercial... (Score:5, Insightful)
... but remember that the TLD was supposed to be just that, the top-level domain. Why not allow massive organizations to have their own namespace? Granted, I do think they should be expected to provide all infrastructure services (root servers, etc.) necessary for such operations, but I don't see this as anything except a return to the original design.
Re: (Score:2)
I agree with this.
I don't see anything inherently disasterous about this, provided we keep the well known domains, and very non-specific ones free for general use.
Re:Seems commercial... (Score:4, Insightful)
I came here to post only one thing, and I'm going to post it. I hate ICANN. Starting with
Re:Seems commercial... (Score:5, Informative)
For example, at my previous company, inside the local intranet I could type 'bugzilla' in the URL bar and it would resolve to the bugzilla of our company. It's really convenient. And now this sort of system will be impossible because it might conflict with the
.wiki domain name space.
Seems like someone has never heard of default domains [tldp.org] and doesn't understand how domain name lookups work from the client side.
Re: (Score:2)
Re: (Score:2)
This would no longer work with custom TLDs, as you'd have a chance of colission.
Re: (Score:2)
Re: (Score:2)
For example, at my previous company, inside the local intranet I could type 'bugzilla' in the URL bar and it would resolve to the bugzilla of our company
I'm not sure you understood what was going on there. The internal network of your previous company had a domain, let's say it was "company.local". Your DHCP server on that network was configured to give you "company.local" as one of your default domain suffixes. This means that when your computer tried to look up something like "bugzilla" and fails because it's not a FQDN, your computer automatically tries appending all of your default domain suffixes in order until it finds a match. So it actually look
Re: (Score:2)
Effectively we're just going back to the era before
.com and other suffixes existed, and your e-mail address would be something like user@ibm or so. The first years of the Internet when it was possibly not even called Internet yet.
And with everyone wanting their
.com domain, it's just like stripping the .com like most sites already stripped the www. part (though in Hong Kong it's remarkable how many websites require the www. and simply give an error if you don't type the www, for example hko.gov.hk fails, w
Re: (Score:3)
Why not allow massive organizations to have their own namespace?
Because we have no definition of "massive" everyone agrees upon, so in the implementation that part will just be dropped and everyone who wants (and can pay the $$$) will get their own TLD.
Basically, we've just ended the hierarchical structure of the DNS. From now on, we have a flat namespace at the top-level. Because, quite frankly, what reason except cost do I have to not shorten the name of my small online game's website from battlemaster.org to just battlemaster?
Misleading summary (Score:2)
Re:Misleading summary (Score:5, Funny)
Yes, but will
.coke be for Coca Cola, or the Medellin cartel?
Coca-Cola. Here's why (Score:2)
Re: (Score:2)
or better yet, can I get
.coca-cola.pepsi and be sued by both of them?
Re: (Score:2)
I dont think Medellin cartel owns Coca Cola or Pepsi. So, of the two, only Coca Cola can sue.
Re: (Score:3)
Re: (Score:2)
Neither, it's been snatched up by a blacksmith.
Two internets (Score:2)
For those who know what they're doing, current domain names work fine.
For everyone else, they're just going to know these sites as terms they type into Google (or Bing, I guess) anyway. There's no point giving them TLDs to make it easier; you can't dumb it down enough to benefit them, and in the meantime, dumbing it down conflicts an already confusing set of standards.
STOP PRESS! Deadline Extended (Score:5, Informative) [techweekeurope.co.uk]
Icahn's brands (Score:2)
get over it (Score:2) [pepsi] resolved, who would win between my local machine named pepsi and the pepsicola pepsi domain? I guess that sort of
Re: (Score:3)
.local is reserved by zeroconf, and probably will be reserved by the IETF committee on a zeroconf-like standard. One way to solve the other problem, what "pepsi" resolves to, would be to use dots somewhere: ".pepsi" is the pepsi site, "pepsi" goes through the configured search domains before assuming its a TLD (which would work well because nobody currently goes to "com").
Plus, we get rid of the "www". Pepsi now says its website is "dot-pepsi". I could get used to that, genericised over all possible TLDs: M
Re: (Score:3)
There is already a standard for that. The root domain is ".", so the fully-qualified "pepsi" TLD would be "pepsi.". Technically the name of this site is "slashdot.org.", not just "slashdot.org".
Not ridiculous (Score:2)
At this point, the only thing ridiculous about it is the deadline.
There is already lack of "logical hierarchy" in full hostnames and their URLs. That hierarchy ended when people started buying multiple names in more than one com/net/org and ICANN didn't bat an eye, and it was further eroded when domains started using the "cute" country codes like "tv" without being even slightly related to those countries.
Since the TLDs are already meaningless, the gates might as well open all the way. It is truly har
Re: (Score:3)
It is truly harmless
How many people do you think will become phishing victims through pay.pal?
Re: (Score:2)
Given that they'd have to pony up $185 grand to start, they'd have to count on getting a LOT of money before some government starts impounding their web sites due to fraud.
The high price doesn't make scamming absolutely impossible, but it's not something you can do with a cheap rented botnet.
I'd like to think that when there's that much money on the line, ICANN isn't going to just tell everybody "caveat emptor" when a TLD is being used for a scam. That was an excuse they could use when a domain name cost fi
Re: (Score:2)
Yep. The
.com TLD has been the default ever since the beginning, and with the exception of .edu, all of the other TLDs are primarily for people who couldn't score the .com version (or those who do trying to keep people from duplicating it in another TLD.)
There's value in a curated TLD like
.edu, though only as long as people know that it's curated. The expense of scoring a vanity TLD will keep scammers out to at least a small degree. And maybe somebody will establish a well-known, well-curated additional TL
Re:Not ridiculous (Score:4, Interesting)
That hierarchy ended when people started buying multiple names in more than one com/net/org
The hierarchy was over when
.com was created. There was no reason not to use .co.us, .co.uk, etc - which would have retained a hierarchy.
.com domain for personal non-commercial use.
It was *completely* over when the first person registered a
Thanks for breaking many email address validators (Score:2)
Webmail:
To: [email protected]
ERROR! Invalid email address.
Re:Thanks for breaking many email address validato (Score:4, Insightful)
Re: (Score:2)
.morons (Score:2)
'nuff said.
Too late (Score:5, Insightful)
The hierarchy is already dead.
.com, .net and .org were supposed to have distinct uses. But they don't everyone goes for .com first and then grabs a .net or a .org if what they want is unavailable. The country codes were supposed to organize sites that were specific to certain countryies. instead they're used to make stupid domains like tw.it
ICANN's only criterion here on whether this is a good idea is whether it will generate lots more money in newly registered domains. Better grab your top level domain before someone squats on it and makes you look bad
Re: (Score:2)
The country codes were supposed to organize sites that were specific to certain countryies. instead they're used to make stupid domains like tw.it
Too bad single-letter names are impossible to register, or I could make a fortune on t.it.
Seriously though, shaving one character off a shortened URL is actually useful for Twitter (if you care about proper punctuation in a tweet, for example, and are hitting the 140 character limit).
ICANN's only criterion here on whether this is a good idea is whether it will generate lots more money in newly registered domains. Better grab your top level domain before someone squats on it and makes you look bad
You're dead on there. This is precisely how these domains are marketed to businesses by registrars.
Re: (Score:2)
But they don't everyone goes for
.com first and then grabs a .net or a .org if what they want is unavailable.
And this is the real issue, as far as I know
.com is now bigger than all the other domains combined and many, many of the other TLDs are bought only to stop squatters. Effectively we already have a flat namespace, if this wasn't such a money grab they could just say all dotcoms (of 3+ letters to not collide with country TLDs) are now TLDs and reassign all the .com DNS servers to TLD DNS servers. It's not like my grocery store has a .com or my university a .edu in the real world, why should they online? No,
Re: (Score:3)
Certainly true in the uk, and its own hierarchy is well used. Companies tend to sit on
.co.uk ie. The Guardian [guardian.co.uk] (although companies are the ones most likely to go elsewhere if needed), universities sit on .ac.uk i.e. University Of Manchester [manchester.ac.uk], health related sit on .nhs.uk i.e. NHS Direct [nhsdirect.nhs.uk], charities seem to sit on .org.uk i.e. The Mens Health Forum [menshealthforum.org.uk], and government websites sit on .gov.uk i.e.HRMC [hmrc.gov.uk]
True there are people who abuse it, but generally you can be assured that if you are on for example ac.uk, it real
Re: (Score:2)
They may be used for their original purpose, but they're not used exclusively for that purpose. With the
.com, .net, and .org suffixes being overcrowded, people have gone to country specific TLDs to find other options. A few years ago, websites started using the Western Samoan TLD (.ws) to mean "website". People have been using the Montenegro TLD (.me) as a vanity suffix. And this is in addition to the more clever uses that people have used, like the GP post mentioned with "tw.it".
So yes, it may be tha
Re: (Score:2)
They may be used for their original purpose, but they're not used exclusively for that purpose.
That depends entirely on the whim of the registrar, and each registrar is a law unto themselves. Some take money for old rope, others hold the line against the ravening hordes.
Georgia's gonna be pissed... (Score:3)
Yeah, Georgia is not going to be happy when they lose their entire country domain space to General Electric. GE has a market cap of something like 10X Georgia's GDP, so I assume it would be a slam dunk that the TLD be turned over to the rightful owner.
why the time limit? (Score:2)
if the tld's are to be sold only to entities holding global, dilution protected(nobody can use them, even for unrelated products, for example can't sell pepsi socks..) why is there a deadline on it? because they wanted to hurry up the registrations?
btw how much does it cost to buy one of these?did they make any limit on how many they're going to make of these? because there could be hundreds of thousands of trademarks which would qualify..
Re: (Score:3).
Evolution (Score:2)
At first, when you wanted to check out Pepsi, you had to guess & write: [pepsi.com]
And then browsers realized that non-http protocol became rare (gopher:// anyone?), so people could write:
And then people realized that "www" was superfluous, and so people could write:
pepsi.com
Now it is suggested that the
.com is superfluous in most cases, so people simply could write:
Re: (Score:3)
Now it is suggested that the
.com is superfluous in most cases, so people simply could write:
pepsi
You already can, in any sort of modern browser. No need to create a new TLD, it works today.
TLDs, search and your privacy (Score:2)
So I have a question: Google Chrome (and some other browsers) treats the address bar as a search bar. How will that work with new TLD's like "pepsi", does every search (for a single word) first get a DNS lookup, and then if fails, searched for at Google (which means all your personal searches leak to your ISP and any DNS server along the way), or do we include a whitelist of every new tld in the browser?
what a joke (Score:3)
Keep in mind the person that started all this was Eugene Kashpureff who ran around in the mid 1990s trying to sell brand name top level domains to big business. The powers that be thought this was a horrific idea and over the next 15 years captured the whole thing so a bunch of old white guys ran it then did the exact same thing, but it just costs 15X more an they get the money now.
If nothing else it serves as a great example of what happens when government takes over technology and all future technology need to keep this in mind so it can never happen again.
And keep in mind it was ISOC (the Internet Society) that handed this to the government while all along saying it was "for the good of the net" and never mind they made hundreds of millions by doing this.
Commerce doesn't like it (Score:2)
The Department of Commerce is putting ICANN's contract out for re-bid partially because they think this is a bad idea.
Personally, I think that not only is adding new TLDs bad, some of the old ones should be wound down. ".biz" is a bad neighborhood. Nobody can figure out what ".info" is for. ".aero" never took off. And the entire domain list for ".museum" is about five pages long.
logical (Score:2)
No, it's the logical conclusion of the Internet becoming commercial. When things are run for-profit than logic takes second place behind profit. Basically, if there's a buck to make, someone will do it, whatever "it" is. And in this case "it" is mutilating the DNS.
No reason I can think to put forth the effort (Score:2)
Cookies (Score:3)
I'm a little surprised how little I've seen so far on how difficult this makes security for browsers. Because most of the TLDs now are country codes such as
.uk, and those countries in turn have their own sub-TLDs suck as example.co.uk, browsers keep a list of which TLDS and sub-TLDs are real suffixes. This lets them know that mail.google.com can read/set cookies for google.com, but evil.co.uk can't read/set cookies for all of "co.uk", much less safe.co.uk.
As you may have guessed, this doesn't always work out properly. It's kind of a crap shoot with sites that use the country TLD directly, such as nhs.uk. With unlimited and variable TLDs, this implementation becomes even more questionable.
Does anybody know if browsers have gotten smarter about this in the past few years, or are we racing towards one of those security nightmares that forces content companies and standards bodies to actually get their acts together?
ICANN solution is backward (Score:5, Insightful)
The ICANN solution seems to use seemingly sound logic to conclude the exact opposite of what makes legal and practical sense. They require the new TLDs owners to be trademark holders. Instead, they should forbid them from being trademark holders. The word "apple" is trademarked by a consumer electronics company, a cruise company, a famous musician, various fruit growers, a bank, etc. So it does not make sense to give
.apple to Fiona Apple, Apple Vacations, Apple Computers, the Washington Apple grower's association, the New York Apple Country, Apple Federal Credit Union, or any other apple-related entity.
Intead, a 3rd-party should be able to hold
.apple, and license it for computers.apple, fiona.apple, vacations.apple, wa.growers.apple, ny.growers.apple, etc. That's how DNS was designed to work, how trademarks work, and it is completely fair. By giving .apple to Apple Computers it makes the DNS system a mix of hierarchy and non-hierarchy, while assigning one trademark holder special rights over another trademark holder. I foresee *lots* of new jobs for lawyers thanks to ICANN.
goodbye ICANN? TLDs not needed (Score:2)
It's already backwards... (Score:2)
"Does anyone else think this is absolutely ridiculous and defeats the logical hierarchy of current URLs?"
A logical hierachry would be com.example.www/somepage.html
Why they opted to make it a little endian scheme, I'll never understand.
I propose .icann (Score:2)
If they keep this shit up we can just re-root their entire namespace there and give the new root to some organization that's chartered with organizing things sensibly instead of maximizing profit.
Re: (Score:2)
I'm pretty sure the average person will sometimes be confused (like when you give them a
.name email address) and otherwise not give a damn.
Re: (Score:2)
Re:Only if you have pointy ears... (Score:5, Insightful)
Re: (Score:2)
It should also be done on the country code level: bank.nz, bank.uk, etc. Then asb.bank.nz and kiwibank.bank.nz / kiwi.bank.nz.
Also to force bank.us rather than
.bank in general.
Re: (Score:3, Insightful)
I think you mean 'seizing' instead of 'ceasing'.
You could not purchase a top level domain in the early days of the Internet.
By design, you want TLD's to be very rich. What's the point in owning a TLD if you can't afford reliable bandwidth, reliable, servers, etc?
More importantly, what's the tangible difference between and? Does Pepsi own sooooo many subdomains that it would actually help them to have their own TLD other than for marketing reasons?
This is the Internet. We need to thin
Famous trademarks (Score:2)
The only issue here is price, which makes it impossible to buy if you're not either very rich, or a big company.
As I understand it, brand TLDs are intended for trademarks that qualify as famous under dilution law [wikipedia.org]. If you're not a multinational company, you probably don't represent such brands.
Aaaah... how good it was at the beginning, when getting a new domain name up didn't cost a dime...
And then NetSol took it over and it cost $70 until the separation of registrar and registry allowed GANDI to jump in and establish the price expectations of the past decade.
Re: (Score:2)
Back when the euro was weaker (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
As I understand it, brand TLDs are intended for trademarks that qualify as famous
Does this mean that the brand becomes the registrar for that domain?
Because I was hoping to get coke.pepsi for my web site.
Re: (Score:3)
If you do not want USA to have control over your domain get one in a freedom loving country.
What "freedom loving country" would you suggest? no, this is not an attempt to troll, I'm seriously looking for one.
Re: (Score:2)
Somalia, land of anarcho-capitalism?
-l
Re: (Score:2)
Norway.
Hope you like the cold.
Re: (Score:2)
Re: (Score:2)
Switzerland where they ban architectural styles because of bigotry, and Iceland... I'm not sure it's safe to be male in Iceland.
Re: (Score:2)
Switzerland where they ban architectural styles because of bigotry, and Iceland... I'm not sure it's safe to be male in Iceland.
... and such is the consequence of real democracy. If most Swiss people don't want their country looking like some backward Muslim state then they can vote to have it banned. No "representatives" to decide that it isn't politically correct or take a bribe from that Saudis, direct democracy.
Re: (Score:3)
If you do not want USA to have control over your domain get one in a freedom loving country.
What "freedom loving country" would you suggest? no, this is not an attempt to troll, I'm seriously looking for one.
Finland [worldaudit.org]
Re: (Score:2)
What constitutes an entity?
Re: (Score:2)
It won't. DNS and ccTLDs is just one part of the bigger picture. The way the Internet backbones are currently interconnected and its operators being mostly under direct or indirect US jurisdiction, there are multiple ways for the US Government to censor sites them deem undesirable... on a global scale. For example, if the US wanted really hard to kill The Pirate Bay, all it needs to do i
|
https://tech.slashdot.org/story/12/04/12/1441200/icanns-brand-named-internet-suffix-application-deadline-looms?sdsrc=prev
|
CC-MAIN-2017-09
|
refinedweb
| 5,020 | 74.49 |
From: Daniel James (daniel_james_at_[hidden])
Date: 2008-06-17 18:23:28
On 17/06/2008, Igor R <boost.lists_at_[hidden]> wrote:
>
> I'd like to define hash_value() for some types defined in Boost, in
> order to use those types in hashed containers. It seems that the only
> way to do this is to define hash_value() in namespace boost, or the
> inner namespaces (where the desired type is defined) - isn't it?
You could create a new type that wraps the boost type in another
namespace, so that you can define hash_value in that namespace - but
that might be a lot of effort.
Or you could just use your own hash function.
> Is this legal?
It's a grey area ;). It's up to your judgement - I expect you
understand the issues. I don't think we should be too precious about
this. After all, boost is open source.
Also, please submit a feature request ticket using the boost trac:
|
https://lists.boost.org/boost-users/2008/06/37271.php
|
CC-MAIN-2020-16
|
refinedweb
| 160 | 83.36 |
annikaheflin577 Points
What's the answer and please explain
This problem doesn't make a whole lot of sense to me can you please help.
import random def random_item(arg): arg = [ 'life' 'love' 'live' 'learn' 'eat' 'pray' 'enjoy' 'happy']: randomization.len(arg) n = random.randict(1,len(arg)) return arg[n-1] # EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h"# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h"
1 Answer
Steven Parker194,132 Points
I left you a number of hints when you asked about this same challenge a couple of days ago. Perhaps the most important one is that you won't need to provide any data. Your function will need to use what is provided to it in "arg" so you don't want to overwrite it with a new assignment.
Another hint I gave before was that the "random" class has no "randict" property. You probably meant to use "randint" instead.
Then, there's two other issues:
- the line with "randomization" causes an undefined reference and doesn't seem to be part of the process
- the "return" line seems to be indented too far
One you take care of all these, you should be good to go.
|
https://teamtreehouse.com/community/whats-the-answer-and-please-explain
|
CC-MAIN-2020-24
|
refinedweb
| 214 | 70.33 |
A friend of mine was banging his head against the wall because this Groovy code.
Let’s explain very quickly what this does.
First, we create an empty map and then we define a key that is the result of a string interpolation. The key will be
"job-4".
Then we verify if the key is already on the map. If the map does not have the key, we add it with the value
1, and then we do the same again, but just this time the key will be on the map and nothing will change. The value for key
"job-4", should remain the same, that is value
1.
Let me tell you something, we are all wrong. The line
println(cache[key]) will in fact, print
2.
This is madness!!! so we looked at other languages to see if one of them behaves in the same way Groovy does.
In Ruby we do:
it prints out the value
1 as expected!
In JavaScript we do:
it prints out the value
1 as expected!
In Elixir we do:
it prints out the value
1 as expected!
In Scala we do:
it prints out the value
1 as expected!
What is wrong with Groovy!!!!???
The problem comes from the way Groovy manages dynamic typing and string interpolation.
When Groovy does the string interpolation, the resulting type is
GStringImpl which means the comparison is not in the way you expected. We need to force
GStringImpl to be a
String be doing
.toString().
If we only do:
def key = "job-${4}".toString()
everything starts working as expected.
Stop using Groovy!!!
|
https://hackernoon.com/what-is-wrong-with-groovy-482b7064f591
|
CC-MAIN-2020-45
|
refinedweb
| 269 | 84.78 |
Hi, I'm currently trying to do something which I thought would be relatively straightforward, but it appears not.
Basically, I have a set of data that needs to be done logarithmically in a histogram, but appears the 'log=True' command in the pylab.hist() only refers to the y axis, rather than the logging the bins and x axis like i hoped. So, i know i can manually log the x axis (with pylab.semilogx()), but I'm tried finding out how to do log bins. However this seemed to not be possible, so I'm now trying to find out how to put my own desired bins into it. There should be an easy way to this.
For example, if I have the following code:
import pylab
a=[0.1,0.3,0.5,0.5,0.7,0.7,0.9]
pylab.figure()
pylab.hist(a,bins=4,range=(0,1))
pylab.show
it gives me a graph with a value of 1 between 0.0-0.25, 1 for 0.25-0.5, 4 for 0.5-0.75 and 1 for 0.75-1.0.
however, if I want to split just the dense bin up further, into 0.5-0.625 and 0.625-0.75 (which will give me a value of 2 in each), how can I make the histograph plot this?
How can i tell it my desired range of bins is from:
0.0-0.25
0.25-0.5
0.5-0.625
0.625-0.75
0.75-1.0?
thanks for your help
|
https://www.daniweb.com/programming/software-development/threads/350524/how-do-i-manually-enter-bins-in-pylab-histogram-plot
|
CC-MAIN-2018-13
|
refinedweb
| 266 | 84.68 |
12606/extract-information-from-ethereum-blockchain-using-python
I am looking to do some analysis on the Ethereum blockchain, particularly, looking for correlations in the data between available hash power and transaction confirmation times.
However, I am unable to make sense of how to go about downloading either of the blockchains or extract the transaction and worker information from them. Ideally, I would download the blockchains, then use a python script to extract the relevant information from the blockchain to a CSV file or something like that? Any pointers on how this can be achieved?
Give the RPC (--rpc) option when you start the process. Make sure you have the entire blockchain.
The rpc starts a server process on localhost:8545. You can change the port as per your wish by --rpcport option.
Simply send HTTP Get requests (by CURL or some http module) to localhost:8545 and get the necessary info in JSON format. You can also use web3.js or web3.py APIs, which interface with the blockchain, basically execute on the console that is opened by the process.
You can do this by developing a ...READ MORE
There are two ways to actually do ...READ MORE
f I understand well, you're looking for ...READ MORE
Your need to improvise your code a ...READ MORE
This was a bug. They've fixed it. ...READ MORE
All you need to do is enter ...READ MORE
You are facing this error because you ...READ MORE
This should work:
#!/usr/bin/env python
import getpass
import json
import requests ...READ MORE
There is no android wallet to connect ...READ MORE
The spending conditions, i.e., who is able ...READ MORE
OR
|
https://www.edureka.co/community/12606/extract-information-from-ethereum-blockchain-using-python?show=12612
|
CC-MAIN-2019-35
|
refinedweb
| 281 | 78.04 |
Hi there,
I have a question about Function Builders and Generics:
The TL;DR is:
I have a function builder that is generic with type constraints. The builder simply collects a variadic number of elements of a related generic type into an array.
When I use the function builder, the generic type cannot be inferred even though I would assume that this was possible.
The smallest example I could find that demonstrates the issue is:
public protocol FieldProvider { associatedtype Field func value(for field: Field) -> String? } public enum TemplateItem<F: FieldProvider> { case staticText(String) case field(F.Field) } @_functionBuilder public class GenericFunctionBuilder<F: FieldProvider> { static func buildBlock(_ children: TemplateItem<F>...) -> [TemplateItem<F>] { children } } struct Generic<F: FieldProvider> { let items: [TemplateItem<F>] public init(items: [TemplateItem<F>]) { self.items = items } public init(@GenericFunctionBuilder<F> content: () -> [TemplateItem<F>]) { self.items = content() } } // Usage struct Business { enum Fields { case name } var name: String } extension Business: FieldProvider { typealias Field = Fields func value(for field: Business.Fields) -> String? { switch field { case .name: return name } } } func createUsingEnum() -> Generic<Business> { Generic(items: [ .staticText("Name"), .field(.name) ]) } func create() -> Generic<Business> { Generic { TemplateItem<Business>.staticText("Name") TemplateItem<Business>.field(.name) } }
As can be seen in
createUsingEnum() the generic type
Business can be inferred.
But in the function builder version
create(), the type cannot be inferred and I need to spell out the full generic type.
As far as I can tell, the compiler should have enough information to infer the type.
I have tried building with Swift 5.1, the latest 5.2 snapshot and latest master branch snapshot. All with similar results.
I am curious to hear whether it ought to be possible for the compiler to infer the type - full well knowing that function builders have not yet been officially accepted and added to the language.
Or might there be some logical fallacy in what I am attempting to do?
Note that the example above is abbreviated a bit - with my small proof-of-concept I would be able to use the small DSL like this:
let t: Template<Business> = Template { Text("Business") Field(.name) SubField(employees) { Text("Name") Field(.employeeName) } }
while with my troubles with automatic inference I have to write:
let t: Template<Business> = Template { Text("Business") as Template<Business>.Item Field(.name) as Template<Business>.Item SubField(employees) { Text("Name") as Template<Employee>.Item Field(.employeeName) as Template<Employee>.Item } as Template<Business>.Item }
|
https://forums.swift.org/t/generics-and-function-builders/33306/3
|
CC-MAIN-2020-24
|
refinedweb
| 401 | 50.53 |
example of a custom tableviewcell-alert-24') except AttributeError: pass return cell view = ui.TableView() view.data_source = source() view.present()
author: Omega0().
You can add subviews to the
content_viewattribute of an instance of
ui.TableViewCell. This is mentioned in the documentation but not directly, it only tells you that views can be added this way, not why you would do it. Also, Dann, for the author of the code above you could find the username of the poster. (I care only because I made it.)
I couldn't find the username. I had this snippet I'm my 'forum snippets' folder to learn from. I tried searching the forum posts for you. But couldn't :( sorry.
That's fine. It was a pretty quick code anyway.
@tachijuan Don't know if this helps you...
'Classes' - SettingsSheet
It's switches in a cell... but you could add labels and an image instead by the same method.
I think that will do it. Have a long flight tomorrow so I can play with this. Thanks for the help fellas. This is rather brute force, but works. Add a list of cells as a public property, and append the cells as they are created... see updated SettingsSheet class. A ui.View can be used like a dict of it's named subviews... but I think this little test script shows that a ui.TableViewCell doesn't support that... try it with View and then TableViewCell. It looks like subviews[n] is as good as it gets.
import ui v = ui.View() #v = ui.TableViewCell() b = ui.Button() b.name = 'btn' v.add_subview(b) print v['btn'].name
@techijuan Ok, the trick is to add the subviews to the cell's content_view not the cell... then it works to use content_view like a dict.
P.S. ListDataSource also has an (undocumented ?) tableview attributute that is useful for upwards navigation
aha!
Cool. Thank you!
|
https://forum.omz-software.com/topic/1132/example-of-a-custom-tableviewcell
|
CC-MAIN-2017-34
|
refinedweb
| 319 | 79.97 |
You can use the best practices listed here as a quick reference of what to keep in mind when building an application that uses Firestore in Datastore mode. If you are just starting out with Datastore mode, this page might not be the best place to start, because it does not teach you the basics of how to use Datastore mode. If you are a new user, we suggest that you start with Getting Started with Firestore in Datastore mode.
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 Datastore mode
- Avoid writing to an entity more than once per second. Writing at a sustained rate above that limit leads to time outs and results in slower overall performance of your application.
- 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 Datastore mode export file into Datastore mode Datastore mode 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
lookup()on that entity without needing to 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 and increased storage costs of index entries.
- Avoid having too many composite indexes. Excessive use of composite indexes could result in increased latency and increased storage costs of index entries. If you need to execute ad hoc queries on large datasets without previously defined indexes, use BigQuery.
- Do not index properties with monotonically increasing values (such as a
NOW()timestamp). Maintaining such an index could lead to hotspots that impact Datastore mode.
Designing for scale
Updates to an entity
A single entity in Datastore mode should not be updated too rapidly.
If you are using Datastore mode, design your application so that it will not need to update an entity more than once per second. If you update an entity too rapidly, then your Datastore mode writes will have higher latency, timeouts, and other types of error. This is known as contention.
Datastore mode write rates to a single entity can sometimes exceed the one per second limit so load tests might not show this problem.
High read/write rates to a narrow key range
Avoid high read or write rates to lexicographically close documents, or your application will experience contention errors. This issue is known as hotspotting, and your application can experience hotspotting if it does any of the following:
Creates new entities at a very high rate and allocates its own monotonically increasing IDs.
Datastore mode allocates keys using a scatter algorithm. You should not encounter hotspotting on writes if you create new entities using automatic entity ID allocation.
Creates new entities at a very high rate using the legacy sequential ID allocation policy.
Creates new entities at a high rate for a kind with few entities.
Creates new entities with an indexed and monotonically increasing property value, like a timestamp, at a very high rate.
Deletes entities from a kind at a high rate.
Writes to the database at a very high rate without gradually increasing traffic.
If you are using Datastore mode, you can get slow writes due to a hotspot if you have a sudden increase in the write rate to a small range of keys. Firestore in Datastore mode 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.
Hot spots can apply to key ranges used by both entity keys and indexes.
In some cases, a 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..
Ramping up traffic
Gradually ramp up traffic to new kinds or portions of the keyspace.
You should ramp up traffic to new kinds gradually in order to give Firestore in Datastore mode sufficient time to prepare for the increased traffic. We recommend a maximum of 500 operations per second to a new Datastore mode costs incurred.
Deletions
Avoid deleting large numbers of entities across a small range of keys.
Firestore in Datastore mode 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 Datastore mode to deal with hotspots.
You can use replication if you need to read a portion of the key range at a higher rate than Firestore in Datastore mode 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 Firestore in Datastore mode permits. Sharding breaks up an entity into smaller pieces.
|
https://cloud.google.com/datastore/docs/best-practices?hl=no
|
CC-MAIN-2020-16
|
refinedweb
| 896 | 61.56 |
[ ]
Advertising
Tony Przygienda commented on THRIFT-2945: ----------------------------------------- OK, rephrased in other points what I read a) we agree the trait is called serializable then b) I will check the README and extend it with namespace example and make sure everything conforms. I will add a simple example of custom trait (this default thingy) c) will look @ the service inheritance test d) We add Hash. Having said that: I discourage you from moving bask to HashSet. BTreeSet/Map can we range-walked which can be a very serious asset. e) I will look @ the format issue & fix `rust_safe_case` f) Understood your reasoning about the Rc<RefCell<Box<.. requirements and no, can't tell you anything better.Yes, you pay Rust for the glorious fact that you get thread-safe and memory safe compiled code and those semantics express this exactly. The performance is normally pretty decent, I find that cleanly written Rust with some optimization @ the end (look for clones ;-) runs faster than C++11 I normally write which is quite something but vtables in C++ and templates can become performance suckers quickly and the right hand moves are so complex to remember/understand that I end up copying tons stuff because trying to debug memory on complex C++11 is suicidal. What I did here in Rust I built a Cursor transport underneath and I serialize once & then just rewind and read the transport over and over again. De-serialization I need to construct the input protocol per incoming snippet since I want to pass those around (i.e. have multiple snippets in flight). That's a plan ? > Implement support for Rust language > ----------------------------------- > > Key: THRIFT-2945 > URL: > Project: Thrift > Issue Type: New Feature > Components: Rust - Compiler, Rust - Library > Reporter: Maksim Golov > Assignee: Allen George > Fix For: 0.11.0 > > > Work on implementing support for Rust is in progress: > by Simon Génier and myself. > It will probably take quite some time to complete. Please keep us updated if > there are changes related to our work. -- This message was sent by Atlassian JIRA (v6.3.15#6346)
|
https://www.mail-archive.com/[email protected]/msg34927.html
|
CC-MAIN-2017-22
|
refinedweb
| 345 | 60.55 |
The .NET MVC Framework – Part 2 – Testing Complex Routes and Controllers
This is part two of the series looking at the new .NET MVC framework. In the last post, I discussed a bit of background of the MVC framework, setting up routes, and creating the first new controller and view for the project.
Before I begin, I want to point out that I’m using Rhino Mocks 3.3. Works great so far—if you run into any issues with this code, please post up and let me know.
Testing Routes
Phil Haack, the Senior Program Manager for the ASP.NET team, has created a great blog post (and attached helper methods) for testing routes using Rhino Mocks. I highly suggest reading his post before proceeding.
I’m using his “MvcMockHelpers” and “TestHelper” classes—they’re fantastic and, maybe if we ask nicely, might find their way into the MSTest or Mvc framework itself.
After those two files are added into your project, add a new Unit Test template to your project. I’ll call mine, similar to Phil’s, RouteTests (I may not lose it or forget what it does if it’s called that. ;)).
Using the AssertRoute of Phil’s TestHelper class, we can quickly and easily see if the RouteTable we’ve specified is working.
[TestMethod]
public void CanMapNormalControllerAndDefaultActionRoute()
{
RouteCollection routes = new RouteCollection();
RouteManager.RegisterRoutes(routes);
TestHelper.AssertRoute(
routes,
new { controller = “home”, action = “index” });
}
AssertRoute, when used like this, has three parameters.
“routes” – passes the RouteCollection generated from our RouteManager—we could explicitly define additional routes if we wanted and inject them here.
“home” – the controller/view we want to render. It could just as easily say “galleries/view/12”.
new {} anonymous type – this is the expected RETURN of the assert; for this example, by using the specified route and calling “home”, we expect the MVC application to return the “home” controller and respond with the “index” action.
I’ve also taken the RouteCollection and RouteManager and pulled those two lines of code out into a “BuildDefaultRoutes” method. I can call that method when needed OR skip it and build my own when needed.
private RouteCollection BuildDefaultRoutes()
{
RouteCollection defaultRoutes = new RouteCollection();
RouteManager.RegisterRoutes(defaultRoutes);
return defaultRoutes;
}
Now, what about our Galleries/Show route, we want to verify that it’s a valid path.
[TestMethod]
public void CanMap_Galleries()
{
TestHelper.AssertRoute(BuildDefaultRoutes(), “galleries/show”,
new { controller = “galleries”, action = “show” });
}
Good deal, “galleries/show” will route to the controller and action I expect.
Now, what if I want to test something a bit more unique—I want to be able to handle the CURRENT urls that are being passed to the WebStorage gallery at.
~/WebStorageHandler.ashx?id=166&tb=false&type=Photo
The query string contains three important parts of information as we progress—the ID of the object in the database, whether or not to generate a thumbnail, and what type of object it is (so it knows how to handle the stream—something that needs fixed).
So, we can use our RoutesTest to build our test, have it fail, and then build the right route to make the test pass.
[TestMethod]
public void CanMap_OldWebStorageHandler()
{
// Develop our test using our new route.
TestHelper.AssertRoute(
BuildDefaultRoutes(),
“WebStorageHandler.ashx?id=166&tb=false&type=Photo”,
new {
controller = “galleries”,
action = “CatchHandler” });
}
In this test, we’re looking for that specific URL, and want it to forward it to the Show action on the Galleries controller and pass along the ID of 166 (since, by default, the URL routes read the query string if the parameters can’t be found in the path).
Now that our test is in there (and fails), what kind of route and controller action would we need to add?
routes.Add(new Route
{
Url = “WebStorageHandler.ashx”,
Defaults = new
{
controller = “galleries”,
action = “CatchHandler”
},
RouteHandler = typeof(MvcRouteHandler)
});
[ControllerAction]
public void CatchHandler(int id, bool? tb)
{
if (tb == true)
{
RedirectToAction(new
{
action = “ShowThumbnail”,
id = id
});
}
else
{
RedirectToAction(new
{
action = “Show”,
id = id
});
}
}
We can test the route, controller, and actions by prefabing two real URLs taken from the live Photo site:
WebStorageHandler.ashx?id=166&tb=false&type=Photo successfully redirects to /galleries/Show/166
and
WebStorageHandler.ashx?id=166&tb=true&type=Photo successfully redirects to /galleries/ShowThumbnail/166
Good deal!
Notice: I’ll be posting a follow-up later today that describes a current issue with mocking up these sorts of complex routes. If you attempt to pass query string parameters as your expectations, and your parameters are not EXACT within your route information, the test will fail. The follow-up will describe how to pull in the query string parameters.
This route intercepts anything looking for WebStorageHandler.ashx and forwards it on to the Galleries controller/CatchHandler action—passing along the rest as parameters.
Testing Controllers
Writing accurate Controller tests also has it’s
complications unique challenges with the MVC Framework. Phil has posted up his blog that the current breakage in Mocks should be fixed soon; however, the subclass techniques seem to be gaining popularity [ David Hayden’s post is interesting and has a good debate of comments on it as well].
To create the subclasses, create a new class and inherit from the base controller.
Here’s an example using the GalleriesController.
public class GalleriesControllerTester : GalleriesController
{
public string ActualViewName;
public string ActualMasterName;
public object ActualViewData;
public string RedirectToActionValues;
protected override void RenderView(string viewName,
string masterName, object viewData)
{
ActualViewName = viewName;
ActualMasterName = masterName;
ActualViewData = viewData;
}
protected override void RedirectToAction(object values)
{
RedirectToActionValues = values.ToString();
}
}
For now, and until later CTPs that allow me to mock these up (or at least use an interface/base class), I’m placing these in a separate class called ControllerTesters. That’s not necessary (I noticed David and Phil both placing theirs directly inside the {x}ControllerTest classes). So, you’ll need a {x}ControllerTester for every controller. 😦
[TestMethod]
public void CanViewGalleries_Show()
{
GalleriesControllerTester controller = new GalleriesControllerTester();
controller.Show(1);
Assert.AreEqual(“Show”, controller.ActualViewName);
}
So what does this tell us?
Using the Tester subclass, we can assert whether or not the .Show() action and resulting view match what we expect.
Conclusion
This covers creating unit tests for your routes, and your controllers/views; you might be wondering why I don’t have any testing of the models. Since unit testing LINQ-to-SQL isn’t specific to MVC, I’ll leave that out for now—there’s plenty of information on that out there.
- December 18, 2007 at 4:16 pmThe .NET MVC Framework - Part 2.1 - Mocking Query Strings in Routes « Ramblings of the Sleepy…
- December 19, 2007 at 4:27 pmThe .NET MVC Framework - Part 3 - Linking Models to Views and More! « Ramblings of the Sleepy…
|
https://tiredblogger.wordpress.com/2007/12/18/the-net-mvc-framework-part-2-testing-complex-routes-and-controllers/
|
CC-MAIN-2018-05
|
refinedweb
| 1,116 | 54.42 |
Biml Reverse Engineer a database, a.k.a. Biml to the rescue.
Maybe I didn't want all the tables. They have the ODS broken out by schemas to identify the data source and I only wanted the CMS data for this first draft. I run back through the Generate Scripts wizard this time only selecting tables in the CMS schema. That significantly reduced the number of objects I needed to script but still, it failed. And my mouse finger was tired. There had to be a better way.
Of late, Biml seems to be that better way. In just a few lines, I created a connection to my database, reverse engineered the targeted schema and then wrote the SQL out to files (so I could then import them with a database project). How cool is that?
inc_Connections.biml
I first added a biml file to my SSIS project that contained an OLE DB Connection Manager to the database I was interested in.
<Biml xmlns=""> <Connections> <OleDbConnection Name="ODS" ConnectionString="Data Source=localhost\DEV2014;Initial Catalog=ODS;Provider=SQLNCLI11.0;Integrated Security=SSPI;"/> </Connections> </Biml>
ExportTables.biml
Here's the "magic". There are three neat tricks in here.
<Biml xmlns=""> <#@ template tier="1" #> <#@ import namespace="Varigence.Biml.CoreLowerer.SchemaManagement" #> <#@ import namespace="System.IO" #> <# var schema = new List<string>{"CMS"}; var ODSCM = RootNode.OleDbConnections["ODS"]; var ODSDB = ODSCM.GetDatabaseSchema(schema, null, ImportOptions.None); string fileNameTemplate = @"C:\Users\fellowsb\Documents\ODSDB\{0}_{1}.sql"; string currentFileName = string.Empty; foreach (var table in ODSDB.TableNodes) { currentFileName = string.Format(fileNameTemplate, table.Schema.Name, table.Name); System.IO.File.WriteAllText(currentFileName, table.GetDropAndCreateDdl()); } #> </Biml>
TieringThe first neat thing is line 2. I have a directive that tells the biml compiler that this is a tier 1 file. I could have specified tier 3, tier 7, or tier 10, it really doesn't matter as long as this is greater than the value in inc_Connections.biml. Since I didn't specify a tier in that file, it's tier 0. I needed to use an explicit tier here because line 7 references an object in the RootNode (my connection manager) that won't be built until the connections file has been compiled. The take away for tiering: if you're objects in the Biml object tree, you might need to specify tiers to handle build dependencies.
GetDatabaseSchema
Cathrine Wilhelmsen (b|t) did an excellent job covering GetDatabaseSchema so I'll let you read her post and simply comment that this method allowed me to just reverse engineer the schema I was interested.
GetDropAndCreateDdl
The last bit of magic is GetDropAndCreateDdl. It's an extension method that allows me to take the in memory representation of the table and emit the TSQL required to create that object. I enumerate through my TableNodes collection and for each object, I call the GetDropAndCreateDdl method and dump that to a file.
|
http://billfellows.blogspot.com/2016/08/biml-reverse-engineer-database.html
|
CC-MAIN-2018-34
|
refinedweb
| 482 | 59.19 |
Building a website has become a complicated process over the years. Writing simple HTML, CSS and JavaScript is no longer the preferred method for the task, either because it’s too dull or too inefficient and error-prone. New tools like frameworks—or even whole new languages—have made the development process more dynamic and efficient. However, while the process has improved once the setup is working, the amount of work to get there in the first place can be tedious and overly complicated.
The most popular tool to coordinate multiple compilation processes and packaging of components into their distributable form is webpack, but the tedious process of configuring webpack is as infamous as the tool itself.
An alternative to webpack
Parcel comes to the rescue by making a bold claim: you can build your website with the technologies you love—including Babel, React, Vue.js, TypeScript, PostCSS, and PostHTML—without having to touch a hard-to-decipher configuration file again. It automatically understands the formats that you are using and puts everything together. Keep in mind, however, that this applies only to Parcel itself. In your project, you might still need to include some technology-specific files, for example, a .babelrc or a .postcssrc if you are using Babel or PostCSS, respectively.
However, true efficiency is more than just not requiring configuration to get started; it’s also about being fast in the development process. Parcel includes a development web server that allows to instantly see changes in the browser by using hot module replacement—what you change is automatically updated in the browser without reloading the page—and thanks to its multicore support, it can be up to twice as fast as webpack or browserify.
Getting Started: A Simple Static Website
It’s true that web applications occupy first place in overall complexity, but static websites remain a particular case. With a static website, all the complications tend to go into the setup instead of any programming that you might do, which most of the time is nonexistent. Parcel solves this problem more elegantly. Instead of preparing boilerplates with a lot of moving parts, we can just write our code in the languages we chose and start being productive.
Let’s see how a regular static site can be built that uses Pug as the templating language that compiles to HTML, PostCSS to transform the custom features that we choose in our CSS (postcss-type-scale and postcss-lh in this example) and Babel to write ES6+ that gets compiled to ES5 using the env preset.
In an empty directory, create a package.json file:
npm init -y
And install all the dependencies mentioned before:
npm install -D parcel-bundler postcss-type-scale postcss-lh autoprefixer babel-preset-env
Note that we don’t have to install Babel, PostCSS or Pug. They are provided by Parcel, and you just install the packages that are used with them.
Open the
package.json file and add the following scripts:
"scripts": { "start": "parcel src/index.pug", "build": "parcel build src/index.pug" }
Add the standard HTML boilerplate using Pug in a
layout.pug file:
doctype html html head meta(charset='utf-8') title Demo page link(rel='stylesheet' href='./styles/main.pcss') body block content script(src='./scripts/main.js')
Notice the path of the resources that we are using; Parcel picks up any path that starts with
./. Also, we include the extension of the source language that we are writing, as you can see in the
main.pcss which is a PostCSS file, instead of the regular CSS extension. After the compilation is finished, the paths are updated pointing to the appropriate files.
Then create an
index.pug with some simple content. Here,
layout is the path to the file we created previously (the extension is not mandatory in Pug):
extends layout block content h1 Hello
For the styles, let’s use PostCSS. We have included support for an lh unit and for simple font-size definitions, here is the content of
main.pcss:
@import './_variables.pcss'; :root { line-height: 1.5; font-size: var(--font-size); } h1 { font-size: 6; margin-bottom: 1lh; }
As in the Pug template, we can
@import other PostCSS files, and they get compiled and merged into a single file at the end. There is no need to add a PostCSS plugin to support imports.
In the
_variables.pcss file we can have something like this, as we are using the
--font-size variable in the main file:
:root { --font-size: 16px; }
Create the
.postcssrc file containing the two plugins mentioned before:
{ "plugins": { "postcss-type-scale": true, "postcss-lh": true, } }
Because we are not using any configuration in those plugins, we add the value of “true” to each key, and in case we need to adjust something we can add an object instead.
The last main component is JavaScript. We have decided to include our scripts written in ES6+ using Babel. The following is the content of the
main.js file:
import { appendTo } from './lib.js'; appendTo('h1', 'World!')
and in lib.js:
export function appendTo (tag, content) { const node = document.getElementsByTagName(tag)[0]; node.textContent += ' world!'; }
As in PostCSS, we have to include the Babel configuration file (
.babelrc) to indicate that we want to use the Env preset:
{ "presets": ["env"] }
Done. The is no need to indicate how we want to compile our files or anything like that. Just start the server to see the project working by running the
start command in the terminal:
npm start
In the end, you can get the plain HTML/CSS/JS to put your site online in any hosting provider, just run the
build command:
npm run build
You might be thinking that this sounds good for a simple static site, but what about complex projects where JS frameworks are involved? The good news is that the same process applies to most cases, including React or Vue.js. For example, let’s say you want to turn this project into a Vue.js application: all you have to do is to import the Vue.js component into your
main.js file (assuming there is a
div#app element in your Pug template and a Vue.js component called
App.vue already created):
import Vue from 'vue' // The Vue.js component import App from './App.vue' new Vue({ el: '#app', template: '<App/>', components: { App } })
The NPM commands that we have (
npm start and
npm run build) remain the same to run the server or to compile the distributable files, respectively. Parcel automatically detects the Vue.js component and makes the necessary transformations; there is no need to make any further adjustments. The only difference is when you want to work with a technology that is not yet supported by Parcel. In those cases you might need to do a bit of programming to integrate it yourself.
Customization: A Note for Edge-cases
If you like to experiment with languages and frameworks, there might be cases where your chosen technologies are not included in Parcel by default. In such situations, it’s usually just a matter of finding the right plugin for the job; a quick search in NPM for packages prefixed with
parcel-plugin- can give you an idea of the possibilities.
Also, regarding customization, Parcel has an API available that allows you to change the default behavior, to add extra functionality to the build process, or to integrate it into a larger system. You have a couple of options (available in the CLI as well) to change things like the output path and the minification process, or to execute code at certain events, or to use Parcel as middleware for Node.js in a framework like Express.
Final Words
Parcel keeps itself to the promise of zero configuration for most cases. It’s not only useful to pack everything for production, but also useful in the development phase to quickly write code in technologies that you like without having to worry about configuring everything by yourself. The included web server can be handy if the project is a client application or a simple static website. In this sense, you can imagine Parcel not only as a bundler but also as a development environment for the technologies that you love to use.
|
https://buttercms.com/blog/parcel-the-webpack-alternative-with-zero-configuration
|
CC-MAIN-2018-39
|
refinedweb
| 1,384 | 62.38 |
Red Hat Bugzilla – Bug 189088
Review Request: knemo Network monitor applet.
Last modified: 2012-12-04 18:37:17 EST
I do not have a sponsor for this. Both SRPM and RPM pass rpmlint with no errors, and I checked it against my previous submission. The only thing I'm not 100% on is %{_datadir}/*/*/*/* in the %files section.
knemo.spec:
SRPM URL:
Description:
A network monitor application for KDE. It's very similar to
windows Network monitor.
*** Bug 192524 has been marked as a duplicate of this bug. ***
Needs work:
* No downloadable source. Please give the full URL in the Source tag.
* Desktop file: vendor should be fedora (wiki: PackagingGuidelines#desktop)
* Desktop file: the Categories tag should contain Application and X-Fedora
(wiki: PackagingGuidelines#desktop)
* The translation files are not properly tagged, use the %find_lang macro
(wiki: Packaging/ReviewGuidelines)
* Scriptlets: missing "gtk-update-icon-cache" in %post and %postun (wiki:
ScriptletSnippets)
* Don't rm -rf $RPM_BUILD_ROOT in %prep, it breaks rpm -qi --short-circuit
* The "-n %{name}-%{version}" part in %setup is useless, it's already the
default
* export QTDIR=/usr/lib/qt-3.3/ should be replaced by:
unset QTDIR && . %{_sysconfdir}/profile.d/qt.sh
export QTLIB=${QTDIR}/lib QTINC=${QTDIR}/include
and it should be moved at the top of %build
* %configure should be moved in %build
* The BuildRoot must be cleaned at the beginning of %install
* Use make install, not make install-strip. RPM will strip the binaries by itself
* INSTALL is useless as a %doc, we're using RPM.
* %{_datadir}/*/*/*/* is a too generic, use %{_datadir}/icons/*/*/*/*.png
* The directory /usr/share/apps/knemo/ should be owned by the package
(In reply to comment #2)
> Needs work:
> * The directory /usr/share/apps/knemo/ should be owned by the package
>
And it should be /usr/share/knemo/ not /usr/share/apps/knemo/
Per default, KDE applications use the /usr/share/apps instead of /usr/share.
Ugly :) But it seems you'r correct, sorry mybad.
Oh my god, I shouldn't have done this, but...
SPEC:
SRPM:
(In reply to comment .
Please try to contact Richard June ([email protected]) and work together
with him on this..
* been there done that myself, search the f-e-l mailing list archives on
monkey-bubble
(In reply to comment .
I'm not trying to overtake the package. Like I said in the other bug, I made a
mistake and recognized that. But as I am exercising my package work, I made my
last available SPECS and SRPMS for the maintainer (Richard June) to use it (I
already did it before Aurelien duplicated my bug). Since my spec conforms with
many things noted by the reviewer, he can use it freely to learn and get this
package available in Extras on short-time.
> Please try to contact Richard June ([email protected]) and work
together
> with him on this.
I sent an e-mail to him early talking about this, asking him if he still wants
to maintain the package, and pointing my work so that if he wants to maintain,
he can use a more-correct specfile ;)
>.
It is a great idea, but if he wants to maintain the package and use my
specfile, he can do it and I will not want any credits for it :P Just think of
it as a replacement for my mistake (not looking in FE-NEW bug).
I'll wait an answer from him, and one more time: I am very sorry about this
issue! This won't happen again.
Hugo, just to make it clear: I understand your motives and it's nice of you to
help Richard with this package. Except, you're giving him a fish, instead of
teaching him how to fish.
About the *.la files, the ones directly in /usr/lib/*.la are safe to remove, but
the others are often needed by KDE.
Hi guys, I received an e-mail by Richard June regarding this issue:
Message was signed with unknown key 0x0B7A5FDA3258B581.
The validity of the signature cannot be verified.
Status: No public key to verify the signature
Actually, I'm not particularly interested in maintaining knemo.
I would happily concede maintainership to you
--
Chuck Norris is a hack. MacGyver could build a gun from a paperclip and shoot
Chuck Norris, then build a Stargate from a toaster and hide the body on some
planet with no food whatsoever for when Chuck Norris wakes up.
Public Key available Here:
Did I make your life better?
End of signed message
If you need other information I can forward the e-mail or ask him to send an
Now I can use my specfile for this review, I would be glad if someone can
review it to include quality software as soon as possible in Extras :) Thanks!
Needs work:
* Desktop files installed in %{_datadir}/applications/kde don't need the
"--vendor fedora" namespace, they already have kde (they are in the kde subdir).
* As a consequence, you don't need to rename them afterwards.
Notes:
* Why drop the keywords from the desktop file ?
(really) Minor:
* The Patch0 line and the "--add-category X-KDE-settings-network" are not
properly lined-up (tab instead of spaces)
Package updated:
Spec URL:
SRPM URL:
Changes:
- Removed vendor option from deskto-file-install (no renaming)
Notes:
> * Why drop the keywords from the desktop file ?
rpmbuild and desktop-file-install were complaining like hell about these
keywords, so I got it out :)
Review for release 3:
* RPM name is OK
* Source knemo-0.4.0.tar.bz2 is the same as upstream
* Builds fine in mock
* rpmlint looks OK
* File list looks OK
* Works fine
APPROVED
(In reply to comment #14)
> You'd best add:
> # /sbin/iwconfig
> BuildRequires: wireless-tools
> # /sbin/ifconfig
> BuildRequires: net-tools
Agreed, the detection is done at compile time, not run time. Thus if you don't
have them during the build, you won't be able to use them afterwards, even if
knemo only calls them and parses the output.
> As such, this pkg probably ought to
> Requires: kdebase
> The categories are already properly set, the only one you should add is
> --add-category=X-Fedora
Agreed.
> 4. unowned %{_datadir}/apps/knemo
I can't believe I missed that...
Thanks Rex.
Thanks Rex! I followed the tips in your review and created a new release. It
is now imported and built. Closing. Thanks Aurelien and all.
As I realized this too late, I imported and built (with Comment #14 changes)
before getting into FE-ACCEPT again (as in Comment #13). I hope a final review
returns good :-) And sorry for my little mistake.
Package updated:
Spec URL:
SRPM URL:
Changes:
- Created BuildRequires for the ifconfig and iwconfig commands,
as knemo utilizes it for monitoring.
- Removed addition of categories in desktop-file-install command
The changes are OK, APPROVED.
Ok, as I am not the original reporter of this bug, who can close it with
resolution NEXTRELEASE? I can't.
Package Change Request
======================
Package Name: knemo
Updated Fedora Owners: [email protected]
Hugo Cisneiros (the previous maintainer of this package) is AWOL. As per this
discussion on the f-e-l, I will be maintaining this package from now on:
An email was also sent by Hans de Goede (j. w. r. degoede <at> hhs (dot) nl) to
[email protected] on 2007-03-02 with the final list of Hugo's
packages' new owners; I can forward this if necessary.
Please change owners.list and the ACLs to reflect this change? Thanks!
|
https://bugzilla.redhat.com/show_bug.cgi?id=189088
|
CC-MAIN-2016-44
|
refinedweb
| 1,256 | 62.48 |
MY CHIEF
The Memoirs of
A d o l f H i t l e r ’s S e cr e t a ry
Introduction by Roger Moorhouse
He Was My Chief
The Memoirs of Adolf Hitler’s Secretary
Christa Schroeder
Introduction by Roger Moorhouse
Translation by Geoffrey Brooks
i ■
F R O N T L IN E
BOOKS
i ■
Original German edition:
Er war mein Chef: Aus dem Nachla.fi der Sekretarin von AdolfHitler
1985 by LangdenMiiller in der FA Herbig Verlagsbuchhandlung GmbH, Munich
First published in Great Britain in 2009
Reprinted in this format in 2012 by
Frondine Books
an imprint of
Pen & Sword Books Ltd
47 Church Street
Barnsley
South Yorkshire
S70 2AS
English translation copyright © Pen & Sword Books Ltd, 2009
Introduction © Roger Moorhouse, 2009
ISBN 978 1 84832 631 6
Er war mein Chef: Aus dem Nachlass der Sekretarin von AdolfHitler was first published
in German by LangdenMiiller in der FA Herbig Verlagsbuchhandlung GmbH,
Munich, in 1985. He Was My Chief is the first English language edition of the
text and includes a new introduction by Roger Moorhouse. Material relating to
the author’s internment and post-war relationship with Albert Zoller has been cut from
this edition but details of her trial have been retained. This period in the author’s life
has also been summarised in the introduction by Roger Moorhouse. Additional
material has been abridged due to copyright restrictions.
This is the first English language paperback edition..
Printed and bound in England
by CPI Group (UK) Ltd, Croydon, CR0 4YY
For a complete list ofPen & Sword titlesplease contact
PEN & SWORD BOOKS LIMITED
47 Church Street, Barnsley, South Yorkshire, S70 2AS, England
Website:
Contents
List of Illustrations
Introduction by Roger Moorhouse
Editor’s Introduction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vii
ix
XV
How I Became Hitler’s Secretary
The Rohm Putsch 1934
Hider’s Dictation and the Staircase Room
Travelling With Hider
Hider’s Birthday
The Polish Campaign
The French Campaign
The Russian Campaign 1941-1944
The Women Around Hider
Ada Klein
Gred Slezak
Eva Braun
Obersalzberg
The Berghof
The Order To Leave Berlin: My Leave-taking of Hider
The End at the Berghof
Appendix: Excerpt from Christa Schroeder’s interrogation
by Erich Albrecht, Berchtesgaden on 22 May 1945
Index
V
1
27
31
59
68
73
76
86
126
134
136
140
147
153
173
181
199
203
8. Christa Schroeder and Johanna Wolf at breakfast. 1940 Christa Schroeder at her typewriter at FHQ Wolfsschanze Christa Schroeder examining Hider’s world-globe in the Berghof‘Great Hall’ Hitler’s guests. Great Hall. Dr Stuckart and Christa Schroeder at the Hradschin. August 1943 . 1935 Goebbels. Dr Lammers. 9. Prague Christa Schroeder and Gerda Daranowski congratulate Hitler on his 50th birthday in the Reich Chancellery. 6. Berghof terrace. Berghof. Haus Wachenfeld. Hitler. New dear’s Eve 1940 Hitler dictating to Christa Schroeder at FHQ Wolfsschanze. 4. an adjutant. c. 7. 20 September 1942 Hider exercising his Alsatian Blondi in the open meadow east of the Wolfsschanze. 11. Dr Frick. 2. 10. 20 April 1939 Hitler’s personal physician Dr Theo Morell. New ^fear’s Eve. Christa Schroeder and Albert Speer waiting for Hider. Gerda Daranowski and Christa Schroeder with Hider at the Berghof.Illustrations 1. 1941 Hitler’s intimate staff in the officers’ mess at FHQ Wehrwolf near Winniza. 1938 Schaub. Wilhelm Bruckner. Eva Braun. 3. Karl Hanke. 5.
12. The Berghof . 15 July 1944 14-16. Rastenburg in East Prussia 13. The Wolfsschanze’s Fiihrerbunker. Hitler with his would-be assassin Claus von Stauffenberg.
she trained as a stenotypist before moving to Munich in 1930. The association thus forged would be a lasting one. compiled from contemporary notes and letters as well as postwar reminiscences. but also on military matters from the Polish campaign through to the final collapse of the Nazi regime. This memoir. She expounds not only on political developments such as the Rohm Purge of 1934 or the attempt on Hitler’s life in July 1944. right up the bitter end in 1945. Yet it is not primarily for her political insights that Schroeder is of interest. It gives the reader a fascinating insider’s viewpoint on many of the salient events of the Third Reich.Introduction S c h r o e d e r w a s a n ordinary woman cast into quite extraordinary times. Her experiences certainly ranged widely. Schroeder would be part of the Fiihrer’s entourage for the following twelve years.the SA. is Christa Schroeder’s own record of those extraordinary times. which she experienced from the comparative safety of Berchtesgaden. Born in 1908 in the pretty central German town of Hannoversch Miinden. Graduating to a position as Hitler’s personal secretary in 1933. she replied to an advertisement in the newspaper for a secretarial position at the headquarters of Hider’s stormtroopers . Whilst there. but there is a backbone to her book which is not concerned with grand politics C h r is t a .
hopes and fears . his vehement abstemiousness. she asked Hitler to his face if he still believed that the war could be won. For one thing. Schroeder knew Hitler as well as anyone and was extremely well placed to comment on his behaviour and personality. This lack of remorse is. so familiar to the modern reader. however. it seems that her candour almost became her undoing when she was ostracised by Hitler for a number of months after making the mistake of publicly contradicting him once too often. three-dimensional.benefactor.rather it gives an intimate view of the workings of Hitler’s household and of the various characters working therein. for example.a subject about which she claimed to have little knowledge or understanding . even his sense of humour.is fascinating. there is a refreshingly gossipy. Indeed. his mood swings. for all that. as it illuminates some of the foibles and idiosyncrasies of members of Hitler’s entourage. human being — with likes and dislikes. She details his bourgeois manners. Indeed. the ‘tone’ of her book is utterly unapologetic. . Indeed.INTRODUCTION . Hitler looms large in the book. chatty flavour to the book. Her description of Hitler is not of the wide-eyed fanatic. Schroeder was herself no shrinking violet. as well as addressing more substantial themes such as Hitler’s often difficult and mysterious relationships with women. a kisser of ladies’ hands. As secretary to the Fiihrer throughout the Third Reich. Yet. and often spoke rather too bluntly to her employer. of course. rather he appears as a generous . Schroeder’s is nonetheless a not unaffectionate portrait. In the winter of 1944.even avuncular . a man who chatted easily with his secretaries and had a passion for Bavarian apple cake. there is nothing. For all its gossipy revelations. there is a dark side to Schroeder’s story. In this regard. her presentation of the leader of the Third Reich as a rounded. Traudl Junge —who famously concluded that ‘we should have known’ about the horrors of the Third Reich. for instance. of the sense of perspective or mea culpa that one finds in the memoirs of Hitler’s other secretary.
describing the work as the . who was serving as a liaison officer with the US Seventh Army. too close perhaps to catch a glimpse of the ugly truth. As she complains in this book: ‘Whether my guilt was as great as my expiation is something I do not know to this day. As the logical corollary to this ignorance. ‘extremely critical’ and even ‘wounding’ in her ways. Nonetheless. thereby leaving litde or no ‘paper trail’. Schroeder would have argued that hers was a rather mechanical task largely restricted to the typing up of speeches and mundane daily correspondence. Schroeder found it difficult to imagine that she personally had done anything reprehensible. a consequence of Schroeder’s rather cantankerous character: even the editor of this volume.’ There were further grounds for her bitterness. After the war. Schroeder was if anything too close to Hider and the Nazi elite —too close to gain an objective view. too close to question the propaganda. One might legitimately ask how a secretary in the Reich Chancellery could have long remained ignorant of the Holocaust. The most sensitive of instructions. described her as ‘tough’. Confined in the rarefied atmosphere of Hitler’s ‘court’ —in the eye of the Nazi storm . Moreover. of course. would always have been transmitted in person. I think —to have known nothing of the horrors of the Nazi regime and of the crimes being committed in Germany’s name. or else couched in an impenetrable fog of euphemisms and double-speak. she was interrogated at length by Frenchman Albert Zoller. she was interned for three years after 1945. Yet. in 1949.Schroeder was effectively insulated from the grim realities of the world outside. This treatment evidently rankled.INTRODUCTION in part. for all her closeness to the epicentre of power in Hitler’s Germany. Anton Joachimsthaler. Yet there is more to it than that. Schroeder claimed —convincingly. classified by the Americans as a war criminal of the first order. Zoller typed up and embellished his interrogation notes and published them under his own name as Hitler Privat. in which such events were rarely mentioned.
But there may be another reason why Schroeder’s memoir was overlooked by British publishers in the 1980s. over two decades later. no royalty. soon after her death. History.that she had been given or had rescued from the ruins of the Third Reich. It may have something to do with Schroeder’s rather prickly and unrepentant nature. This is peculiar. and appended lists of errors and statements that. She would later complain that Zoller had also taken many of the material mementoes . she said. It may also be that such personal testimony was simply out of favour in the mid 1980s. to put an end to what she perceived as her exploitation and misrepresentation by a generation of historians and writers. Despite being a critical and commercial success. in German. especially if one bears in mind the reception accorded to the memoir of Hider’s other secretary —Traudl Junge’s Until the Final Hour —which was published to great acclaim in 2002. but . it seems.Hider’s sketches etc. Two years before its original publication. opinions and anecdotes that she had never given. what rankled most perhaps. and with the precise instructions that she left regarding how the memoir was to be prepared and published. of course. but with Schroeder receiving no credit and. had been falsely attributed to her. As a self-confessed ‘fanatic for truth’. was that she claimed that he had also appended her name to various comments. supposedly discovered in the GDR. given the injustice that she clearly felt. But. Schroeder’s book did not find an English language edition until the present volume.INTRODUCTION memoir of Hitler’s ‘secret secretary’. was at the height of its postmodernist spasm and was perhaps too busy finding obscure new perspectives and spurious grand narratives to bother too much with the simple memoirs of a simple secretary. the book had a hint of obsession about it. Understandably perhaps. however. aged seventy-six. Christa Schroeder’s memoir was published. in 1985. She waxed bitterly lyrical about Zoller’s perfidy. . the world had been stunned by the grand hoax of ‘The Hitler Diaries’. at that time. she was desperate to set the record straight.
and an illuminating. In the process. Roger Moorhouse. And. Though Christa Schroeder was perhaps not as insightful or perspicacious as the modern reader might have hoped. highly personal portrait of Hitler himself. moreover. such once-pressing concerns are now history themselves. of course.INTRODUCTION quickly demonstrated to have been crude forgeries. 2009 . It fully deserves its place in the canon of first-hand accounts of the rise and fall of the Third Reich. a number of historians. many of those same publishers recoiled when they were presented with any work that they considered to be even vaguely similar. publishers and newspapers were embarrassed. her memoir will certainly not disappoint. Her book is engagingly written and contains much of interest: from thumbnail sketches of the characters of Hitler’s entourage to an insider’s view of the great events of the day. And. historical tastes have shifted once again and memoirs and first-hand accounts are once more seen as being of particular value. Thankfully. not least because so few memoirists stood as close as she did to the very heart of the Third Reich. in the aftermath.
of herself and her own past. Sometimes she could be direct and wounding in her own way. Educated. often insecure and sensitive being within. always on the quest for truth and the meaning behind matters. uncommon in Germany. if I would escort a lady to meet him in Munich. suggests. but the rough exterior hid a nervous. Frau Schroeder was a fanatic for truth. xv . a former Luftwaffe newsreel correspondent attached to Fuhrer-HQ. her past and Hitler himself. the modern environment. musically gifted. As her first name. In a newspaper cutting which I found later in her papers she had underscored twice A fe w y e ars a g o 1 Christa Schroeder never married. she was no ordinary person and did not resort to cliche. she was also tough and extremely critical of people. Thus Frau Schroeder found in me somebody with whom she could converse about her life.Editor’s Introduction I was asked by Walter Frentz. and all women out of their teens are now accorded the prefix ‘Frau’ irrespective of their civil status. I was the author of many technical and historical works and was working at that time on a book about Hitler’s planned broad-gauge railway for Europe. In this way I chanced to know Frau1 Emilie Christine Schroeder. The practice of addressing women as ‘Fraulein’ or ‘Frau* depending on their marital status was current into the 1970s but has become discontinued in modern Germany as part of the process of female emancipation.
and so found herself tossed back and forth between Hitler.frequendy in the interests of a State —grows dim.’ She was a woman who looked at things critically. trim it. but basically could never come to terms with her own past. adding a marginal note: ‘This is the correct definition of Truth/ The truth is an amazing thing. but it never loses its breath. ‘Lies and deceit plough the soil of the world* is an old German proverb. But some day it reappears.’ reads an inscription over the portals of a patrician’s house: and we should remember the old saying. pronounced on them. Her relationship with the Nazi party She was not a National Socialist in the true sense. But you can’t kill it.e d it o r ’s in t r o d u c t io n in red the following passage. but we should never lose patience in waiting for Truth’s hour. the Nazi system. Eventually it always resurfaces. Whether that would actually be possible after twelve years close to Hitler is another matter. The lie will always be with us. one day somewhere it breaks through. for how many times is it stood on its head?’ Christa Schroeder wanted to get to the very roots of a thing. observed them. hide it. pluck the feathers from it and shake it to pieces. ‘The truth may sink. could analyze them. There are times when the truth . You can bend it. the friends and events of yesteryear. when it becomes a target for destruction. ‘The truth must have a thick skull. She often said: ‘If the job offer had been made to me in 1930 by the KPD and not the NSDAR perhaps I would have become a Communist. The same may be said for our private and business lives. she hated distortions. the consequences of the war and the cruelty of the extermination programme for the Jews. In her notes she stated: .
2 Univ. Charles Patterson Van Pelt Library.1945.5. interrogated her. She was rather stupid. Pennsylvania. When I expressed regret that my whole life. 22. “No. microfilm 46M-11FU US Army 101st Airborne Division. had been for nothing. nothing is wasted. I suppose I went a few times to the big assemblies in the Zirkus Krone. As I was a member of the Reich Leadership Section I never came into contact with the small centres and was only asked once or twice to take part in gatherings and suchlike. everything has a purpose. Frau Schroeder perhaps admits her inner turmoil.’ In her shorthand notes. Since I knew nothing of politics and did not want to lose my job I signed the application form and all was well. Counter-Intelligence Corps. . .’ Her letters and postwar notes In her note of 18 February 1979. the sporadic progress of her self-set task and her quest for truth: For years everybody has urged me to write down everything I know about Adolf Hider. all the years. An alternative view of her appears in the US Army intelligence report of 22 May 19452 in which it is reported that: ‘Mr Albrecht .e d it o r ’s in t r o d u c t io n After three months I was told that I had to join the Party since only NSDAP members could be employees.” He added that his wife had assured him so. Some time ago I began transcribing my shorthand notes from 1945. dumpy and an ardent Nazi. Frau Schroeder wrote of this event: ‘After the interrogation was over. It changed nothing in my life. he replied. but I felt nothing in common with the speakers or the masses and I must have appeared terribly stupid. Lt Albrecht brought me back to Hintersee and had a very friendly conversation with me. But instead of devoting myself to the task. and working industriously at it for two to three hours daily. .
intentions and prospects. because he had so many. It is simply impossible.e d it o r ’s in t r o d u c t io n I became aware repeatedly of the many layers of Hider’s character. then one can perceive the significance which the imponderables assumed in his life. It was my mistake to assume that I could unveil the ‘true face’ of Adolf Hitler. Hitler had the gift of a strange magnetic radiance. Everything to him was calculation and subtlety. and fascinated his conversation partners in a manner which defies description. preferably spending his time in bed. He weathered all dangers which threatened him. He had a sixth sense and a clairvoyance which was often decisive for him. She considered that in Hitler’s personality of many layers and pluralities the spectrum extended from extreme kindness and concerned attentiveness to ice-cold brutality. It plunged me into depression. but then proceeded with his life ‘in a certain capricious torpor’. observed in some mysterious way the secret reactions of the masses. the most prominent characteristics of the peculiar person who almost undermined the . These were. who constantly planned great things for tomorrow or the day after. In her copy of the disputed Zoller book mentioned at greater length below she corrected her copy of the text at pages 10-12 and left the following passage standing: For a long period he was the only string-puller behind all events which occurred in the Reich. I believe. If one reflects on the series of extraordinary strokes of luck which kept him safe during all the many attempts on his life. I was in that psychic condition which the Russian author Ivan Goncharov described in his 1859 novel about Ilya Ilyich Oblomov. He had the sensitivity of a medium and the magnetism of a hypnotist. To his death he played the role of the theatrical director. always exhausted and drunk thinking over his fine plans. and from which he concluded that Providence had selected him for his mission.
1904 Muhlhausen. but several Hitlers in one person.1904). When a servant appeared and whispered to her that her husband had arrived and was waiting for her downstairs. executed as war criminal).e d i t o r ’s i n t r o d u c t i o n basic foundations of the world. He was always inquisitive when something was whispered. Alsace. He was obliged to leave the Rastenburg FHQ and had not seen Hitler subsequently.1. which she took with Adolf Hitler. Hitler was unsure and at first could not look Dr Brandt in the eye. He was a mixture of lies and truth. At the beginning of March 1945 she .Anni . Shortly after the attempt on Hitler’s life in July 1944. of simplicity and luxury. She asked her friend Anni Brandt for her impression: This morning Anni Brandt3 confirmed it to me. the simplest way was to whisper about the matter to a neighbour and one could rest assured that Hitler would enquire.3.was invited by Eva Braun to tea at the Reich Chancellery. and Speer had him freed. one child: taken into US custody April 1945. of kindliness and brutality. 4 SS-Gruppenfuhrer Dr (med. On 17 April 1945 he was condemned to death by court martial but was still at Kiel awaiting execution when Hider’s death was announced. of mysticism and reality. Dr Karl Brandt was sent packing. 1928 Olympic Games Amsterdam.1945.6. Now Hider sent for him. Hitler wanted to know what had been said. d. and if one wanted to arouse his interest in anything. and sending his wife and child to Bad Liebenstein so that they would fall next day into American and not Russian hands. introduced to Hider 1925 and from then until 1945 part of his intimate circle at the Berghof. of faithfulness and violence.) Karl Brandt (b. but then began to converse with him as they used to do in the past. There was not just one Hitler. of the artist and the barbarian. German Ladies’ national swimming champion (crawl and backstroke) during 1923-9 period. Married surgeon Dr Karl Brandt 17.8. 2. All the more incomprehensible for me was it therefore when only weeks later Hitler sentenced him to death. 8.4 Thus it is 3 Anni Brandt nee Rehborn (b. Dr Brandt was arrested by the SS on 16 April 1945 for defeatism after sending Hider a letter on 1 April 1945 expressing doubt in final victory. xix . Langenberg 25.1948 Landsberg Prison.
By the year of her death. in reply to my question. she had cast 95 per cent of her shorthand notes into typed folios of 162 pages for a manuscript. At this juncture I would like to thank the shorthand historian Herr Georg Schmidpeter who transcribed those stenographic notes not already typed up by Frau Schroeder. They were taken down in Stolze-Schrey shorthand and not. ‘What was the boss. Professor Brandt. a good or evil man?’ should answer spontaneously. How I saw everything then . in the larger circle at the Berghof at mealtimes or at midnight around the fireplace: and later during the war in the Fiihrer-HQs at tea after the nighdy military situation conferences. observations and slips of paper with jottings noted down as items were remembered or on which she was working currently. Frau Schroeder worked only sporadically at her notes. p. ‘He was a devil! Frau Schroeder concluded: Thirty-three years have now passed since then. The old book contained her shorthand notes made during the period of her internment postwar. 15 May 1983. The last entries are dated August 1948. She had a hackneyed book marked ‘Shorthand Exercises’ on the cover and a lever arch file for manuscripts. XX . I was never a person interested in politics. as Quic\ magazine (Issue 19. in his personal presence at the evening tea sessions in the ‘staircase room’ of the Radziwill Palace. Besides these she had many other notes. It was only Hitler as a man who interested me then: what I experienced of him under dictation. Some of these pages date from the 1976—84 period and do not appear in the shorthand notes.that is what I want to write about. 156) alleged. while amongst the doctors being transported to Belgium for war crimes trials. ‘in a secret script which only Frau Schroeder could read’. 1984.e d it o r ’s in t r o d u c t io n understandable that at Ludwigsburg.
a French liaison officer to the US 7th Army.e d i t o r ’s in t r o d u c t io n The genesis of the Zoller Book In the first days of her confinement at the US Army Internment Camp Augsburg in May 1945. Parts of the text foreign to her notes had been interpolated. such as photographer Heinrich Hoffmann or adjutant Julius Schaub or others whom Zoller had also interrogated. The German version was a re-translation from French of the original German draft. He asked her to write down everything she knew about Hitler. Diisseldorf. In 1949 the book was published using Zoller’s name as author. and so on. but had allowed Zoller to appear as author with her full agreement. She did not dispute the veracity of what was alleged in these statements. under the tide Hitler privat — Erlebnisbericht seiner Geheimsekretarin. She recognized at once that the falsely attributed statements must have been made by prominent arrestees at the Augsburg Internment Camp. Frau Schroeder was interrogated by Albert Zoller. The original language was French with a translation into German. She was supplied with some limited manuscript material to the book but when Zoller failed to produce the entire manuscript despite repeated requests she refused him permission to use her name as author. or of conversations at military situation conferences which she never attended. this resulting in frequent shifts ofmeaning. In 1949 after her release Zoller informed Frau Schroeder that he intended to publish her notes under her name. only that she disputed having spoken or written them herself . the result being published by Droste Verlag. Statements were attributed to Frau Schroeder regarding military-technical matters of which she had no knowledge. the circumstances of Hitler’s life and events during the Nazi period. The Foreword depicted the person and activity of the ‘Secret Secretary’ in such a manner as to make it seem that Frau Schroeder was author of the book.
’ It was moreover self-evident that no Party member. Frau Schroeder concluded.e d it o r ’s in t r o d u c t io n Frau Schroeder worked through a copy of Zoller’s book striking out all passages which did not originate from herself. ‘seems absolutely credible. In front of witnesses he would never have admitted the inhuman harshness of the orders he had given. and then to deny it. To my surprise he defended himself with the assurance that he was only carrying out Hider’s orders.11. I assume full responsibility. In a letter dated 21. would have dared to have undertaken such far-reaching measures without Hitler’s agreement.‘If in military situation conferences the conversation turned to rumours about the mass murders and torture in the concentration camps.1972 to Frau Christian she explained: It is interesting how Zoller put words in my mouth which are mythical and in reality must have originated from his confidential conversations with General Staff officers which he obtained in his capacity as an interrogation officer. Only seldom would he respond. or brusquely halt the talk. Here is an example. ‘The foregoing’. He writes .. It was quite improper for him to have used these as material for a private publication. and it originates. She claimed 160 to 170 pages as her own work and 68 to 78 pages as from other sources. or as being individual passages re-worded or given a different slant by Zoller. from somebody present at the military situation conferences who did not . no SS-Fiihrer no matter how influential. One day some generals asked Himmler about the atrocities in Poland. and can only have originated.. Hitler would refuse to speak. But he added immediately: ‘The person of the Fiihrer must under no circumstances be mentioned in that connection.puts into my mouth . His crafty solution was to put these statements into the mouth of ‘the Secret Secretary’ where to the outsider and uninformed they appear credible.
A few days later she telephoned and asked me to drop by. Henriette von Schirach and so on. she had no special wants and was content with what she had. She also tired very quickly. she raised the matter of the notes again. Krause. This surprised me.e d it o r ’s in t r o d u c t io n want to be named.’ My own involvement begins In 1982 Frau Schroeder asked me if I wanted to publish her notes with my own commentaries. von Below. Once Frau Schroeder returned from hospital after the removal of a carcinoma. That remained the position until her death although there was no shortage of offers. I knew of her bad experience with the Zoller book and that she did not want the notes published in her lifetime. Another of her reasons for having delayed publication was that no sooner were memoirs published than they would be pulled to pieces by contemporaries. She had no interest in selling the notes. Frau Schroeder wanted no remuneration for the notes. however. and of my compiling them together with a commentary. After explaining that she was to be re-admitted to hospital she gave me a large. As far as she was concerned that was an end to it. and so the “Secret Secretary” said it. On her return by ambulance she was clearly seriously ill. She was anxious that under no circumstances ‘should her entire literary estate fall into the hands . old black trunk containing her literary bequest. The day before she left for the Schlossberg Clinic at Oberstaufen she invited me to call and we spoke in detail about the publication of her notes in the presence of the female friend with whom she was to travel on the morrow. emphasizing repeatedly that her pension was sufficient. She declined money or reward in kind. Hoffmann. At the time she could not flex her fingers and had difficulty in typing. a sin of which she was of course guilty herself with respect to the books of Linge. When I failed to reply promptly to her enquiry the matter was dropped for a considerable period. I do not think you could get more crafty than that.
If the book does not always appear to flow smoothly. She remained there until 20 February 1930 when she left for Munich in search of a better position and to advance her career. The mother was a single parent with a very strong personality who failed to provide her daughter with the warmth and affection she probably craved. In this period of the Great Depression. Complying with her wish that her notes should be published after her death. Her relationship with her mother was not close. where she was employed as the sole legal secretary to an attorney. C. She often took part in shorthand competitions and not infrequently would emerge with first prize. completing her training on 1 April 1925. leaving her orphaned and alone. and recognizing that they contained much interesting material. Meanwhile she also attended the Commercial Career and Business School.F. Who was Christa Schroeder? Emilie Christine Schroeder was born on 19 March 1908 in Hannoversch Miinden. in her home town. and continued working thereafter for the Schroeder firm as a shorthand typist until 19 July 1929. In October 1929 she left Hannoversch Miinden for Nagold.’ and I should remember what she had always said and wanted. She had a great talent for shorthand writing which she continued to develop by intensive continuation training and courses. the reason is that it was necessary to use incomplete pages of manuscript and single detail notes just as Christa Schroeder prepared them and wanted them published. Wiirttemberg. The mother died in 1926 when Christa was 18. Germany had almost 7 million xxiv . Schroeder Schmiergelwerke KG. or no matter who.e d it o r ’s in t r o d u c t io n of journalists. I arranged them in order and supplied the commentary. After completing secondary education on 11 April 1922 she began a three-year commercial training course at a firm owned by distant relatives.
Frau Schroeder went to Berlin with them at her own request because she was feeling the heat from the Gestapo over her alleged friendship with a Jew the previous year.9.6then Hider’s chief adjutant. 6 Oberst Wilhelm Bruckner (b. Early on the Adjutancy consisted of eight or so persons and served as a liaison and communications centre for journeys. and in Munich it was not easy to find a position.12.1884 Baden-Baden. Although further parts of the premises front and back continued to be rented. later it expanded to accommodate the military. various NSDAP Staffs removed to Berlin on 4 March 1933. 18. 1918 oberleutnant. rejoined army in rank of major.1948. 1925-8 active as sports trainer.1944 oberst: 4. 1919 Reichswehr and Freikprps Epp. Munich. the needs of the Party administration soon outgrew them. the NSDAP was reconstituted on 17 February 1925 in a single room at the premises of a publisher at Thierschstrasse 15. 1. She took up her post in March 1930 and worked in various departments there until 1933. 11.e d it o r ’s in t r o d u c t io n unemployed. 1. described her as follows: 5 Following Hitler’s release from Landsberg Prison.10. the setting of agendas.9. xxv . and responded to newspaper advertisements including one inserted by the NSDAP (Nazi Party) Reich Leadership at Schellingstrasse 50.1954 Herbstdorf.12. Wilhelm Bruckner. on 4 June 1925 several rooms were rented in a building at the rear of Schellingstrasse 50. She was in the entourage on all journeys and active at all Fiihrer-HQs (FHQs). She applied to many companies.5 She was selected from amongst 87 applicants for her outstanding skill and ability. Traunstein). A short while later while helping out at the Reich Chancellery she came to the attention of Hider and was transferred into the ‘Personal Adjutancy of the Fiihrer’.5.7.8.1933 SA-Gruppenfuhrer. First World War military service France and Romania. arranging receptions and so forth.1932 SA-Oberfuhrer. 18.1940 dismissed by Hider.3. served in France: 1. After the election to power of Adolf Hider on 30 January 1933. As this room was soon inadequate for the membership. chief adjutant.1934 SA-Obergruppenfuhrer. Frau Schroeder worked at the Reich Chancellery until the outbreak of war in 1939 and was then more mobile as one of Hider’s secretaries.1930 Hider’s adjutant. 1.8. d. 1. 1922 SA-Fiihrer (Munich Regt): involved in failed putsch 1924.1945 while hospitalised for a wound at Traunstein interned by US Army: released 22.
e d i t o r ’s i n t r o d u c t i o n I have known Fraulein Schroeder since 1930. Dr Karl Brandt described Frau Schroeder during his interrogation at the Nuremberg War Crimes Tribunal: She is a woman who speaks her mind.6. Left Berlin on Hider’s order 21. 1933 transferred to Berlin with Hider’s Chancellery and attached to Personal Adjutancy as Hider’s personal secretary. xxvi . social graces and circumspection she proved herself particularly on journeys and in the various FHQs. In all these positions absolute confidentiality . from 1930 secretary to Hider’s adjutant Wilhelm Bruckner.1945. 5. critical and intelligent. opposed to Frau Schroeder’s negotiations with Zoller. she was appointed secretary to Adolf Hitler.4. Fraulein Schroeder fulfilled completely all expectations made of her through her unfaltering devotion to duty. Christa Schroeder was a different kind of person from Fraulein Wolf. then worked for the head of the Economics Division. her abilities linked to fast comprehension and her independent collaboration when taking dictation.1945. Hider always protected her against efforts to have her replaced.1985 Munich). 5. 23. Through her tact. Schroeder had a turnover of work which no other secretary ever matched. 1929 employed by Hider’s private chancellery. She could often spend several days and nights almost without a break taking dictation.1929 joined NSDAP.7At the beginning of the war this pair alone handled all Hider’s secretarial business. 1923 private secretary to Hitler’s mentor Dietrich Eckart. 1922-8 secretary to Landtag ‘Volkischer Block* deputy Dr Alexander Glaser. 1.1.1948.particularly in the latter . 1. Was often unwell and did not stand flights and road journeys well. secretary to Rudolf Hess. released 14.1928 secretary to Gregor Strasser. interned. From then until about 1933 she was a secretary in the Reich Directorate of the Supreme SA Command (OSAF).was essential. In 1933 she transferred from Munich to Berlin with the Liaison Staff. Recommended for her great ability and social graces she arrived eventually in the Fiihrer’s Adjutancy as my secretary. d.1900 Munich. She would 7 Johanna Wolf (b. Clever. arrested by US forces at Bad Tolz.5. For her typing and shorthand abilities. and her talent for independent working.11.6.
Nothing else was alleged. On 24 October 1947 she was accused of being a Group 1 Hauptschuldige. The war guilt of the shorthand typist After the collapse of the Third Reich Frau Schroeder was arrested by the US Army Counter-Intelligence Corps (CIC) on 28 May 1945 at Hintersee near Berchtesgaden and interned at various camps and prisons by the occupying Powers.000 marks) and that ‘the consequences of Article 15 are to apply for the next ten years. or Hitler kept her out of it deliberately because he could not tolerate her criticisms. to the forfeiture of all her goods and possessions (5. On 7 May 1948 after the review hearing it was held that: XXVll . By doing so her boldness undoubtedly put her life in grave danger. She held herself apart from the private circle. and this led on occasion to serious altercations. On 13 February 1947 the judicial tribunal of Internment Camp 77 at Ludwigsburg served an arrest order on Frau Schroeder and she was brought before the tribunal for a preliminary hearing next day. a war criminal of the principal group. The indictment specified that Frau Schroeder had been Hider’s shorthand typist and had received from him a gold badge for efficient service.’ On 20 April 1948 the Ministry for Political Freedom of Wurttemberg-Baden overturned this verdict on the grounds that ‘the classification of the accused as a major war criminal is based upon an error in law’. At the full hearing on 8 December 1947 she was convicted of being a Group 1 major war criminal on the facts cited in the specification and was sentenced to three years’ labour camp. As Fraulein Schroeder’s intentions were completely honest this hurt her to the quick and as time went on she became sharply critical of Hitler himself. and referred the matter back to the tribunal.e d it o r ’s in t r o d u c t io n always express her opinion openly and with conviction.
.. then I xxviii . There she accepted employment on 1 November 1959 with a property insurer in a managerial capacity. critical... She was highly paid only for her outstanding talent and great competence as a shorthand typist. she returned to Munich. On 26 June 1967 at age 59 and in ailing health she retired and lived a secluded life in Munich until her death on 28 June 1984. willing to help. I have the ability to rapidly size up a situation. has already spent a long period in custody and has thus expiated sufficiendy. As regards her obligation to expiate her activity. Her work was wholly mechanical. In a memorandum About Myself’ she wrote: I am attentive.’ In civilian life from 1 August 1948 until 1 November 1958 she worked as a private secretary to Herr Schenk. judgmental. however.e d i t o r ’ s in t r o d u c t i o n . from the beginning to the end she was employed as a shorthand typist. the owner of a light metal works at Schwabisch Gmiind and then at its Maulbrunn main plant until 31 October 1959 after which. About herself It is interesting to observe how Frau Schroeder saw herself in the last years of her life. as in 1930. it is taken into consideration that she was bombed out of her home and is penniless. Frau Schroeder was reclassified as a Group IV Mitlauferin (collaborator) and released from detention at Ludwigsburg on 12 May 1948. she lacked any kind of independent organized authority and at best can only have exercised the least possible influence on the direction of events. If I do. and the gift of intuition. I seldom find a person to be nice. the accused can under no circumstances be considered a Group 1 war criminal. She concluded: Whether my guilt was as great as my expiation is something I do not know to this day. From a person’s face and mannerisms I am able to read much about his character.
’ Frau Schroeder then suggested that the secretary could leave the employment to which Hider replied: ‘I would know how to prevent that.e d it o r ’s in t r o d u c t io n jump across all barriers. She described the situation in a letter from the Berghof to her friend Johanna Nusser8 on 22 February 1941. I despise people who are materialist. who have no opinions of their own but adopt the views of others. The latter are now at the Institut fur Zeitgeschichte. how would you feel if one of your secretaries wanted to marry a Yugoslav?’ Hitler answered: ‘There would be no question of it. who lie. At the beginning of 1939 she asked Hitler: ‘Mein Fiihrer. she never was to find the tranquillity of existence a woman would wish for. In 1938. She spoke on her behalf at the war crimes tribunal hearing and helped Frau Schroeder after her release in 1948. This tragic aspect of her life probably left its mark on her. who need to dominate others. xxix . Unfortunately! My capacity for criticism is coupled to an irresistible urge for truth and independence. who are conventional. After references to his ‘contact in the Reich Chancellery in Berlin’ the Gestapo took an interest and interrogated Frau Schroeder.’ Alkonic had contacts within Yugoslav officers’ circles and was later involved in shady business dealings in Belgrade.the life a young woman imagines for herself After a less than enjoyable youth. who prejudge and are never prepared to reflect upon everything which has led to this point. During her time as Hider’s secretary Christa Schroeder never knew a private life . Frau Schroeder became engaged to Yugoslav diplomat Lav Alkonic although she knew that this could have consequences with Hider who would never have given his blessing to such a liaison. I despise people who are self-important. In the 1950s Frau Nusser returned a batch of letters written to her by Schroeder during the war and allowed her to pass another batch to the historian David Irving. Frau Schroeder stated that the ‘suspicion’ had arisen following the interception by the Vienna censor of a letter 8 Johanna Nusser was a long-term friend of Frau Schroeder with whom she maintained an intimate correspondence during the war.
‘You understand what I mean by that. however. The engagement was broken off in 1941. Only limited areas of free movement existed in the Reich Chancellery. one cannot avoid seeing that for Frau Schroeder the years alongside Hitler were years lost. gave me this advice. don’t you?’ he said. that in her heart she was never happy to be there. In any case. She saw continuously the same people and XXX . I hope the OKW is satisfied with my statement. Consul-General von Neuhausen of Belgrade. everybody does it. The Gestapo man then interposed' that Lav was mentioning his ‘contact in the Reich Chancellery’ when calling on German firms. Life for Christa Schroeder in proximity to Hitler was marked by the need for her constant presence and compliance with the regulations for State protocol laid down by Hitler. I said. As an individual human fate. He also believed that Lav was working with the Yugoslav General Staff. I wouldn’t want them to go delving any further into the matter. he had been involved in some dubious business affairs which had not been very fair. and her health was seriously affected by living in damp and musty bunker rooms at FHQ and later in Allied internment. at the Berghof or in the various FHQs. for the people in the prisons and concentrations camps of the Nazi system: and that these people suffered more than a secretary of Hitler. It may be interjected here that there was also no fulfilment in life for the 55 million or so victims of the Second World War. one shouldn’t take it too seriously. whom I met in the former Rothschild Palace at the invitation of General Hanesse.e d it o r ’s in t r o d u c t io n from a. As a result ofthe foregoing we cannot write to him again —at least not until the war is over. and she had seen no alternative but to tell the Gestapo the truth. But certainly it was just one fate amongst millions of others.certain Djuksic. How much truth there is in that is hard to tell. Neuhausen did not think much of Lav.
these were for me 15 years cloistered away from a normal. 7. Depending on his mood when the evening ‘tea hour’ began. interned 23. within the enclosure of the FHQ —described by Generaloberst Jodi9 at Nuremberg postwar as ‘a cross between a monastery and a concentration camp’. xxxi . which makes one feel trapped. On 30 August 1941 she wrote to her friend Johanna Nusser from FHQ Wolfsschanze.8. I believe that after this campaign I should make the effort to make contacts with life-affirming people beyond our circle.9. especially during the war years in the various FHQs.10. for otherwise I shall become withdrawn and lose contact with real life. d. As Hitler’s chief of staff advised him on tactical and strategic matters.5.1945 Miirwik. three of them with the Supreme SA leadership (OSAF) and its Economics Department. Rastenburg in East Prussia: Here in the compound we come up eternally against sentries.5.1946 sentenced to death as war criminal.1946 executed Spandau). Rheims. and twelve years in the personal adjutant of the Fiihrer and Reich Chancellor.1890 Wurzburg.5. A life behind defences and guarded barbed wire fences.1945 Wehrmacht signatory to partial capitulation to Western Allies. civilized existence. Walking inside the 9 Generaloberst der Artillerie Alfred Jodi (b. Christa Schroeder summarized her unhappy existence: 15 years of service.1939 Chief of Wehrmacht Policy Office (later Wehrmacht Policy Staff) at FHQ.e d it o r ’s in t r o d u c t io n the same faces of the entourage with whom she was obliged to co exist day in. 16. this being shut away from the rest of the world. became etched in my consciousness. 10. From 23. 30. he would deliver to his captive audience his endless monologues into the early hours. eternally have to show our identity papers. in between a couple of weeks break with the Reich Leadership ofthe Hider \buth. Lacking regulated duties or a service schedule she formed part of Hitler’s most intimate circle which served him as a kind of substitute family. day out. Some time ago this sense of being hemmed in. everyday.
that on the night of 20 April 1945 in company with my old colleague Johanna Wolf. all the instincts of struggle in one’s personality remained underdeveloped. Heinrich Heim: Adolf Hider. 1941—1944. Monologe im FHQ.e d it o r ’s in t r o d u c t io n fence. In that there lies a great danger and a powerful dilemma from which one longs to be free but then. both now and when the past was still the present It does so today to a much harsher degree!’ Anton Joachimsthaler Munich. After the war she concluded: Belonging to Hider’s intimate Staf£ always treated as persona grata. My past has demanded much of me.1942 at FHQ Wolfsschanze. Hider’s Staff and the inner circle always referred to it as ‘the Berg’. passing sentry after sentry. Hider stated that the Berghof was also ‘Gralsburg’ (The Grail Fortress). uncertain future. And how they were needed in the situation at the war’s end. of which I had no foreboding that the 15 years past and the three years of internment ahead would leave an indelible physical and psychic mark on me which I still have to this day. I realized that it is really always the same whether we are in Berlin. rather like an egg without a shell.2. precisely because there is no possibility of a life beyond this circle. once beyond it. on the Berg10or travelling: always the same old circle of faces. always the same round. . one knows not where to begin because one has to concentrate so utterly and totally on this life. It was in such a condition. Adolf Hider took his leave of us and told me to get away from Berlin for a dark. at the disintegration of the Third Reich and during my three-year internment in Allied camps and prisons. June 1985 10 From 1936 Hitler’s house on the Obersalzberg was given the name ‘Berghof’. On 2.
The association thus forged would be a lasting one. Whilst there. she replied to an advertisement in the newspaper for a secretarial position at the headquarters of Hider’s stormtroopers . Graduating to a position as Hitler’s personal secretary in 1933. which she experienced from the comparative safety of Berchtesgaden.Introduction S c h r o e d e r w a s a n ordinary woman cast into quite extraordinary times. Born in 1908 in the pretty central German town of Hannoversch Miinden. right up the bitter end in 1945. Her experiences certainly ranged widely. It gives the reader a fascinating insider’s viewpoint on many of the salient events of the Third Reich. Schroeder would be part of the Fiihrer’s entourage for the following twelve years. but also on military matters from the Polish campaign through to the final collapse of the Nazi regime. This memoir.the SA. she trained as a stenotypist before moving to Munich in 1930. is Christa Schroeder’s own record of those extraordinary times. She expounds not only on political developments such as the Rohm Purge of 1934 or the attempt on Hitler’s life in July 1944. but there is a backbone to her book which is not concerned with grand politics C h r is t a . compiled from contemporary notes and letters as well as postwar reminiscences. Yet it is not primarily for her political insights that Schroeder is of interest.
for my few savings were quickly melting away. In the past. whose effects even today I am still unable to shake off I was invited by an unknown organisation. the man who would later become Adolf Hitler’s official photographer. the ‘Supreme SA leadership (OSAF)’ to present myself in the Schellingstrasse. I turned down some work offers hoping to find something better. had made his scurrilous films in these rooms. In this almost unpopulated street with its few businesses the Reich leadership of the NSDAI* the Nazi Party.Chapter 1 How I Became Hitler’s Secretary I wanted to see Bavaria. As I had resigned of my own accord from the Nagold attorney whom I had used as a springboard to Bavaria. I was unable to claim unemployment benefit. I had no premonition that it was to open the doors to the greatest adventure. When replying to an extremely tiny advertisement written in shorthand cipher in the Munchner Neuesten Nachrichten. I had not studied the economic situation in Munich beforehand and I was therefore surprised to find how few job opportunities there were and that Munich had the worst national rates of pay. 50 in the fourth floor of a building at the rear. but soon things began to get difficult. So. was located at No. in the spring of 1930. The former photographic studio with its giant oblique A S A y o u n g GIRL 1 . Heinrich Hoffmann.1 arrived in Munich and started to look for work. I was told it was very different there from central Germany where I had grown up and spent all 22 years of my life. and determine the future course of my life.
There were few Bavarians amongst them. functioned as his Ha (Chief of Personnel). 2 . Dr Otto Wagener. Below the roof at No. must have resulted purely from my being a twenty-two year old with proven shorthandtyping experience who could furnish good references. in Lithuania. Many of these militants went later to the NSDAP. and afterwards the Ruhr. In the autumn of 1919. every Gauleiter ‘had his own SA ’ and his own way of doing things. in contrast to the majority of men on the lower floors where other service centres of the NSDAP were located. Franz Pfeffer von Salomon and his chief of staff. who had lost a leg and was prematurely grey. retired Hauptmann Franz Pfeffer von Salomon. Originally. Upper Silesia and the Ruhr. In 1924 he was NSDAP Gauleiter (head of a provincial district) in Westphalia. I guessed right: most had been Baltic Frei^orps fighters. 50 was a very military-looking concern. That the choice fell on me. After the First World War he had been a Freikprps fighter in the Baltic region. which certainly did not serve the interests of unity in the Movement. The OSAF men appeared to be a military elite. As Hitler took upon himself the decision 1 ‘Baltic fighters’ were members of the various German Freikprps who united with Baltic nationals in 1918—19 to resist the advance of the Red Army and secure the German eastern border. an eternal coming and going by tall. These were predominantly strong Bavarian types.1The smartest and most elegant of them was the Supreme SA-Fiihrer himself. Germany had about 420. I also had a number of diplomas proving that I had often won first prize in stenographic competitions. slim men in whom one perceived the former officer. His brother Fritz. In 1926 Hitler had given Franz Pfeffer von Salomon the task of centralising the SA men of all NSDAP districts.HE WAS MY CHIEF window was now occupied by the Supreme SA-Fiihrer. a person being neither a member of the NSDAP nor interested in politics nor aware of who Adolf Hider might be.000 Freikorps men under arms. Later I learned that I had been the last of eighty-seven applicants to keep the appointment. Many were ‘litde Hiders’.
a former general $taff officer and Freihprps street fighter. and no doubt he gave an inward smile of satisfaction at his own foresight. something which to all appearances he regretted having to do. One day for example I saw a copy of the Party newspaper Volkjscher Beobachter lying on his table. tailored shape.HOW I BECAME HITLER’S SECRETARY in all matters of ‘degrees of usefulness’. industrialists and the nobility 3 . He had given up a directorship in industry and. The OSAF chief of staff was retired Hauptmann Dr Otto Wagener. In August 1930 Hitler was obliged to give in to the pressure of the trouble-makers and sacrificed Pfeffer von Salomon. relying on his comrade-in-arms Salomon. went all out for Salomon and constandy reported their worst suspicions about him to Hitler. for he envisaged the SA as the sword by which he proposed to force through the political will of the Party. Franz Pfeffer von Salomon was a critical sort of man. The debonair Salomon seemed to find Hitler’s figure and manner of dressing. which was the main reason for his having delegated the job. and Hitler took the opportunity to appoint himself Supreme SA-Fiihrer in his place. This was a clever chess move. as probably much else. had followed Hitler’s call for collaborators. I often had cause to confirm this. The Gauleiters were incensed by the reduction in their power. like Salomon from comfortable origins and full of vigour for putting Germany back on her feet. the latter resigned in August 1930. although he did not much like the man. Hider delegated this unpleasant job to Hauptmann Salomon. This ‘keeping myself out of it’ was a crafty move to which Hider often resorted later. he considered it opportune to suppress the Gauleiters by centralising the SA. Dr Wagener lectured at Wurzburg University. It showed a photograph of Hitler. unkempt uniform jacket into a slim. Since this struggle did not go his own way. After making it clear that Salomon had outlived his usefulness. apparendy not to his taste. Salomon had doodled Hider’s filthy. Hitler had of course expected this. That he was a man of wide education with far-reaching contacts to politicians.
He was discharged from the Reichswehr for his involvement in the 1923 putsch. but a year later was active in the Deutsch-Vol^ische Freiheitspartei as a Reichstag Deputy and organised the National Socialist armed group Frontbann. He met Hitler in 1919 as a Reichswehr Hauptmann in Munich. At the end of 1928 he was reinstated in the rank of Oberstleutnant in the Reichswehr and as a general staff officer was sent to La Paz as a military instructor. In 1930 Hitler recalled him to lead the SA. The WPA offices with their various departments for Trade. Rohm was an important member of the Nazi Movement and was on familiar terms with Hitler. Industry and Farming were located in the Braunes Haus at Brienner-Strasse 54.HE WAS MY CHIEF was obvious from the very comprehensive correspondence which I had to transcribe for him. As a liaison officer to the Reichswehr. the former Barlow Palace opposite the Catholic 4 . although he gave up leadership of it once Hitler was released from Landsberg prison. My work for Dr Wagener was interrupted for a few weeks towards the end of 1930 when on Hitler’s orders he took over the leadership of the SA in September to fill the gap before the arrival of Hauptmann Ernst Rohm. When Dr Otto Wagener was appointed leader of the NSDAP Economics Office (WPA) on 1 January 1931. He was seriously wounded three times and lost the upper part of his nose to a shell splinter. he asked for me as his secretary. recalled from Bolivia. He was commissioned in 1908 and in the First World War fought at Flaival on the Western Front. Whilst he held the post of OSAF chief of staff. Ernst Rohm was the son of a senior railway inspector in Munich. Dr Wagener drafted the ‘Economic-Political Letters’ whose length and multiplicity of subjects caused me much toil. After the lively workload at OSAF I found this to be almost a punishment. I then spent a couple of weeks with the Reich leadership of the Hitler Youth which at the time was housed in a private apartment.
1888 Diisseldorf.4At the end of 1932 secret negotiations 2 When the rented premises at Schellingstrasse 50 were no longer adequate for the NSDAP Reich leadership.5 million the former Barlow Palace at Briennerstrasse 45. It was not until 1978 when I read the book by H. provincial government at Wiesbaden. 5 . 1938 president. They also recognised the danger of such genius which. drew almost everybody under his spell. Renamed ‘Braunes Haus’ on 1 January 1931. Pfeffer remained in Munich without an office after his withdrawal but lived with Party associates until elected to the Reichstag on 6. and on his return would dictate long memoranda which when complete would then disappear into his desk. Wagener 1929—1932s that I saw immediately that Wagener’s mysterious partner on his trips and discussions had been Adolf Hitler. In 1933 police commissioner in Kassel.2. on 5 July 1930 Hitler bought for RM 1.4. released 1946. As his intuition could not be faulted with logic because it has a visionary origin and lacked any basis of logic. interned by Allies. he considered them to be fault-finders and pedants and eventually he cast them aside. which he would have not found pleasant. or so it then seemed.2Dr Wagener used to dictate long reports about discussions he hid had without mentioning the name of the other party. 19. it housed the NSDAP Reich leadership on three floors. strengthened by the suggestive power of his oratory. 3 The tide means ‘Notes by a Confidante’. 4 Franz Felix Pfeffer von Salomon (b. In my opinion these three saw in Hitler a singular visionary genius. Later other buildings were purchased including two during the reconstruction of the Konigsplatz on Arcisstrasse which remain standing today. OSAF Franz Pfeffer von Salomon was relieved of the post of OSAF and left out in the cold. and all too much cloak-anddagger. 1944 briefly under arrest in connection with July Plot. d. Turner jr.11. I would often get annoyed about this unnecessary production of paperwork. 12. These three well-above-average men were probably agreed in taking the opportunity of the frequent and long conversations to test Hider’s infallibility by queries and objections.1932. He also made long trips away from the office. and was enlarged.HOW I BECAME HITLER’S SECRETARY seminary. Built in 1928 it was converted by Professor Troost and Hider. Aufzeichnungen eines Vertrauten Dr h.c. His other conversation partners were Franz Pfeffer von Salomon and Gregor Strasser.A.1968 Munich).
following USCHLA hearing cleared of all involvement. Berlin. 8.1933 resumed former WPA post. 1947 convicted in Italy of war crimes. PoW (British) 1944 in rank of major general. 3. released and returned to Erzgebirge to farm.1971 Chieming-Stottham/Bavaria).6 It is no wonder that hardly anybody knows the name after he withdrew and was apparently no longer required after 1933. Martin Bormann was simply one of the most devoted and loyal of Hitler’s vassals who would often force through ruthlessly and 5 Gregor Strasser (b. but remained Reichstag deputy until 1938 and SA-Gruppenfuhrer. expelled from the Party. 30. 6 .9. 8. fought in the Second World War. 1952 released. Pfeffer von Salomon and Strasser were personalities with too much independence for Hitler’s liking.1.4.1930. and all decisions he imposed were blamed ‘entirely on him’ postwar.12. 12. murdered by Gestapo by shooting at their Prinz-Albrecht-Strasse prison. I never heard of him again.1932 head NSDAP Reich Organisational Directorate. from 1. Took over position of acting OSAF from Salomon until 31.1933 Reich commissioner for trade and industry. A person then active in the OSAF who did achieve a meteoric rise was Martin Bormann.6.1934 arrested in Rohm purge. In any case. returned to industry in Berlin. Ministers and also people of Hitler’s entourage.1932 resigned office.4. 9. still of interest today to authors and historians. Apparently his closest colleagues favoured him for finance minister. 30. Gauleiters. 6 Otto William Heinrich Wagener (b. 31.1892 Geisenfeld.1888 Durlach/Baden.6.1933 relieved of all posts after Hitler and Goring suspected him of lobbying for post of minister for industry.1934 Berlin).5. d.6. No doubt Dr Wagener. 4.1932 resigned from Party activities after accusation of disloyalty by Hider in the Schleicher affair. d.5. In 1934 he was killed ‘by mistake’ during the Rohm putsch.1931 head of Economic-Political Office (WPA) atBraunes Haus.HE WAS MY CHIEF between Gregor Strasser5 and Schleicher regarding his being offered the vice-chancellorship led to the total break with Hitler. 9. attached to Fiihrer-StafFfor special purposes.6. end 1933 Reichstag deputy Koblenz-Trier. Dr Otto Wagener moved to Berlin in 1932 and was relieved of all offices in the summer of 1933. The worst character traits were attributed to him. 20.9. who should have known better. not only by journalists and historians but above all by the surviving NSDAP bosses. 29. after Hitler took power I never heard them spoken of again.
He had been present at the marriage of his daughter to Martin Bormann. slim figure he always looked very elegant. NSDAP Reich Leadership Committee of Investigation and Reconciliation. and where necessary to settle differences between individual members in an amicable way’. the beautiful daughter of Party judge. Seen in this way. a position which required a lot of understanding for human inadequacies. With his long face and tall. renamed ‘The Supreme Party Court’ by Hider on 31. By 1 January 1928 it was so well capitalised that only death and invalidity was reinsured out.8All SA men were covered by it. In the First World War he was regimental adjutant and later commander of a machine-gun sharpshooter unit. Its purpose was to ‘protect the collective honour of the Party and its individual members. Bormann could never be called an attractive man. who as the Reich USCHLA judge in the NSDAP was highly respected and enjoyed Hitler’s confidence. At OSAF.7 Buch had been an active officer and subsequendy an instructor at an NCO training school. In the spring of 1930 at OSAF. 8 The SA personal injury insurance scheme started with the Giesinger SA in Munich and at the beginning of 1927 was extended to cover the entire SA under the administration of OSAF in a special sub-division Versicherungswesen.HOW I BECAME HITLER’S SECRETARY sometimes brutally the orders and directives given him by Hitler. After the war he left the army in the rank of major and joined the NSDAP In 1925 he was appointed USCHLA chairman. running batdes with Gauleiters. much tact. He had married Gerda Buch. At their gatherings there 7 USHLA = Untersuchungs-und Schlichtungsaussschuss. 7 . Party bosses and the rest being the rule. Martin Bormann headed the SA personal injury insurance plan designed by Dr Wagener.1933.3. which was naturally very beneficial for Bormann’s prospects. for his father had been president of the Senate at the Oberland tribunals in Baden. later known as the NSDAP Hilfskasse. In 1918 he took over an officer-candidate battalion at Doberitz. retired Major Walter Buch. Bormann followed the same kind of path as did Franz Pfeffer von Salomon. Bormann was as yet unburdened by the far-reaching and unpleasant tasks which Hitler gave him later. ministers. energy and authority. He was predestined for the office.
1931. released 4. Anyone who knew how Hitler did things will realise that this was decisive for him! When the reinsurer demanded a hefty rise in premiums at the end of 1928 for increased risk. hurry’ was his celebrated phrase. 1934-29. from 1938 Reichstag deputy. and he never forgets anything! . head o f ‘Private Chancellery Adolf Hider’ February 1933. NSDAP Hilfskasse 12.4. If I tell him. Bormann’s reports are so precisely formulated that I only need to say \es or No . Only after beginning work on the staff of the Fiihrer’s deputy did Bormann succeed later in proving his extraordinary qualities.1927. He is the exact opposite of his brother9who forgets every task I give him. d. remind me of this or that in six months. being known as the NSDAP Hilfskasse from 1 September 1930. Hitler. 9 Albert Bormann (b. .4. His career took off in the course of the 1930s. With him I get through a pile of files in ten minutes for which other men would need hours. Bormann does it for me in two hours.4. always full of praise for Martin Bormann. The insurance was useful and necessary.1902 Halberstadt. 1945 personal adjutant to Hider. in Bavaria then assumed the name Roth and worked as a farm labourer until 5. . From chief of staff to Rudolf Hess he became NSDAP Reichsleiter and then Hitler’s secretary.HE WAS MY CHIEF tended to be a lot ofbrawling which tended to result in bodily injuries. He expected from his staff that same enormous industriousness which distinguished himself. I can rest assured that he will do so.1989 Munich). once said: Where others need all day. OSAF abandoned reinsurance altogether and under the direction of Martin Bormann from 1 January 1929 the insurance was turned into a giant Party enterprise with no private involvement. joined NSDAP 27. 8. Bormann came to Hitler not only well prepared with his files but was also so in tune with Hider’s way of thinking that he could spare him long-winded explanations.1949 when he surrendered to the authorities. 2.4. Brother of Martin Bormann.9.5.10. It was created to serve the single primitive purpose which the genius of Martin Bormann could not cover. ‘Hurry. . interned. and this did not help to make him loved.1949.
for he was incorruptible and came down hard on all corruption he discovered.’ Bormann did this and protected Hitler. humane or serving some useful purpose. To my mind he was one of the few National Socialists with clean hands. and I can rely on him absolutely and unconditionally to carry out my orders immediately and irrespective of whatever obstructions 10 Although Schroeder may have thought him to be Herr Incorruptible. do me a favour and keep the Gauleiters away from me.’ Bormann executed all Hider’s orders faithfully and without question. never asking if they were right. Whatever or whoever is useful to the Movement is good. 9 . If a Gauleiter then happened to cross Hitler’s path while strolling. For sheer lack of time Hitler could not attend to all day-today affairs. ‘but whatever he takes on is given hands and feet. Ministers.10if one may put it that way. the ‘clean hands’ of Martin Bormann were the result of his personal devotion to the Nazi cause. and he was also the scapegoat. Hitler would put on his surprised face.’ Hitler said once. In a letter to Hess on 5 October 1932 he summed up his attitude thus: ‘For me and all true National Socialists the only thing that matters is the Movement. The Gauleiters were as a rule old street fighters who had known Hitler longer than Bormann and felt senior to him. Hitler would play the innocent and gasp: ‘What? You are here?’ When the Gauleiter then held forth on Bormann’s shortcomings. I am of the opinion today that nobody in Hitler’s entourage save Bormann would have had the presence to run this difficult office. Gauleiters and others believed that Bormann acted from his own lust for power. I remember for example that at FHQ Wolfsschanze Hitler would often say: ‘Bormann.HOW I BECAME HITLER’S SECRETARY Many of the rumours still current about Bormann have in my opinion no basis in fact. ‘I know that Bormann is brutal. nothing else. whoever damages it is a parasite and my enemy. He was neither hungry for power nor the ‘grey eminence’ in Hitler’s entourage. and perhaps whenever possible he avoided doing so to prevent himself becoming unloved! Accordingly all the unpleasant business was left to Martin Bormann. For his oppressive attitude in this regard he increasingly antagonised corrupt Party members and many others.
Hess or the Party. Viennese psychologist and biographer of Lanz von Liebenfels whom he knew well. All inferior races were to be exterminated. and of whom Hitler once said: ‘I only hope that he never becomes my successor. propagated racial purity in his first book in 1905. who had studied sufism. being involved in the detention of the ministers at the Biirgerbraukeller. rosicrucianism and astrology in Turkey. Next he entered commerce and studied economics and history. 10 . for I do not know whom I would pity more. He wrote a magazine Ostara in Vienna in 1907—8. Following the failure of the putsch he spent an adventurous six months in the * The Thule Society was a cornerstone of the Nazi Movement. which von Liebenfels gave him free of charge.HE WAS MY CHIEF may be in the way/ For Hitler. Dr Wilfred Dahms. In November 1923 Hess led the SA Student’s Group and was at Hitler’s side for the putsch attempt of 9 November 1923. der Hitler die Ideen gab that the primary aim of the Thule Society was to create a Nordic-Aryan race of Adanteans. One evening in 1920 he happened upon an NSDAP meeting and joined the Party immediately as an SA-man. He was brought up in Egypt until aged fourteen. when he attended a special school at Godesberg on the Rhine. Hider collected all issues. He advocated the racist State with a self-elected Fuhrer. Martin Bormann was a better and more acceptable colleague than Rudolf Hess had been. After the 1919 revolution he joined the Thule Society* in Munich and took part in the overthrow of the revolutionary councils in Munich. Guido von List (1865-1919) was the first popular writer to combine racial ideology with occultism. the son of a wholesaler. took the one-year examination and then a course in business practice which took him to the French-speaking region of Switzerland and then Hamburg.’ Rudolf Hess was born in Alexandria. His friend and pupil Lanz von Liebenfels (1874—1954). and saw international Jewry as the enemy of Germanism. receiving a leg wound. Egypt. His father came from Franconia and his mother was of Swiss descent. stated in the biography Der Mann. At the outbreak of the First World War he volunteered for military service and in 1918 was an airman with Jagdstajfel 35 on the Western Front with the rank of lieutenant. a former Cistercian monk. The three co founders were mystics. The third co-founder was Rudolf von Sebottendorf (1875-1945?).
Instead The original Thule Society was founded in 1910 by Felix Niedner. Hider was not a member of the Thule Society but the link was the DAP founded on 5 January 1919 by Anton Drexler which was useful for contacts. For a short while Walter Funk. The whole affair began with a telephonist hearing a surname incorrectly. held the seat. General Haushofer. after Hitler and Eva Braun had gone upstairs. at the German Academy at Munich University. but suffered changes of leader after the departure of Dr Wagener. he invited a few guests sympathetic to him to his country house for a celebration. translator of the old Norse Eddas: the 1919 Thule Society was an amalgamation of the original society with the Germanen Order. members and the interchange of information. a secret anti-Jewish lodge founded in 1912. Two days before the abolition of the Bavarian peoples’ court he surrendered to the police. and taken to Landsberg prison where he remained with Hitler until New dear’s Eve 1924. From 1925 he was Hitler’s secretary. The DAP was the forerunner of the NSDAP The Thule Society was still in existence in 1933 when it was probably absorbed into the SS. Later he became an assistant to the professor for geopolitics.1 remember that on the evening of 10 May 1941. and at the end of my spell in Munich it passed to Bernhard Kohler.HOW I BECAME HITLER’S SECRETARY Bavarian mountains. Kohler remains in my mind for his advice to me: ‘The person who defends herself. My idea was to throw light on a slander circulating about me which was making my life in Munich hell. later the Reich economics minister. known for his thesis Arbeit und Brot (Work and Bread). (Translator’s Note) 11 . Rudolf Hess and Hider’s mentor Dietrich Eckart. The Nazi swastika was designed by Dr Krohn. accuses herself!’ and dissuaded me from instigating an USCHLA hearing. was tried and sentenced immediately. Amongst the members were Karl Haushofer. That evening everybody reported on how relieved he seemed! The NSDAP economics department at Munich went on. The emblem of the Thule Society was a circular swastika superimposed upon a broadsword within a wreath. The male telephonist at the Braunes Haus had misunderstood the name of a friend who had called me. a Thule Society member. Martin Bormann was certainly not dismayed by Rudolf Hess’s flight to Britain in 1941.
then my boss in the economics department. As soon as we made a stop anywhere. a Jewish name. Despite this proof of 12 . surprised me with the question: ‘Christa. He drove the coach himself and had apparendy taken a liking to me. she replied: ‘An SS-Fiihrer!’ I asked her to have him present himself so that I could clear up the matter. The excursion had been arranged by a Herr Kroiss and his wife from Rosenheim. are you really having a relationship with a Jew?’ When I asked who had said so. a pure Bavarian name. Herr Kroiss and his wife would invite me to their table. the niece of the NSDAP Reich treasury minister Franz Xaver Schwarz. Herr Kroiss. was asked twice by three gentlemen in a large Mercedes where the best place was to spend the night.1 had gone on a coach excursion through the Dolomites to Venice with an older female colleague. and were together with him in Italy?’ My assurances and explanations availed me nothing. not even when my friend Vierthaler provided an affidavit swearing to his pure Aryan origins. Bernhard Kohler.HE WAS MY CHIEF of Vierthaler. A statement by Herr Kroiss that he organised his tours in such a manner that nobody could absent themselves overnight was similarly unsuccessful in putting an end to the accusations. Shortly before. and a couple of days later he turned up —I have forgotten his name —and asked me: ‘Do you perhaps wish to deny that you are having a relationship with the Jew Fiirtheimer. who knew the route very well. with whom I lodged the various affidavits told me: ‘Whoever defends herself. and the telephonist’s later error at NSDAP HQ. but realised that he opposed an USCHLA hearing. One of them invited me to take a trip with him in a gondola that afternoon. which I was pleased to accept. accuses herself!’ I did not understand the sense of this. these three gentlemen booked into the same Venice hotel as ourselves and even invited themselves to sit at our table. never suspecting what was in store for me as a result of my companion’s envy and feelings of being abandoned. As fate would have it. ignoring my travelling companion. in October 1932. Back in Munich a friend. he misheard Fiirtheimer.
He was a dark-eyed. the suspicions of the Party members smouldered and I suffered very much as a result of it.11 they also avoided me with a hurtful distrust. 12 The liaison staff at Wilhelm-Strasse 64 in Berlin was a service office of Hitler’s deputy Hess. the actual head office was in the Fiihrer-building on Arcis-Strasse in Munich. The Munich girls held back. whether he was or not I have no idea. Next day the owner’s son advised me: ‘Fraulein Schroeder. diagonally opposite the Reich Chancellery. those people who spoke High German. In order to sweep aside all suspicions I decided to reject all future invitations. called for stenotyists to volunteer for the NSDAP Liaison Staff in Berlin. Once Hitler had become Reich Chancellor. they were not keen on Berlin. I informed the Reich treasurer. If the dyed-in-the-wool Bavarian of the early 1930s was filled with the proverbial hatred of the Prussians. by extension. The gendeman caller had invited me to a recital. 13 .HOW I BECAME HITLER’S SECRETARY my manager’s confidence in me. and instead took every course going at the Berlitz School and local college. I would spend most II Prussians were all those who came from northern Germany or. chief personnel officer at the Braunes Haus.12Upon my arrival I was acquainted with my duties by the elegant and robust Consul Rolf Reiner. One evening a male friend came to collect me from my small hotel. be cautious!’ He said nothing else. and next day he told me that it had been arranged. Apparently the SS had asked the hotelier to look at my friends closely. All the greater was my own readiness. its function was to act as the contact office between Party centres and the Reich ministers. In March 1933 I arrived in the capital. I never asked him. Rohm’s adjutant in Bolivia. It was precisely this hatred of the Prussians which now changed the course my life was to take. The office block in which the NSDAP Liaison Staff was housed in Berlin was at Wilhelm-Strasse 64. NSDAP Reich treasurer Franz Xaver Schwarz. black-haired attorney and apparendy looked Jewish. Headed by Rudolf Hess.
13 In 1933. The experience of how readily believed were those who pointed the finger of suspicion. became deeply engraved within me. During the ^ftfeimar Republic the palace was the seat of the Reich government. all Hitler had was one office and a room for his adjutants. Bismarck. and how easy it was to become their victim. this time as a film engineer for three 13 The palace at Wilhelm-Strasse 77 built by Graf von der Schulenburg between 1738 and 1739 was bought by the Radziwill family in 1796. After this nasty experience. his father was Silesian and his mother from the Thuringian aristocracy. Whether it was the proverbially good Berlin air or the atmosphere with my more united Berlin colleagues I felt I had shed the suspicions which had weighed down so heavily on me in Munich. After more study. This left him with nowhere to install a female secretary. particularly after the compulsory purchase of all buildings in the Voss-Strasse in 1938. 14 . Wilhelm Bruckner came from Baden-Baden. I would then type up his letters in the Liaison Staff and bring them back in the post portfolio for him to sign. Working for Hitler’s chief adjutant Wilhelm Bruckner was far more interesting. At the end of the war only ruins and rubble remained. moved in after rebuilding.HE WAS MY CHIEF of my time with the Liaison Staff although from time to time I might be required to make myself available to Hitler’s chief adjutant. and from then until 1939 further building and expansion work was always in progress. although I was never able to shake off completely the effects of the slander. After the First World War he remained in the Reichswehr as an Oberleutnant then joined Freikorps Epp. the first Reich Chancellor. At least every two days he would summon me by telephone to the Reich Chancellery for dictation. The Reich bought it from them in 1875. Nearly all incoming mail was passed to the competent SA centre. Work with the Liaison Staff was for the most part very easy. SAGruppenfuhrer Wilhelm Bruckner in the Reich Chancellery. I think I looked at things rather more critically and became less trusting. He was an engineer by trade but studied economics later. and renovation work was completed in 1878. helping to put down the revolutionary council in Munich.
HOW I BECAME HITLER’S SECRETARY years he joined the NSDAP in 1922 and the following year led the proscribed SA Regiment Munich.1903 Munich. His fiancee Sophie Stork. Once a letter came from a schoolboy which said: ‘So long as he —Bruckner —is close to Hider. d. Very reasonable and practical. even when he gave someone a ticking off nobody could get mad at him.10. but he also had charm. one need never worry about Hitler’s safety.14 a frequent guest at Obersalzberg. very tall. 5.5. One of his most important jobs was to receive members of the public who wanted to make a request. He would note the request. Bruckner was not only one of the best-looking men in Hider’s circle. according to Schroeder she received from Hider compensation in the sum of RM 40. complaint or suggestion. Bruckner had a ready ear for everybody and.’ After Hider took power in 1933. so far as possible. would help out financially in needy cases. complaint etc. That earned him four and a half months in jail. or give encouragement. immediately and in an unbureaucratic manner. 15 . he was on sick leave for a long period. Subsequendy he took office as the third general secretary of the Verein fur das Deutschtum im Ausland (Association of Germans Abroad) in Munich. Over the years Bruckner gradually fell into disfavour with Hitler. and at the end of 1924 another two months for membership of a banned organisation. After Bruckner broke off the engagement in 1936.000 which caused her many problems with Allied investigators after the war. Bruckner was given a whole new set of duties in addition to those he already exercised as Hitler’s chief adjutant. 21. At the end of 1930 he was appointed SA adjutant to Hider although in this role he was more a personal aide in constant attendance. After a car accident in 1933 at Reit im Winkl when he lost an eye and suffered various fractures. to Hider in person. blond and blue-eyed. They came to the Reich Chancellery in the hope of talking to Hider. who 14 Sophie ‘Charly’ Stork (b. on a small white card which he used to tuck into the sleeve turn-up of his SA uniform.1981 Seeshaupt) was introduced to Hitler at Obersalzberg in the spring of 1932. She was a frequent guest at the Berghof and received commissions from Hitler for her hand-crafted ceramics etc.
HE WAS MY CHIEF had been a passenger in the car. For more than a decade Bruckner had stood at Hider’s side even in the difficult times. carefree people and had an eye for a pretty woman. In occupied France he had the post of city commandant. Possibly Bruckner made too light of many things in life but he was a gendeman and his charm created a good atmosphere in Hider’s entourage. Sophie was a very talented artist. She painted a coffee service for Eva Braun. Therefore I came under pressure all the 16 . and served him loyally. the house manager. When he fell in love with the daughter of the ‘other woman’ cited as a co-respondent in the Magda Quandt divorce — before Magda met and married Goebbels — Hitler’s displeasure with Bruckner grew. Her father owned a noted sporting business in Munich. the latter gave her a frosty welcome. and there was always urgency about the work. liked happy. Particularly after the accident Hider took a dim view of Bruckner not marrying Sophie Stork and made her a large ex-gratia payment from his own pocket. After his dismissal in 1940 Julius Schaub became chief adjutant. made personalised tiles for the pastry area of the new Berghof dining hall and the large hand-crafted ceramic oven in the lounge. which apparendy used to annoy Bruckner. also suffered serious injuries. After dinner. which was a serious snub. The demands made of Bruckner in the Reich Chancellery were of great importance for those involved. When Bruckner brought his Gisela to the Berghof one evening to meet Hider. Hitler stopped at the dining room door and said to Bruckner: ‘I expect you will be escorting Fraulein Gisela back down into Berchtesgaden tonight?’. a good-looking man and always the optimist. Sophie Stork was the jealous type and often let it show. After a long period of internment after the war he lived for some years after his release at Traunstein where his sergeant from the First World War let him have two small rooms. but he was no substitute for Bruckner. Bruckner. It came therefore as a severe blow when Hider dismissed him without ceremony in October 1940 after an intrigue by Kannenberg.
I must have done the job to his satisfaction for he gave me a box of chocolates as I left. Hitler.’ When I said in embarrassment that I had an ugly name. Herr Hitler. Emilie. One day when I was giving Bruckner his outgoing mail to sign Hitler came into the room. (Christine is my middle name) he contradicted me: 'You ought not to say it is an ugly 17 . gave me a questioning look and said: ‘Do we know each other?’ I replied. ‘I mean your first name. I know that. Herr Holsken. but Fraulein Frey. He came to me in a friendly manner and said: ‘I am very pleased that you will write for me. had something he wanted to dictate urgently.’ That had happened one Sunday in 1930. could not be contacted. Rather taken aback I said. His secretary cannot be contacted and I would like you to come with me. ‘Schroeder!’ ‘No. and as a result he remembered me so that soon I was working not only for Bruckner but also for Hitler personally whenever he requested it. Whenever he met me afterwards in the Braunes Haus he would always acknowledge me in a very friendly way. I did some work for you in Munich. Rudolf Hess received me in an ante room and led me to Hitler’s study. ‘Yes. coming back from the mountains. was asked to find an experienced substitute. who was then his stenotyist.’ At that time I did not realise Hitler’s importance and was used to typing dictation directly into the machine so I went ahead without any inhibitions. He had an above-average memory for faces and events. On 23 December 1933 upon completing a task for Hitler I requested a signed photograph.HOW I BECAME HITLER S SECRETARY time and shuttled assiduously between the NSDAP Liaison Staff and the Reich Chancellery.’ At the Braunes Haus. I was surprised when he wanted to know my name. Remembering my fast typing speed at OSAF he came to my flat and said: ‘Herr Hitler has returned from the mountains and has something he must dictate. who worked in Rudolf Hess’s secretarial office. It is only a draft and so it will not be important if you make a few typographical errors.’ he replied. He stopped. It was my first direct meeting with Hitler.
it was the name of my first sweetheart/ Naively. Perhaps he was put out by the fact that they had done work previously for several of his predecessors and had been employed as secretaries by them. These were Fraulein Biigge and Fraulein Frobenius. from where he graduated into Hider’s private chancellery under Rudolf Hess. and took over running it from 1933. That same year he married a woman of whom brother Martin disapproved because she was not Nordic. In 1930 at the Braunes Haus Hider had used as his secretary Fraulein Herta Frey (later married as Oldenburg) from Hess’s Chancellery. I record it here not to put matters straight but because Hitler’s remark had the simple interpretation for me that as a young man he had led a normal love life. and from 1931 or 1932 Johanna Wolf who had been in the NSDAP Gau of Lower Bavaria and worked for Hider’s mentor Dietrich Eckart in 1923 until his death that year. I happened to mention this to Henriette von Schirach. not suspecting that she would use it without permission in her book Ane^doten um Hitler}5 She inflated this little aside out of all proportion. that brother would send for an orderly officer to 15 Turmer Verlag. and the two brothers became estranged. In any case he ignored them completely. Adolf Hider had two civil servants at the Chancellery available to him as personal secretaries. 1980.HE WAS MY CHIEF name. Officially as Reich Chancellor. Albert Bormann had been introduced by his brother Martin into the SA-Hilfskasse insurance scheme in 1931. 18 . If they were standing together. If for example Hider gave one of them a job to pass to the other. The two private secretaries Fraulein Wolf and Fraulein Wittmann whom he employed in 1933 had no office space in the Reich Chancellery and worked a roster between themselves of four weeks in Munich with Rudolf Hess and four weeks in Berlin at Hider’s private chancellery run by Albert Bormann from outside the Reich Chancellery. it is very beautiful. each would ignore the other.
Hitler had given orders to renovate the old palace. The Personal Adjutancy now underwent expansion. Hitler said.10. speaking of Hindenburg. 1923 active role in putsch.8.I was summoned to Hitler’s Reich Chancellery more frequently than Johanna Wolf. Julius Schaub’s16desk was there.’ Accordingly. After the Radziwill Palace was ready the ‘Personal Adjutancy of the Fiihrer and Reich Chancellor’ was housed in a large room next to the so-called Bismarck room. he wanted to inform his brother of the fact. 27. When Albert Bormann divorced after a few years and married his ex-wife’s cousin. and I moved in as Bruckner’s secretary. It was also in this hall that Hindenburg had received Hitler and appointed him Reich Chancellor. 31. Martin Bormann refused to receive him with the remark: ‘I don’t care if he marries his grandmother. spent most of the First World War in military hospitals either as an attendant or patient. Most of the time I sat alone looking out on the old park. I spent a long period shuttling back and forth between the old Reich Chancellery and the Liaison Staff. Herr Hitler.1898 Munich.1. If one of the brothers told a funny story everybody present would laugh except the other brother who would keep a straight face.12. after his appointment to Reich Chancellor.HOW I BECAME HITLER S SECRETARY convey the instruction to his brother standing a few feet away.1920 joined NSDAP. This was especially necessary in the historic Congress Hall where Bismarck had celebrated the now-famous Berlin Congress of 1878. Until the work was completed Secretary of State Lammers made available to him the service flat under the roof of the old Reich Chancellery on the corner of Wilhelm. Before Hitler could move into his flat in the Radziwill Palace as Reich Chancellor. the floor won’t last much longer. 10. He was Hitler’s factotum and had followed 16 Julius Gregor Schaub (b. ‘The old gentleman’. d.and Voss-Strasse.’ Since I was resident in Berlin and always on call —I had only to walk across the Wilhelm-Strasse . 20. fled 19 .1917 conscripted. had told him on that occasion: ‘Keep to the walls if you can. the old walls had to be renovated.1967 Munich).
When told that Schaub had been hitting the bottle at a reception Hitler made a despairing gesture with his hand and sighed: Tfes. in the early years of power it was always: ‘Schaub. This earned him some jail time which he spent with Hitler at Landsberg am Lech. Hitler knew that Schaub liked his tipple.17Since Hitler never carried a pen or pencil on his person. He had rather bulging eyes and limped because he was missing some toes from frostbite in the First World War. fled to Kitzbiihl using alias ‘Josef Huber’. 20 . it is sad. and since he boycotted anybody not to his liking affection for him in Hitler’s circle was very limited.1945 detained by US forces. released 31. 27-31. He was involved in the 1923 putsch. sentenced to 18 months at Landsberg. He joined the NSDAP early on and came to Hitler’s attention as he limped around the NSDAP meetings. I know. 8.4.2.5.1924. 17 The list of presents was arranged by donor.12. He was so loyal to Hitler that at his request he gave up smoking. But what can I do. write this down!’ Before Martin Bormann ascended into Hitler’s close circle. and finally abandoned the struggle to make Schaub teetotal. 20. A typical Bavarian. 17. sh. Schaub had trained in pharmacy and after the First World War worked at the main supply office in Munich. he was probably the only person who knew all Hitler’s intimate and personal secrets.1924 arrested on border at Salzburg. Schaub was always Hitler’s mobile notebook. This handicap was perhaps the reason why he was so irritable. Schaub was not very prepossessing. at war’s end released by Hider.’ After taking power Hitler needed a qualified valet.HE WAS MY CHIEF him like a shadow since 1925. Schaub to Austria. After early release he became Hitler’s constant companion from January 1925. He was ever suspicious and additionally very inquisitive. scheduled the important birthdays and made lists of presents. I have no other adjutant. and Schaub was retained to handle all his confidential affairs. next day appointed Hider’s private valet. SSObergruppenfuhrer and Reichstag deputy. but not alcohol. For the 1935 and 1936 lists see BA Koblenz R43 II 967b. He kept all Hitler’s secret files in an armoured safe. article and year.1949 released.
had been a dancer. settling invoices and so on. an Austrian. After Wilhelm Bruckner was sacked by Hider in 1940. Schaub received the title ‘personal adjutant’ with the rank of SSGruppenfuhrer. In it she described her povertystricken circumstances. since the latter did not like money on his person. Naturally without their knowledge Schaub had to rent the couple a two-room flat and furnish it (carpets. which was a big plus point with Hider. That they were overjoyed goes without saying. 21 . Hitler checked the details and finding them true found the man a position. He carried Hider’s loose change. A large reception was arranged for the Party at NSDAP HQ in Munich every year. he invited singers from the Berlin Opera and dancers from the theatrical operas and the Charlottenberg Opera. bedding. Every year he threw a banquet for artists and another for industrialists. It was also one of Schaub’s duties to visit variety performances and theatres at change of programme in order to keep Hider informed whether a visit might prove rewarding. curtains. the main purpose of these being to raise money for Winter ReliefWork. as from 1943 SS-Obergruppenfuhrer. Schaub often recalled with pride that his mother. He was an enemy of the gutter press. This position 18 Schroeder explained that since there was no dancing at Hitler’s banquets in the Reich Chancellery. Then a Christmas tree was set up with the usual adornments and the candles lit while Schaub fetched the young couple in the car. furniture). When he had to ring up actresses and dancers inviting them to the Fiihrer’s flat for an evening chat18 he could even be charming.HOW I BECAME HITLER’S SECRETARY also handled some of Hitler’s financial affairs. I think it was December 1936. That was probably the reason why he was so fond of dancers and cabaret artists. Her fiance. She begged Hitler to find him work. had done much for the Nazi Movement and was on the run to avoid arrest. One day a pretty young girl brought a letter to the Braunes Haus for Hitler’s personal attention. During the Berlin Olympics a great banquet was held at the Reich Chancellery for all competitors. who died in the 1908 Messina earthquake. for she earned very little herself and the couple was keen to marry.
From the SS bodyguard stationed around the Fiihrer apartment a mature SS-Fuhrer19trained in commerce was selected for service in the Personal Adjutancy and to handle our telephone exchange. It made no difference to Hitler. dismissed along with Bruckner by Hider 18. which Wiedemann turned down.1940 with the observation: ‘I am sick of the problems in the Adjutancy’.1945 brought to Washington.1967).7. July 1941 expelled from United States with all German diplomats.1948 released from internment. Bavarian reserve infantry regiment. Wiedemann studied political economics in Munich.9.1. As the pair of them had plenty to do elsewhere they gave Wernicke and me a free hand and so we kept the office work in the Personal Adjutancy flexible and fairly unbureaucratic.16. 1938 Reichstag deputy.8. November 1941 consul-general Tientsin (China). March 1939 consul-general at San Francisco.1970 Fuchsgrub). As regimental adjutant with 16.1899 Ribbeck/Templin. 18. 6.8. Released from the Reichswehr in 1919. He next met Hider by chance in December 1933 when he was in financial difficulties 19 Paul Wernicke (b. where he was offered the opportunity to lead the SA.8.1. d.1941. Div-Staff HQ. SSObersturmbannfuhrer Paul Wernicke had good office experience. attached to Sonderkommando Der Fiihrer at the Reich Chancellery. Wiedemann had been Hitler’s immediate superior. Schaub obeyed without question.1.1891 Augsburg. In the 1920s he met Hitler again at a regimental reunion. 1930 joined SS. and all files and papers there and at the Munich flat.1935 adjutant at Personal Adjutancy as N SKK Brigade-Fiihrer.HE WAS MY CHIEF often brought him into situations which he was not competent to handle. Wernicke soon proved himself an important and reliable colleague. 14. Things changed when Hauptmann Wiedemann20was appointed Hitler’s adjutant. Eastern Front. to LSSAH 2. When in April 1945 he told Schaub to destroy all personal property at the Berghof which might suggest to people a female presence. Cdr. 20 Fritz Wiedemann (b. was capable and tidy and soon made himself indispensable to Bruckner and Schaub. 5. 22 . neither of whom had a clue how to run an office.5. 1. in which Hitler had served as despatch runner. rank of SSObersturmbannfuhrer.1934. Regiment List.10. d. entered Personal Adjutancy 2. February 1933. 24.
3. After an eleven-month training period with the staff of Rudolf Hess at the Braunes Haus in Munich. 5. after taking power Hitler required a properly trained manservant whom he found initially in Karl Krause.l 1. When Hitler asked how things were going. Hider offered him the post of adjutant.1911 Michelau).2. In January 1939 Hitler could stand no more and told Wiedemann that in his closest circle he could not use a person not in agreement with his policies.HOW I BECAME HITLER’S SECRETARY after the failure of a dairy enterprise in which he had invested. Wiedemann took up his post as Hitler’s Adjutancy on 1.21 When dismissed. which he accepted at once.1934 selected as manservant for Hider. the adjutancy correspondence and filing was in something of a mess. whom Hitler called ‘my ultra-optimist’. As Bruckner was not an office person.11. Wiedemann made several trips abroad.11. December 1943 to 12.1931 Reichsmarine. The impressions he got there led to his becoming ever more downbeat when speaking to Hitler.8. fell 13.1. 1945 SS-Untersturmfuhrer and highly decorated. 22 Hans Hermann Junge (b.1939 dismissed by Hider for lying.4. he replied: ‘grim’.8.1935 at the Reich Chancellery in Berlin. Hider Jugend.1940 to LSSAH Waffen-SS as Oberscharfuhrer.SS-Panzer Div.1914 Wilster/Holstein.1940 returned to Kriegsmarine.3. 10. September 1934 at Obersalzberg with rank of SSObersturmfuhrer. 1. As already mentioned. 1.9. In 1945 the Americans fetched him home as a witness for the Nuremberg trials. 1.1933 23 . Wiedemann combined his work as adjutant with a re-organisation of the day-to-day office procedures in the Personal Adjutancy and increased the staffing level. 2. He flew to the United States a few times and frequently to England. For this reason Wiedemann was sent as consul-general to San Francisco. In contrast to the positive Bruckner. June 1946 released from Allied internment. his replacement was soon labouring under the designation ‘my ultra-pessimist’. 1. and tended to put things off for tomorrow.1944). from where he was next sent in the same role to Tientsin in China. Krause was replaced by Hans Junge22 21 Karl Krause (b. where he was in principle Bruckner’s office replacement. In late 1941 he returned to Germany.
In the evening the servant would report to Hider once all his guests had assembled for dinner.1943 12 SS-Panzer Div.1933 entered LSSAH. 14. . 24. The servant would then place newspapers and reports before the door and retire. although in general conversation the ‘SS2’ was dropped.1943 drafted into Waffen-SS.1935 manservant to Hider. 24 On 17 February 1933 a private bodyguard for Hider consisting of 117 selected SS-Fiihrer and SS men was formed into the SS-Sonderhpmmando Berlin under SSGruppenfuhrer Dietrich.1936 with SS-Begleitkpmmando Der Fiihrer. 24 .1945 Soviet PoW.1913 Bremen.8. 23 Heinz Linge (b. 2. it is arranged that you will lead in Frau Such-and-Such.HE WAS MY CHIEF and Heinz Linge. the servant would prepare his bath and set out his clothing for the day. for service with Hider. On 3 September 1933 the SS-Sonderkpmmandos were consolidated into the Adolf Hider Standarte. Hider would never have a manservant help him dress. SS-Obersturmbannfuhrer.1. While Hitler was reading.7. 23. Accommodated initially in the Friesen Barracks in Berlin. the SS-Sonderkommando moved to the cadet academy at Lichtenfelde in April 1933. released 1955. From the men selected by Dietrich. 17.7. Hider’s servants and orderlies were drawn from the SS-Leibstandarte Adolf Hitler (LSSAH)24 having been selected by Sepp Dietrich. and from 13 April 1934 LSSAH.1943 married Hider’s secretary Gertraud Humps.5. 1980 Bremen). d. Hider Jugend. 1. killed in action. 1. The servants had a very important role to play for the invitees .23 although these men were known as orderlies. After Krause. A few months at the Munich-Pasing servant training school made them into perfect servants.informing them of Hitler’s mood! joined SS. Hitler would then choose the ones he wanted.6. A valet’s duties consisted of attending to Hitler’s personal requirements. from 1940 orderly to Hider. .3. They had to look good. blond and blue-eyed. ’ During the war the servants in the FHQs would invite the participants by telephone to the nightly tea session after the military situation conference. renamed LAH on 9 November 1933 with 835 men. LAH commander.12.3. remained at FHQ to the end.1934 volunteered for LSSAH. In the morning at the agreed time Hitler would be awoken by a knock on the bedroom door. be tall if possible. 1. At the Berghof he would always be told: ‘Mein Fiihrer. capable and intelligent. The on-duty guard was stationed in the Inner Court at the Reich Chancellery. 19.
On his way to these conferences Hitler would always be in haste but on the way back took his time. and it was impossible to have a peep. laid out for him there. At about ten each morning Hitler came through the high wing-doorway at my back from his flat in the Radziwill Palace. presents from supporters and adoring women. to the ministers or their representatives and to the foreign ministry. books. On the other side of the room were the tall wing-doors opening to Hider’s room and then beyond that to the Congress Hall made famous by Bismarck.HOW I BECAME HITLER’S SECRETARY From my work space in the Adjutancy I looked down on the fine old trees in the Reich Chancellery park where Bismarck used to stroll. The Personal Adjutancy was only a liaison and communications centre. handicrafts. The conferences were not tailored to a particular timetable and would often last into 25 . pictures. At this time I saw Hitler daily. In fine weather the glass doors would be fastened wide open and his great. He would always give me a friendly greeting: ‘How are you?’ He was not an office or desk person and preferred to hold his afternoon conferences in the Winter Garden strolling up and down with his conversation partners. Secretary of State Dr Lammers would have drawn up a schedule the day before for the high-level discussions to be held. bright room used only as a corridor to the Reich Chancellery park. We secretaries only had access to Hider’s study for dictation. Mostly he would stand at the large table and look over the materials there. except for weekends which he usually spent in Munich. Often he would give a short instruction or sign those documents appearing to be urgent. These might be applications for honorary citizenship. He passed through the Personal Adjutancy to reach his study in the Reich Chancellery. All political directives and orders for home and overseas Hitler distributed orally to the Reichsleiters. etc. All important correspondence was kept by Hitler personally in his private room while Schaub kept much more in the strongbox. Sitting at my work position I knew only rarely with whom Hider would be having a conference. artwork. to Himmler.
’ One was always groping in the dark for information. He was informed about everything and apparently enjoyed his unique privilege. 25 Hitler issued his ‘Basic Order’ respecting secrecy on 25 September 1941. all the secretiveness created a whirlpool which made me quite nervous. The person absolutely in the know in the Adjutancy was Julius Schaub. Even the trips out would only be announced very shortly before departure. or at least less than the secretaries to the Reichsleiter. and the atmosphere would become ominous. no employee and no worker may know of any secret matter which it is not absolutely necessary for that person to know in the course of his or her duty/ 26 . no official. he would give me a warning look from the corner of his eye over the spectacles perched low on his nose. If Hider’s ‘Basic Instruction’25 was enforced strictly anywhere it was in the Personal Adjutancy. The conversation partner would then carry out the directive or order. I would feel a nasty tightening of the chest should he then decide to investigate further with a ‘What? What’s up?’ Personally that always made me feel threatened and I would try to extricate myself from the business as quickly as possible. perhaps remarking: ‘Oh. I was just wondering. Part I prescribed: ‘Nobody. I never learned anything about the measures being introduced and current events. ministers and so on. While I was living in Wilmersdorf and had to go back there to pack after a trip came up out of the blue. rarely getting to know something concrete. or have it typed up for his signature later. no centre. If by chance I got wind of something and was imprudent enough to even think about asking Schaub. or at least so it seemed to me. When something of importance had occurred.HE WAS MY CHIEF the early hours. then one would get a certain feeling. or was about to. This was published to all military and Reich centres by the interior minister on 1 December 1941.
he had conferences to attend.Chapter 2 The Rohm Putsch 1934 June 1934 a large number of secret machinations was afoot. It was my first flight high above the clouds and I was enchanted by the sight. We took off at about 0300. but one could sense something in the wind. without previous warning. Hitler was not visible. 27 . Bad Wiessee. I seemed to be over a white. foaming sea. There was nothing you could put your finger on. No explanation was given why.1 On the evening of 28 June in Berlin I received telephoned instructions to fly by Ju 52 that night from Tempelhof aerodrome to Godesberg. I was still in this dreamy state when I arrived at Hotel Dreesen. Schaub. Reich press chief Dr Dietrich. In the early hours of 30 June. Chief adjutant Bruckner gave me the job of making telephone reservations at Hotel Hanselbauer. we received orders to fly to Munich. for some high-ranking SA leaders for the next day. Hitler had gone to Essen as witness to the marriage of Gauleiter Terboven. Goebbels was aboard with some of his staff*. Goebbels and the officials of the Criminal- A t th e end of 1 Hitler attended the wedding ceremony with Goring on 28 June 1934 and afterwards visited the Krupp works at Essen. He was accompanied by his closest staff: Bruckner. where I was soon awakened to raw reality. Hitler was in the first aircraft to go.
There was something in the wind but impossible to identify what. the occupants of the second aircraft. We were all still in the dark when. all from Munich. which always took offa little later than Hitler’s aircraft. that Hider himself. Stabschefi’ What must he and the police have thought? I had no inkling of what had transpired beforehand. after a long drive to Bad Wiessee. only half an hour previously. had roused his former friend Rohm for his bed and had him arrested. Rohm and other arrested SA leaders were driven at once to Munich in Hitler’s convoy of vehicles. The adjutants had simply forgotten to tell him. The Criminal-Police officials looked at me in surprise as I went up to SA chief of staff Rohm. Bruno Gesche had not been informed of where to go from Munich. we entered the foyer of the Hotel Hanselbauer to find there the same oppressive atmosphere we had sensed in Godesberg. being left only with this scene in the reception lounge. knew nothing of the main drama which had played out in the Hotel Hanselbauer. we had to almost do an aboutface and get back in our cars. designated RSD (Reich Security Service) it had grown in size to 250 men.3Hider. Gesche was scratching his head as to how to proceed and I mentioned to him the SA conference at Wiessee set for that day. intending that to be a clue for him. the only woman present amongst the SS-Begleitkpmmando (bodyguard) under Gesche. a lieutenant in the Bavarian provincial police force and from 10 March 1933 adjutant to Himmler as president of police. his fine shepherd dog resting alongside him. By 1944. When we arrived in Munich something unexpected occurred. I flew in the second aircraft. 2 In March or April 1933 Hitler formed a ‘Police Commando for Special Purposes’ headed by Johann Rattenhuber.HE WAS MY CHIEF Police Division2under Rattenhuber. 3 Hider’s driver Erich Kempka stated postwar that Hitler went to Bad Wiessee 28 . who was sitting in a winged-back armchair. Gesche had already asked if there were any orders left for him at Hitler’s flat in the Prinzregenten-Platz but had drawn a blank. the SSBegleitkpmmando. After Rattenhuber had briefly updated Gesche on events. The squad. We. gave him the friendliest handshake and said: ‘Heil Hider. was eight strong and worked alongside Hider’s bodyguard.
in the kitchen region. having gone with his staff and the police commando only. a fact of which they took a dim view. delivered a brief address from which one phrase has stuck in my mind: ‘I am pleased —or I am proud. rather like a person who. von Spretti. I was sitting at a table all alone when the door opened and Hider came in. This part of the kitchen was not on the way to his private apartment on the first floor of the palace. The SS-Begleitkpmmando was left in the dark. but the actual number of victims was greater. What had brought him there? What did he mean when he told me he felt ‘as if newly born?’ In his own dining room on the park side Goebbels and the other men of his staff were waiting for him. After the return to Berlin I had gone to the dining area at the Reich Chancellery for a snack. The official list has eighty-three names. visibly moved. The journey. I have bathed and feel as if newly born. sat himself near me at the oval table and. talk being of shootings at Stadelheim4 amongst other things. Hitler. 4 On 30 June 1934 at Stadelheim prison. had them get out and personally tore the shoulder straps from their uniforms. that I have you!’ Meanwhile alarming news had filtered through. I saw this perfectly clearly from where I sat in one of the cars to the rear. Hayn. The event of that day which remains imprinted indelibly in my memory was my meeting alone with Hitler in the SS-Begleitkpmmando dining room at the Radziwill Palace. taking a deep breath. Heines. Heydebreck. yet he sat with me. Other executions followed next day at Dachau concentration camp and elsewhere.’ I was very surprised at Hitler’s presence in this area. Schneidhuber and Schmidt were shot. He glanced at me. where I had never seen him before. 29 . where a Reichswehr company had paraded. Munich. Those arrested were slotted into Hitler’s column of vehicles in their own car but under guard. and saluted Hider. said: ‘So. the SA leaders Uhl. interrupted by various stops of a similar nature. stopped all vehicles coming from the opposite direction (mostly containing SA leaders I had told to proceed to Wiessee). ended in the courtyard of the Braunes Haus on Brienner Strasse 45.THE ROHM PUTSCH 1934 in the leading car.
The SA is and remains the destiny of Germany. it cannot be ruled out however that it was his intention. 30 . What also struck me in this order was the absence of the usual salute ‘Heil Hitler!’ with which it was customary to conclude all official correspondence. a sigh of relief from Hider delivered to somebody who knew nothing of the background particulars to the occurrence. then we shall allow them this short. but be at the disposal o f‘Volk und Vaterland’. Purely subjectively. but after Himmler had inveigled his SS people into the police. ’ This ‘feeling as if newly born’ was a ‘thank God’. That would have been a breach of the political accord with France. . According to this order by Rohm. to fulfil those honourable and onerous duties which Volk and Fatherland expect of them. He spoke of ‘enemies of the SA’. and Rohm’s order to the SA of 10 June 1934. fully rested and invigorated. . This means that chief of staff Rohm had sent his 4. Hitler wished to avoid difficulties in that direction and feared that Rohm had a private political agenda. If the enemies of the SA are hopeful that the SA will not become involved after their leave. but as he did so threatened to strike out with a hefty paw. joyful respite.HE WAS MY CHIEF through some dreadful experience. After 30 June 1934 people puzzled a lot over whether Rohm really had been planning a coup. the SA ‘fully rested’ would serve not ‘Fiihrer and Reich’ as it was then the practice to say.5 million SA men on leave. has to say: ‘Thank God . Rohm probably wanted at least the status of a people’s militia for his uneasy and temporarily unemployed SA force. The last paragraph of his order reads: I expect that on 1 August the SA will be ready. or only partially. in my opinion he had not. At the time and in the manner which appears necessary afterwards they will receive the appropriate answer. Judging by the files to which I had access later.
As guests were always invited for midday and the evenings. and Schaub would explain by saying that ‘the boss is waiting for a report’. His father had owned a licensed restaurant of renown in the capital. House manager Kannenberg would ensure that we did not go hungry. So that a secretary (or often two) would be available fresh from rest. oranges and plates with various sandwiches was a delight for the eye. The Fiihrer’s household was run by house manager Arthur Kannenberg and his wife Freda. he informed me. and in the 1920s his son became the proprietor of the popular and well-loved eating house on the outskirts of Berlin known as ‘Uncle Tom’s Cabin’. When I first arrived in Berlin and was ‘on call’ with the Liaison Staff across the road from the Fiihrer-apartment. the sight of the bowls of fruit alone. with their Williams pears. Often the dictation would be postponed for days. apples. one could compare the Fiihrer household to a well-run restaurant. Schaub would give early notice of the work that had to be done. This gave rise to a secretary-on-standby service where one of us would sit in wait in the so-called Staircase Room near Hitler’s study. Kannenberg actually came from an old Berlin family of gourmets.Chapter 3 Hitler’s Dictation and the Staircase Room H in the late evening or at night because that was when he had the best ideas. I never i t l e r g a v e d i c t a t i o n m a in ly 31 . blue Brussels grapes.
Kannenberg was not only an outstanding gourmet but an excellent humorist blessed with the legendary Berlin wit. told me once. recruiting personnel for house and kitchen. ‘You took tram 76 to Hundekehle and then made a pilgrimage on foot to the beautifully positioned garden restaurant which served not only coffee and pastries but also high-quality meals in the evenings. and from then on whenever Hitler arrived at the Anhalter aboard the express from Munich with his entourage he always liked to go to Kannenberg’s and tuck into the outstanding vegetable and salad dishes which were a speciality of the house. After taking power in 1933. a Berliner and widow of art-dealer Karl Haberstock. household laundry and preparing the daily menu. Hider found his clowning and folksy musical renderings on the accordion so much to his taste that at the beginning of 1932 he appointed Kannenberg to manage the officers’ mess at the NSDAP Braunes Haus in Munich.HE WAS MY CHIEF went there myself. pay and accommodation. quiet wife Freda. reception and social rooms and the hiring of additional servants and waiters (at major state receptions these were drawn from the SS-Leibstandarte Adolf Hitler and the president’s Chancellery in livery). but Frau Magdalene Haberstock. whom Hitler employed to buy antique paintings. Goebbels recommended Hitler to visit the establishment. Hider brought Kannenberg and his nice. to his apartment in the Radziwill Palace from where the Kannenbergs ran the Fuhrer-household until 1945. the purchase and control of food and drink. Kannenberg opened another near the Berlin Anhalter railway station.’ Immediately after this restaurant went into liquidation. Their field of competence included hiring staff. The major-domo for the latter would pound the floor with his mace before announcing each guest or couple by name. daughter of a German forester. 32 . providing uniforms. Their jurisdiction extended to state receptions and all organisational matters such as the floral decoration of tables.
chairs and on the floor of the private library and in Hitler’s study. Meissen porcelain. He threatened Kannenberg with disciplinary action should he be guilty of any slip-up of this kind at a reception. Hitler would have Kannenberg set out the presents on tables. and artists and artistes whom he respected. 33 . house manager Kannenberg would select pieces of art from Berlin’s most exclusive shops for Hitler to make his choice at the Reich Chancellery. Since Hitler wanted to choose the presents for himself. On several occasions he allowed me to assist in the choice. In 1939 in conversation with an officer of the close staff who had accompanied Ribbentrop to Moscow. He was always plagued by the idea that his staff might err and so lose him prestige. Hitler often expressed his regret when taking tea with his female secretaries in the Staircase Room that as Reich Chancellor it was no longer possible for him as it had once been previously to go shopping in Berlin for presents. the officer related to Hitler how Stalin had checked the table before dinner to make certain was all in order. I said: ‘Stalin seems to have the same concerns as yourself that something might go amiss. It always gave Hitler special pleasure to send presents to people he liked and to whom he felt close. especially women with whom he had been friendly before taking power and had formed part of his social circle at that time.HITLER’ S DICTATION AND THE STAIRCASE ROOM Hitler had a great fear of committing afaux pas at receptions. Hitler would always cast his eye over the dining table to ensure nothing had been forgotten.’ Kannenberg had an important function just before every Christmas. silver trays and bowls. I can still picture these presents before me today paintings. travel necessities. Before Christmas. He said that this had always given him great pleasure in the past. For birthdays and especially at Christmas Hitler never forgot to select his presents for this personal circle comprised not only of Hitler’s closest colleagues and their wives. Before his guests arrived. but also people he knew and friends from the old street-fighting days.’ to which Hitler replied: ‘My servants are in order.
She was always able to find a blend between the colours of a painting and the flowers she put nearby. the Rothe firm in the Hotel Adlon on Unter den Linden. travel rugs. Hitler once said of him: ‘He controls the kitchen like a Pasha!’ Kannenberg was absolutely certain of his power.HE WAS MY CHIEF bracelets. recalled Kannenberg ‘turning up there with a carload of food and things. During the war. to making generous gifts from the Fiihrer-household supplies in order to curry favour with prominent individuals.’ To my question whether Kannenberg would have accepted money for it. reigned like a sovereign and was not averse. Hider would then decide from a long list of recipients who would receive what this year. every year before Christmas. he wanted to make himself loved!’ To my observation: ‘He was always a bit of a wheeler and dealer. It was all on the side. We stood there gaping. 34 . car rugs and so on. I can tell you. books and picture frames. silver spoons. The Kannenbergs were often sent to the Berghof for the visit of prominent guests and to ensure the smooth running of the state dinners. table lamps. which also indicated what everybody had received from Hider in past years. who stayed during the war as a guest with her friend Kluge on a Silesian property. opera glasses. gold watches. which at that time were very welcome. Julius Schaub kept this list. hair driers. leather trunks. Hitler received from the Iman ofYemen a couple of sacks of coffee beans as a present. Kanneberg administered a small empire. with its museum like coolness. with vivid blooms. Haberstock replied: ‘No. Everybody on his presents list would receive a few pounds of the beans. dress handbags. Flowers were delivered to the Reich Chancellery by Berlin’s leading florist. particularly during the war. coffee and tea services. Here Frau Kannenberg would decorate the Great Hall. Anybody in Kannenberg’s good books never went without coffee or other goods then subject to rationing. articles for the writing desk. Frau Magda Haberstock.’ Haberstock retorted: ‘A bit is putting it mildly!’ Kannenberg’s wife was very adept and had a good eye for the placing of table decorations and floral arrangements.
good-looking young men who wore a white dinner jacket with neck collars.4. 35 . or whatever one likes to call them.1938 SS-Obersturmfuhrer. Both were victims of Kannenberg’s intrigues. He had one particular 1 Max Wiinsche (b.HITLER’S DICTATION AND THE STAIRCASE ROOM Her arrangements always met with Hitler’s full approval.1933 joined LSSA H . Unfortunately he liked intrigue and playing on words: house manager-house manipulator was always a phrase that came to my mind when I thought about him. It was Kannenberg who engineered the fall from grace of Hitler’s long-serving chief adjutant Wilhelm Bruckner and the transfer of orderly officer Max Wiinsche1 to the Front. as an SS man highly decorated. the then modern Olympia style. 20.1940 dismissed with Bruckner by Hider. 18.8.10. Kannenberg himself was small and round. for Kanneberg felt that he ought to be able to regiment them as he did his own people. and black trousers. circumspect and of quiet demeanour.1. 1. They were seconded from the SS-Leibstandarte Adolf Hitler and after a training course at the Pasing Waiter’s School were attached to the serving staff of Hitler’s household. This cut both ways. valets and waiters. This brought them into Kannenberg’s empire.1940 returned to FH Q as adjutant. In the Fuhrer-apartment and at Obersalzberg the orderlies.1936 SS-Junker School at Bad Tolz.7. duty at Front.9. 25.4.4. 17. For him she represented the personification of the ideal German housewife.1936 SSUntersturmfiihrer. This was naturally not acceptable to the SS-Leibstandarte men and they gave adjutant Max Wiinsche plenty of opportunity to intercede on their behalf. she was well-groomed. She always styled her hair the same way.1914 Kittlitz. released 1948.6.1935-31.4. but unusually mobile.1944 SS-Obersturmbannfuhrer and regimental commander. He always reminded me of a rubber ball.1940. He had rather protuberant —even hyperthyroidic —eyes and was perhaps unstable emotionally. 11. although they were not employed by him or to serve under him. worked as servants.3.1995 Munich). detached to Hider as orderly officer and later to adjutant until 24. and without doubt the nicer half of the Kannenberg pair. 10. 24. PoW (British). 20. d. even bouncy.
Direcdy opposite the door to Hider’s study a couple of steps led to a long corridor. Kannenberg now seized the opportunity to unleash his grudge against Wiinsche. the Schneider Wibbel Stube. Later in Diisseldorf he opened a hostelry.g. which Kannenberg had brought to a fine art in the 1930s during the picnic outings. which of course had not been his. shortly before the collapse. Hider valued his technical capabilities and enjoyed his clowning. beyond which 36 . it was not surprising that in time Kannenberg would be allowed some leeway to play the fool. Bruckner had not been involved in it at all. perhaps because Kannenberg still had the knack of amusing and entertaining his guests. When Briickner took the side of Wiinsche against Kanneberg.HE WAS MY CHIEF altercation with Kanneberg on personnel matters which the latter did not forget. and fled to the Thumsee in the south. has a number of photos (e. A carefree hour in the Harz’) which show Hitler in the completely relaxed type of mood such as he rarely enjoyed later. Hitler dismissed Briickner on the spot and sent Wiinsche to the Front. Hider was delighted that everything had gone off so well and he praised Kanneberg for the excellent preparations. Hider was convinced and ordered Briickner to his presence. Kannenberg left the Reich Chancellery in 1945. Hitler abseits vom Alltag. A pictorial book published by Heinrich Hoffmann in 1937. But back to the Reich Chancellery. which attracted a lively affluent clientele. Kannenberg was ordered to Obersalzberg but did not arrive until after adjutant Wiinsche and housekeeper Josefa had got everything arranged. and Kannenberg had never let him down. Since Hitler was so anxious that everything should run perfecdy at state banquets and the annual festivals for the arts. On these occasions Kannenberg would delight Hitler and guests with his music and clowning. and had always provided the fullest satisfaction. Hitler probably realised later that he had been sold a dummy by Kannenberg but that did nothing to lower Kannenberg in the Fiihrer’s estimation. When the Italian princess Mafalda visited in 1940.
Wilhelm Bruckner used to say that ‘breakfast is the nicest time of year’ and he would readily accept any excuse to be delayed in the Winter Garden. the adjutants and servants. always pegged open. The dining hall was next to it and annexed to the elongated Winter Garden with its chintzcovered armchairs. was at the entrance to the adjutancy wing. In later years we secretaries would eat mostly in the Staircase Room which. led into the film room with its hearth. To the right was the Bismarck room. There was no difference in the menu. to the left of which wing doors. was so much to his liking that he would often come by at this hour and later came to tea almost daily. which developed quite naturally. Dr Dietrich (Reich press officer). When I was settled into the Personal Adjutancy in the spring of 1934. as I mentioned previously. The far end of the Winter Garden ended in a fine semi-circular path. We ate in the basement of the Department for Economics at the Radziwill Palace. He only used his office when Secretary of State Lammers made an appointment for him there expressly. Then one came to the rooms of Schaub.h i t l e r ’ s d ic t a t io n a n d t h e s t a ir c a s e r o o m was the so-called adjutancy wing with the rooms for Hitler’s aides. From the tall glass doors at that end one had a panorama of the trees in the Reich Chancellery park. saw us sitting there and asked if he might join us. We also took our afternoon tea there. the regular mealtimes were initially taken with Sepp Dietrich. Dr Dietrich. actually the reception room. One day Hitler happened to pass the Staircase Room. If one went beyond these and descended the staircase one came to the so-called ladies’ saloon. the SS-Fiihrers and men of the SS-Begleitf(ommando. Sepp Dietrich and Bruckner (later Alwin-Broder Albrecht). In the afternoon Hitler held most of his talks strolling its length. 37 . Breakfast was taken in the Winter Garden. The first room was the Staircase Room (Treppenzimmer) which will often be mentioned again. This hour of easy chatter. On Hitler’s orders guests and staff in the basement dining room received the same fare as was served in the dining room to the Fuhrer-apartment. also known as the smoking room.
’ he would often say. the typists’ table. It had a very high ceiling and was only used for visitors in an emergency because it had no bath. Gerda Daranowski and myself. There was no fixed eight-hour day. Usually we two secretaries would keep Hitler company. From when war broke put in 1939 we secretaries served mosdy at the current FHQ then in use. ‘How wonderful that used to be with Geli. or would touch upon later in the evening tea circle and at table in the FHQ officers’ mess. although purpose-built work rooms were planned for us in the new Reich Chancellery they proved too far away. He used to talk about the experiences of his youth and the past. later occasionally all three. namely Johanna Wolf. his bedroom and later alongside it Eva Braun’s apartment were all on the first floor of the Radziwill Palace. One felt that what he said in the Staircase Room came from a secret memory box which at all other times he kept locked shut. Actually the Staircase Room was rather functional. Once when he said: ‘You cannot 38 . Despite the simple furnishings of the Staircase Room Hitler liked it very much. We were on call twenty-four hours and had to be permanendy at Hitler’s disposal. The Staircase Room was our permanent office for when we were in Berlin. The simple furnishings were a chintz-covered couch. a safe. the library. His study. except when engaged in official conferences. only a washstand with mirror. and since Hitler stayed in his apartment. a wardrobe.HE WAS MY CHIEF The afternoon tea hour in the Staircase Room became a fairly fixed ritual. It was a place where he could relax and I always had the impression that he felt unburdened there. She would drag him into a hat shop and try them all on only to discover that none suited her. or on an alternating roster. lamp standard and octagonal table with wickerwork chairs. subjects which he might never mention again. Hider regretted very much not being able to wander the city and go shopping. we were closer to him in the Staircase Room than the new Reich Chancellery and within immediate reach.
Hitler picked up the handkerchief by its extreme tip and approached the group of teachers. As his classmates looked on. During the break the boys looked at the entry. laid his handkerchief on a small stool and left the room to converse with colleagues. mirroring the sunlight). He would have food stains on his jacket and carried a handkerchief so incredibly filthy and encrusted that he would have to tug it open before use. The master stood up. When the master returned. The professor. opened it. He won the bet by intently brushing his non-existent moustache whenever they glanced at him. the boys chanted the rhyme in unison.HITLER’S DICTATION AND THE STAIRCASE ROOM do that and just leave without buying something. He mentioned a professor of religious instruction at school who was always unkempt. He said once that his aversion to the clergy stemmed from that time.’ A much-loved activity at his school was reflecting the sun with a hand-mirror. The professor had admonished the class for not kneeling in the approved manner in church. er spiegelt mit dem Sonnenlicht’ (Hitler is mischievous. Hitler replied with a straight face that he did not know how one should kneel and would like the professor to demonstrate. as was his custom. Hitler was so keen on ‘mirroring’ that a teacher felt compelled to make an entry in the class register. Hider recalled that as a twelve year old he wagered his classmates that he could make the girls laugh during a religious service. pleasantly surprised that this boy was so interested in being taught the correct position took out his filthy handkerchief. and to their delight saw that the master had unintentionally made a rhyme of it: ‘Hitler ist ein Bosewicht. At that moment the school bell rang for break.’ In the Staircase Room he told us of the pranks he played in late childhood.’ she laughed and replied: ‘That’s what the salesgirls are there for. spread it on the floor and knelt on it. offering the handkerchief to the teacher with a smile: ‘The Herr Professor has forgotten his handkerchief. On the subject of drinking and smoking he admitted: 39 .
He went on: After our final exams I went with my classmates to a tavern to celebrate with schnapps. All my enquiries met no success. Next morning I looked in vain for my school-leaving certificate which my father wanted to see. He also spoke of his mother. or part of one. The farmer had found it in his manure heap and had returned it to my school. and so I told her that I had eaten deadly nightshade. It made me feel sick and I went to the manure heap behind the house to vomit several times. and so I went to the headmaster to request a copy. I decided that when he beat me the next time I would make no sound. [he used to say. When I read Karl May once that it was a sign of bravery to hide one’s pain. Later I bought a long porcelain pipe. to whom he was very attached. I ran home and was sick repeatedly. My mother was very concerned. I smoked like a chimney even when I was in bed. and of his father’s violence: I never loved my father. I swore to myself then and there that I would never touch another drop.HE WAS MY CHIEF As a boy I did once smoke a cigarette. That was the moment when I swore never to smoke again. Then he went through my trouser pockets and found the cigarette butt. She sent for the doctor. checked my mouth and looked at me suspiciously. Mother thought I had gone mad when I reported 40 . Once I fell asleep smoking and woke up to find the bed on fire. My poor mother would then always be afraid for me. for the headmaster produced the original certificate. and I have kept my promise.] but feared him. It made me feel terrible. He was prone to rages and would resort to violence. There I experienced the greatest shame of my youth. When it happened —I knew my mother was standing anxiously at the door —I counted every stroke out loud. who examined me.
He confided to us that when his half-sister Angela got engaged. who was older and more ebullient than I. Therefore I stayed in Vienna and my halfsister became his housekeeper on the Obersalzberg.’ In another letter dated 7 February 1957 she said: I always had to give way to my half-sister. Hitler had no sense of family. In a letter dated 29 August 1956 she wrote: ‘I did not grow out of Vienna. She was a quiet. who were simply ‘geese’ for him. rat-hunting in the churchyard with an air gun. He would criticise them for their disapproval of his favourite sport. although my brother and I had the same parents. Hider also liked to speak of the abilities of his mother as a housewife. His sister Paula was quite a few years younger than he was. In every direction in a private sense. he advised the prospective groom. who gradually increased the family property. in the true sense of the word. to break off the engagement and ‘let the stupid goose go’. 41 . and then in Berchtesgaden until her death. whom he liked. He wanted to be free and unrestricted in every direction. It was clear to me that we could not allow everybody to see that we were fighting over him. shy child and he had no great opinion of her. until after the war ended.h i t l e r ’ s d ic t a t io n a n d t h e s t a ir c a s e r o o m to her with a beaming smile. Hider said that he had the greatest respect for his father for having worked his way up from being an orphan child to a customs official. He often used to speak of his sisters. Paula lived in Vienna until the end of the Second World War. It may have been for the difference in their ages that he shut her out of his life. for my father never beat me again. That era ended in 1935. Later when he understood how hard life could be. ‘Thirty-two strokes father gave me!’ From that day I never needed to repeat the experiment.
he said. His motto Deutschland erwachel was turned by Hider into the battle cry of the Nazi Movement. came to attention in 1939 when he wrote a book. Eckart translated Peer Gynt from the Norwegian into German. two days earlier. He had met Hider at a political meeting in 1920. was a journalist and ethnic poet.HE WAS MY CHIEF On 5 February. the owner of the Briiggen fief at Berchtesgaden. his half-brother senior to him by seven years. The other son fell as an officer on the Eastern Front. born the son of a notary at Neumarkt in the Upper Pfalz. Alois Hitler had a restaurant on the Wittenberg-Platz [in Berlin] during the Third Reich but his name was never mentioned in Hitler’s presence. Eckart’s death was a heavy blow for Hitler. Eckart served time with Hider in 1923 at Landsberg prison. He was buried in the old section of the Berchtesgaden cemetery. Repeatedly when in power he would rue the death of the ‘loyal Ekkehard’ and regret that now he had the 42 . neither were the relatives at Spittal. William Patrick Hider. He once said that ‘this friendship was amongst the finest to which I was party in the 1920s!’ Dietrich Eckart. He had made his name as a theatre critic at Bayreuth and was friendly with Henrik Ibsen. which brought him much recognition. Hitler spoke frequently about the period of struggle and Dietrich Eckart. from where he was released at Christmas that year suffering from a terminal illness. This half-brother married an Irish girl who gave birth to two sons. he would rather have strangers around him whom he could pay for their services. The first of these. In later life he was never to find a friend with whom he had similar harmony in thought and feeling. spending his last days with a friend.’ Alois Hitler. Whenever he spoke of Dietrich Eckart his eyes would water. never played a role in his life. Hider always became very emotional when recounting this to us in detail. Eckart was a father figure and would often help Hider out of his financial plights. she had explained: ‘We sisters were too jealous of him in his eyes. Mon Oncle Adolphe. where he died before the end of 1923.
* August Kubizek. when he also sang as a chorister at Lambach monastery. who died in 1936. the corridor would have filled with people. and the bathroom was at the other end of the corridor. he raised his bid immediately.* he had been there when Hindenburg’s invitation reached him in 1932. Hitler went on: I had a permanent room there with running water but no bath. and with raised arms and an embarrassed smile I would be manhandled hither and thither all the way back to my room. and when he identified them as Eckart’s earliest work. Every time I was forced to run the gaundet. When I told him one day of a female friend who had inherited some handwritten poems by Dietrich Eckart from the widow of Ernst von Wolzogen. Hitler seated beside chauffeur Julius Schreck. so great was his joy at having something in his friend’s handwriting in his own hands. Adolf Hitler — Mein Jugendfreund. Leopold Stocker Verlag.HITLER’ S DICTATION AND TH E STAIRCASE ROOM power to do so he could not repay all the good Eckart had done him. summoning him to Berlin. Hitler attended school at Lambach in 1895 and 1896-8.55-6. pp. unabridged impression and reprint 2002. whom he nicknamed ‘Wolferl’. Hitler spoke a lot of the journeys he made in the years of struggle. Eckart’s former secretary. Everything connected with Dietrich Eckart touched Hitler. Hitler was very fond of Lambach. Hitler related how difficult it was on these journeys to remain anonymous. Hitler wanted to buy them at once. They would often stop for a rest at Lambach on the Chiemsee. Schreck was succeeded by Erich Kempka. When Schaub reminded him of the Hotel Elephant at Weimar. (TN) 43 . It was from his loyalty to Dietrich Eckart that he based his attachment to Johanna Wolf. for whenever I left my room the word got round like wildfire through the entire hotel and by the time I left the WC. most of which had been destroyed by his jealous wife. In the summer they always drove in the open Mercedes.
He could copy exactly the sharp laugh of King Victor Emmanuel of Italy. Money I was expecting had not been received. A ‘beaver’ was a man wearing a full beard.HE WAS MY CHIEF He described the games they played to pass the time on the drives. He liked to quote this example: I had signed a Loan Note for the Party for 40. and showed very skilfully how the king.’ That would not be the case once the first setbacks began in 1941—2. Often somebody had to be found at the last moment to redeem them. He often spoke of the financial bonds in which the Party invested earlier. for example ‘Dr Steinschneider’. he said. From Hitler’s impression one could imagine him shrugging his shoulders and gesticulating furiously with his right hand. ‘not only in the First World War. Occasionally he would imitate the speech and mannerisms of his old comrades. could stand up and appear to be of normal size. everybody realised it was a hoax and the questioners had been caught out.000 RM. He also liked to imitate foreign statesmen. and the first to do so won a point. and were signed by him. and one did not realise it was a game until one had lost. A highlight of his repertoire was his imitation of the fast-speaking and repetitive Bavarian publisher Max Amann. but also in the period of struggle. who appeared gigantic when seated. when Hitler became more reclusive and almost inaccessible. the Party coffers were empty arid 44 . The tremendous voice of the partially-deaf printer Adolf Muller was also the subject of Hitler’s mimicry. Somebody would tell a story so convincingly that the listeners were forced to ask at the end: ‘Who was with them?’ If the answer was ‘Dr Steinschneider’. and if one was spotted on the journey you had to shout ‘Beaver!” . There were no fixed rules. Another game was ‘The Beaver*. This kind of game would always put Hitler in the best of humour. In this prewar period Hitler could be merry and humorous and knew the value of humour: ‘A humorous word in a difficult situation has often worked wonders’. He was an excellent mimic.
and he confined his reading matter to history. His time there was very strictly scheduled. His religion was the Law of Nature. philosophy and biographies. films. The highway over the Bavarian Alps was also his idea. The Church was always a favourite topic. This would enable people to experience the beauty of the mountains. He placed the money at my disposal and thus enabled me to liquidate the debt on time. 1847. theatre. d. The car was to resemble a May beetle. I was considering shooting myself. From 1892 Dir-Gen. If there was a pause in the talk and we were stuck for something to discuss. 1929 guest of honour Nuremberg rally. from 1931 arranged that for every ton of coal sold by Rhine-Westfalen Coal Syndicate. painting. Four days before the redemption date I informed Frau Bruckmann of my unfortunate plight. I told Kirdorf of my plans and won him over at once to the cause. Hitler also related that at Landsberg prison he either typed parts of the text of Mein Kam pf himself or dictated it to Hess. artistry: all were an inexhaustible fund for conversation. Hitler had no affiliation. which already has his garage with it. She phoned Emil Kirdorf2 and sent me to see him. 1938). There was really no subject he had not dwelt on: architecture. Whilst in Landsberg he worked on plans for the autobahns and to make available to every citizen a four-seater car for 990 RM. He considered the Christian religion to be a hypocritical trap which had outlived its time. 2 Emil Kirdorf (b. The ideas for the VW car and the autobahn both occurred to Hitler in 1922 and he said that he had drawn up the plans for both at Landsberg. 5 pfennigs would go to the NSDAE 45 . Gelsenkirchner Bergwerke AG. sculpture.HITLER’S DICTATION AND THE STAIRCASE ROOM the redemption date on the note was coming nearer without any hope of my getting the money together. since there seemed no alternative. it was only necessary to mention any of the foregoing and Hitler was in his element. The Transalp highway from Lindau to Berchtesgaden was the second point of his programme.
self-sacrificing ladies of high society. although he intended to renounce membership as soon as the war ended. the law of the jungle has been in force from the beginning. Man. He said that it reinforced in him the impression ‘that he was being eyed-up like an ape in a zoo’. One day after the renovation work at the Radziwill Palace. whose photo at the time wras 46 . ‘The mass service will make it possible to have very festive ceremonies. and above all the Church. We are a limb of Creation and children of Nature and the same laws apply to us as they do to all living beings. On the subject of the closing ceremonies at the Nuremberg rallies he once said: ‘The closing Congress must be as solemn and festive as the Catholic mass. In Nature. I was called to the Reich Chancellery apartment in the late morning. Scarcely had I sat than the waiter Karl Krause led in a very young and pretty blonde. The bringing in of the standards. the whole ceremony should be planned like a ritual of the Catholic Church. and the weak. We are probably the highest stage of development from some mammal or other which had developed from the reptile.’ He also planned mass marriages with 50—100 couples. and then perhaps through the apes to the human being.’ Great music bands. I was asked to take a seat at table.HE WAS MY CHIEF Science has not yet decided from which roots the human race sprang forth. This act would have a symbolic significance: for Germany the end of an historical epoch and for the Third Reich the beginning of a new era. He also spoke of the motherly. have made it precisely their goal to keep alive by artificial means the weak. those unfit for life and the invalids. This was the baroness Sigrid von Laffert. and he remained to the end a Catholic. Hitler was clever enough to know that he could not destroy the moral high ground which religious belief provided. Hitler was at breakfast with his adjutants in the dining room. are trampled underfoot. flower decorations everywhere. in whose salons new contacts would be made. All those unsuitable to live.
Since he made lively hand and arm movements to emphasise points he was making in his speeches. an ambitious 150 per cent National Socialist who once managed to inveigle a twentyone-year old relation. and also liked to extend his body while strolling in conversation. 4 Hitler’s wardrobe came almost exclusively from the Wilhelm Holter’s gendeman’s outfitters on Wilhelm-Strasse 49. Berlin. peered at curiously by everybody as an attraction. saying something like ‘Here comes my sunshine’ or ‘The sun is rising’. During the putsch of 9 November 1923 Hider fell to 3 Wilhelm Heyne Verlag. Hitler found her there. but did no more than politely request her to dress and leave the room. p. however. This occasional raising of the right shoulder may have been due to the left shoulder being stiff. pretty as a picture. He was pleased by her pretty niece and took a few steps in her direction. he had an aversion to a close fit. but better known as the niece of Hitler’s patroness Viktoria von Dirksen. In any case. 47 . naked into Hitler’s bed at the Reich Chancellery. His tailor4 had to shape all uniforms and suits for comfort in this regard. He hated trying things on.27. especially when the subject was one which excited him and which he did mainly by raising the right shoulder. his attraction to Sigrid von Laffert could not be missed. I cannot be sure any more. Hider’s clothing was purely functional. and neither could it be hidden from Eva Braun in Munich. In later years in the Staircase Room he would make remarks about the invitations and say: ‘I felt there like an exotic zoo animal. Viktoria von Dirksen ran a political saloon in which Hitler was often centre-stage. David Irving related the following anecdote about her in his very superficial analysis How Sic\ was Hitler Really?'? ‘There was for example Viktoria von Dirksen. Munich 1980.HITLER’S DICTATION AND THE STAIRCASE ROOM gracing the title page of the Berlin Illustrierte under the heading ‘A German Girl!’ She was the daughter of an officer from Doberan in Mecklenburg.’ At this time he was probably still enjoying the invitations of Her Excellence.’ This was a fable.
The shoulder was therefore never properly fixed and remained stiff ever afterwards. polished like a mirror. They could look friendly and warm-hearted. dislocating his left shoulder. I found his eyes expressive. As soon as he entered a room everybody present would notice him. clear. and in conclusion. but also excited increasing in volume and overwhelming in aggression. for it contrasted with the free and unforced approach one expected. when he went to greet somebody. ‘I am totally indifferent to what the future will think of the methods which I have to use. ‘Ice-cold’. Dr Walter Schultze. and then traverse his large study to get to his desk’. almost ceremonial. They looked mostly as if interested and searching. Looking back this seems to have been because he never hurried. Although with this slightly lop-sided posture and ample jacket Hitler did not exacdy cut an elegant figure. which I often had cause to notice. This tended to induce in the other person a feeling of uncertainty. Hitler feared being ‘bumped off’ at the hospital. and rather bulging. he still commanded respect. exact and convincing. ‘Ruthless’ (riic^sichtslos) was common in his vocabulary: ‘Force it through ruthlessly. pale light blue. It could be unusually calm. husband of Ada Klein and leader of the SA medical corps. ‘simply idiotic!’ 48 . and became increasingly animated during conversation. Often it would be ice-cold. or ‘Now I am ice-cold’ were much-used phrases of his.HE WAS MY CHIEF the pavement.’ I heard frequently. indifference and disgust. His manner of walking was always measured. whatever the cost!’ Other phrases to crop up a lot were ‘with brute force!’ and ‘with brutal energy!’. or express indignation. Hider had always to be the controller! He mentioned frequendy for example: ‘how uncertain it made visitors to the new Reich Chancellery to have to cross the long marble hall. One could always tell his mood from his voice. In the last months of the war they lost expressiveness and became a more watery. could not convince Hitler to have it X-rayed.
but that is impossible. He had wisely grown a small moustache to cover up his very thin lips. I would buy several of the same kind. His adjutant Schaub would settle everything. to go with the uniform. Even his gold watch he carried loose in his jacket pocket. Imagine my face without a moustache!’ and at that held his hand below his nose like a plate. During the years of his friendship with Ada Klein5he told her: ‘Many people say I should shave off the moustache. but by 1945 they were yellow and he had bad breath. when paying off a taxi he would always give a big tip ‘almost equivalent to the fare’. During a flight a photographer. I need the moustache to relieve the effect!’ I liked his hands. they spare on tips!’ It amused Hitler that there were men always looking for new ties. It was always a few minutes fast so that he arrived at meetings and conferences punctually.HITLER’S DICTATION AND THE STAIRCASE ROOM Hitler’s nose was very large and fairly pointed. From 1933 Hitler avoided personal contact with money which seemed in some way repugnant to him. He placed no value on having a variety of dress styles.’ he said once. although he could deliver a surprising commentary on a dress and pay compliments to the lady wearing 5 See Chapter 10. According to Ada Klein. either in motion or at rest. 49 . I do not know whether his teeth were ever very attractive. Later he only ever wore black ties. He doubted the reliability of his waiters and adjutants although he was perpetually asking them for the time. but had a cared-for look with their short nails. ‘My nose is much too big. Over the years the joints got increasingly thicker. perhaps Heinrich Hoffmann himself. They were not manicured. Hitler never wore personal jewellery. ‘When I saw a tie I liked. He rarely spoke on fashion. She repeated his often-expressed conviction: ‘Rich people are tight. Before 1933 he carried a wallet and put loose coins in his jacket pocket. took a very fine photograph showing Hitler’s hands on the armrest of his seat.
He did not like the sun and had bought the Berghof precisely because it was situated on the north side of the Obersalzberg. During the 1933 Nuremberg rally I was summoned there and ordered to the Deutscher H of Hotel where Hider dictated to Johanna Wolf and myself that night the speeches he delivered next day. He did not like horses and hated snow (especially after the winter of 1941). although his guests found it unpleasant. I do 50 . he looked into my eyes. but when he did he could be very angry. but that ‘a strong will’ was also needed. He would go to town on certain dress crazes. Hitler rarely had occasion to remonstrate with his servants. and cold when it rained. I often heard him say in admiration to Eva Braun: ‘Ah. come on. He bathed daily. Even in summer it was unusually cool. such as shoes with cork soles. and sunshine made him feel bad.’ Hider set great store on hygiene. The house was in shadow all day. Additionally he would always try to look every man in the eye to give him the feeling that the Fiihrer had seen him. you’ve seen it before. Probably he always shaved himself. particularly after meetings and speeches. Hitler was very strong-willed. I’ve worn it often enough. from which he would return sweating. He was afraid of water. you are wearing a new dress!’ and she would reply indignantly: ‘Oh. as when Karl Krause forgot to take out the pins from his shirts one day. During a tea hour he revealed that he had ‘done daily training with an expander’.’ One must mention that Hitler did no sport. often several times a day. We watched from the hotel window as Hider saluted the march past by the SA. At the beginning of the 1930s his clothing was sent to a large Berlin laundry which would put pins into the upper part of the shirts to retain their shape. and the thick walls made sure no warmth got through from outside.HE WAS MY CHIEF it. but I am convinced it was all done for some purpose or other. A manservant would not have been called upon to do much for him. His skin was very soft. Often one actually heard it said: ‘The Fiihrer saw me. Hitler loved this cold. SS and RAD (Reich Work Service). I was surprised that he could stand for hours at a stretch with his arm extended.
about that there is no doubt. He possessed extraordinary powers of suggestion. When surprised visitors saw his trembling hand. and this was no doubt the reason why people who came to him in desperation went away reassured. He had the power to relate something so convincingly that he fascinated his listeners. even if I run the danger of being ejected. he replied: ‘You can rely on it. The knowledge from 1944 onwards that he was no longer master of his own body was a heavy burden. He could expound even the most complicated subjects clearly and simply. (TN) 51 . he would cover it instinctively with the other. Harsh and inflexible as Hitler could be with others. p. When I encouraged him to do so. Forster was determined to hold nothing back and tell Hitler the whole truth about the situation in Danzig.’ Undoubtedly he knew how to charm a person under his spell during conversation.’ he said in relief. he did not exempt himself He never spared himself. Hitler was a ‘tolerably good swimmer’ and one day dived into the river Rodel to save Kubizek’s mother from drowning after she slipped from a rock. but he assured me that Danzig will be saved. He told me that Danzig was surrounded by 1. and these were short of fuel.’ Such were Hitler’s powers of suggestion. I am going to tell him everything.HITLER’S DICTATION AND THE STAIRCASE ROOM not believe he could swim. I remember that in March 1945 Gauleiter Forster came from Danzig totally demoralised.34.100 Russian tanks and the Wehrmacht was opposing this force with four Tiger panzers. Leopold Stocker Verlag 2002. He was a prisoner to the delusion that an iron will could succeed everywhere. He would reject tiredness and would call upon endless reserves of energy.’ To my surprise he returned from his talk with Hitler a changed man. He countered my doubting smile: ‘I admit I have no idea where he will be getting them from. ‘The Fiihrer has promised me new divisions for Danzig. Despite * According to Kubizek. Adolf Hitler —Mein Jugendfreund. No wonder that the trembling left hand was such an embarrassment to him.* One day he told me: ‘The movements a person makes while at his daily work is enough to keep his body in shape.
1924 sentenced to fifteen months’ imprisonment for participation in the putsch of 1923. From his youth onwards Hitler had a great lust to read. Nobody could have gauged how deeply the blow had struck him. churches. He told me one day that during his youth in Vienna he had read through all 500 volumes at the city reference library. 31. active in Hider’s storm troops. by 1930 NSDAP Reichsleiter. He would often say: A secret shared is no secret.11.12.1933 Oberbiirgermeister of Munich until 1945. and to assimilate contents of the most diverse kinds. In the same way he could describe with amazing detail how theatres.8. enabled him to extend his knowledge into almost all areas of literature and science. Should bad news arrive during a private conversation the only clue would be a movement of his jaw and he would carry on calmly.1895 Braunschweig. but that was all. 1945-16. I remember him receiving the report about the destruction of the Mohne and Eder dams. 5.3. 8.1949 interned.’ The Oberbiirgermeister of Munich6 with whom Hitler enjoyed discussing the expansion and beautification of the city related 6 Karl Fiehler (b. As he read it his face turned to stone. Yet to the end he remained master of his emotions. 52 . monasteries and castles were built.1969 Munich). With equally astonishing self-mastery he kept his secrets. which flooded much of the Ruhr. This passion for books.4.1.’ He never spoke of his secret intentions and plans nor dropped hints about an impending military operation or suchlike. He was convinced that nobody should know more than what was needed for the discharge of his or her office.HE WAS MY CHIEF every effort of will he could do nothing to stop the trembling. d. 28. I was always amazed at how precisely he could describe any geographical region or speak about art history or hold forth on very complicated technical matters.1923 joined NSDAP. Even during his incarceration at Landsberg he studied tirelessly the historical buildings of all European countries and would often boast that he ‘knew the architectural beauties of those countries better even than the experts who were native to them. 20. It would be hours or days before he would refer to such an event. and then give full vent to his feelings.
If he was in a good mood he enjoyed describing the great receptions at the Reich Chancellery. and on reflection surprising personal details might also occur to him. and repeat the serious or light-hearted conversations he had had with his guests. place and circumstances under which he had met a person. of the First World War. The friends of his youth in Vienna. but his secret was that he trained and expanded it every day. books and statistics. He could remember exacdy the time. It is confirmed that from his youth onwards Hitler had the gift of an unusual memory. He would mention the names of actors and recall how the critics had treated them. I have asked myself very often how a human mind can have retained so many facts and impressions. a fact confirmed by architects Speer and Giesler postwar. Hitler could not only recall very easily names. He could see in his mind’s eye what dress this or that artiste had worn. He retained a mental image of all persons whom he had got to know in his life. It was no different with his impressions of theatrical presentations or films: he could describe a scene he had watched in Vienna as a young man down to the last detail. Hitler seemed able to follow a conversation in English or French if it was not spoken too quickly but explained: ‘I have not made the effort to be fluent in a foreign language because in talks with 53 . Hider had reproached him: ‘Six months ago I told you I wanted to have it done this way!’ and then repeated word for word the conversation they had had on the subject. but faces too. the period of struggle and the seizure of power were all deeply embedded in his memory with all their peculiarities.h i t l e r ’ s d ic t a t io n a n d t h e s t a ir c a s e r o o m how surprised he was when Hitler recalled the minute details of a conversation they had had months previously. It was his practice or method during the tea hours and when chatting at the hearth over a subject he had been reading about to repeat it several times in order to anchor it more firmly in his memory. Equally he could describe the atmosphere and sequence of events at rallies at which he had spoken. He said that when he was reading he tried to grasp the essence of a thing and fix it in his mind.
buildings and theatrical plays without actually knowing or having seen them. To my astonishment I realised that he was reciting a page from Schopenhauer which I had just finished reading myself. He answered: ‘You are right. He could recite pages and pages of books and so give the impression that his ideas had evolved from his own comprehension. While my interpreter translates. about cities. taken a litde aback. that all knowledge comes from others and that every person only contributes a minute piece to the whole.’ Despite the effort Hitler made to surprise people with his rich trove of knowledge. must have convinced his listeners that he actually knew all this from his own experience. Once I began working for him. I wanted to get the thing straight. threw me a glance and then explained in fatherly tones: ‘Do not forget. and the clear dialectic with which he formulated his thoughts. I therefore asked him how he could judge the director and performers if he had not been present. I gain time to think of new. and to show them his superiority. Hider. One day he delivered a damning criticism of a theatrical presentation which I knew he had not seen. but Fraulein Braun was there and told me everything. Nearly everybody with whom I discussed it was convinced that Hider was a profound thinker.’ In the same convincing manner Hitler spoke about famous men. The confident and decisive manner of expressing himself. analytical spirit. and a wonderfully sharp. He was expert at convincing his listeners that everything he said was the result of his own deliberations and critical thinking. one was forced to draw the conclusion that everything he described in his narratives with such astonishing precision he had thought through or experienced personally. he made sure he never let them know the sources of this knowledge. my child.HE WAS MY CHIEF foreigners every word counts.’ 54 . foreign countries. Summoning all my courage I drew the fact to his attention. One day Hitler launched into a philosophical dissertation on one of his favourite themes. appropriate ways to phrase a thing.
That also happened if he mentioned Churchill or Roosevelt. Interestingly enough. before Lenbach’s portrait of Bismarck. I would simply omit some of the references. working on the punch lines for a speech. gathering himself as it were before resuming his wandering. For my part if he mentioned the ‘whisky-guzzler’ (Churchill) or the ‘bloodhound’ (Stalin) too often. His word flow would be stemmed again as he paused before the commode. and he would make lively gesticulations with his hands. when reading through the draft he would never notice these cuts. A while would pass in silence.HITLER’S DICTATION AND THE STAIRCASE ROOM Back in the Staircase Room I would wait on standby until a valet shouted through the wing door: ‘The chief is asking you to come for dictation!’ Therefore up and follow the valet. a sign of how worked up he had been. Then he would close in on the typewriter and begin to dictate calmly and with expansive gestures. Occasionally he would halt. over-pitch so to speak. After staring at it for some time.’ As a rule Hitler would be standing at or bent over his desk. Then his choice of words would not be so fussy. Gradually getting into his stride he would speak faster. emotion would take possession of him. Without pause one sentence would then follow another while he strolled around the room. He would open the door to the library and shut it as he withdrew. Often he would appear not to notice my presence. During the dictation I often found my heart racing as Hitler’s excitement spilled over me. He would stand rooted to the spot as though confronting the particular enemy he was imagining. It would certainly have been 55 . for example. In these situations his voice would increase to maximum volume. lifting up to admire one of the small bronze figurines. If he touched upon Bolshevism in his speech. and I doubt whether he saw me as a person when I was at my typist’s desk. lost in thought. he would replace it. His face would become florid and the anger would shine in his eyes. Before the dictation I would not exist for him. hanging a notice on the latch: ‘Do not disturb. His voice often skipped over bits.
HE WAS MY CHIEF
easier to have taken this dictation in shorthand but Hitler did not
want this. Apparently he felt himself as if on wings when he heard
the rhythmic chatter of the typewriter keys. Besides, he had before
his eyes the written record of what he had just said. During the
dictation he spoke no private words.
These dictations were as a rule speeches for the Reichstag, for
meetings, Party rallies, at opening ceremonies for car, artistic, farming
or technical exhibitions, for foundation-stone laying ceremonies,
opening ceremonies for completed stretches of autobahn, for the
New Year reception of diplomats and so forth. Also letters to foreign
heads of state such as Mussolini, Antonescu (Romania), Horthy
(Hungary), Inonii (Turkey) and Mannerheim (Finland) were
dictated. He dictated private letters only when protocol demanded
it, to thank somebody or offer condolences. He would send birthday
greetings to Frau Goebbels, Frau Goring, Frau Ley, Winifred Wagner
and others on handwritten white cards bearing his name in gold
lettering below the eagle and swastika in the top left corner.
Dictating into the typewriter required extreme concentration.
One had to follow his sense, and apply some intuition, for fragments
of his sentences were often lost. He would start off by speaking none
too clearly and his voice often echoed as he strolled the large room.
Additionally the typewriter had its own mechanical noise. In those
days of course there were no electronic machines. As Hitler would
never be seen wearing spectacles in public, typewriters were later
manufactured with 12-mm characters so that he could read the
script in public without glasses. The ‘Silenta’. This would result in bated breath while
watching Hider correcting the draft afterwards.
56
HITLER’S DICTATION AND THE STAIRCASE ROOM
When the dictation was finished, Hitler would occasionally
sit at his writing desk, put on his gold-rimmed spectacles, take up
the fountain pen from the old-fashioned black penholder and start
changing words, striking some out, inserting new ones, and all
scrawled in his Fraktur style. From time to time he would look up
and say: ‘Look here, child, see if you can read this!’ When I assured
him that I could, his voice would sound a little disappointed: ‘\es,
you can read it better than I can!’
Correcting the draft was a labour which never ended. After every
assault on it the modified version had to be retyped. More than once
I had to run to his car to hand over the last pages. At that time there
was still the personal contact with him. Once when giving him some
pages before he left for the Reichstag I asked him not to speak so
loud because the microphone distorted his voice if the volume was
too great. In 1937—8 Hider would receive that kind of advice without
demur. Every secretary had ‘her time’ when she would be favoured
by him over a longish period. On one occasion I did not like the way
he had phrased something. When I dared mention it, he looked at
me, neither angry nor offended, and said: ‘You are the only person I
allow to correct me!’ I was so astonished, perhaps also disbelieving,
that I forgot to thank him.
From the outbreak of war Hitler would never deliver a speech
without a manuscript. ‘I prefer to speak, and I speak best, from the
top of my head,’ he told me, ‘but now we are at war I must weigh
carefully every word, for the world is watching and listening. Were
I to use the wrong word in a spontaneous moment of passion, that
could have severe implications!’ Only internally, before Gauleiters,
the military or industrialists, did he speak freely and unscripted.
Once he had finished the outline of a speech he would seem to have
thrown off a burden. If he dictated it during a stay at the Berghof,
he would announce the next day at lunch that his speech was ready
and he expected it to be well received. Then he would heap praise
on the skill of his secretaries or, as he called us at the beginning, ‘his
57
HE WAS MY CHIEF
writing force’. Often there would be two of us together when one
would relieve the other after a couple of hours of dictation, and he
would praise us: ‘You write faster than I dictate, you are true queens
of the typewriter!’
He liked to relate the difficulties he had had in earlier years when
he needed to dictate something during a visit to a Gauleiter, for
example. ‘Mostly the girls would get so excited when they saw me,
blushing furiously, and would be unable to do the work as I wanted.
When I noticed that I would break off the dictation pretending that
I had to wait for some report or other before I could continue.’ I
found this tactful of Hider, for it was not easy to work for him. ‘Shall
I demonstrate my own typing skills?’ he joked. ‘I do it more or less
like this.’ And then he would pretend he was seated at a machine
ready to type. He would flex his imaginary sheet of paper, straighten
it up carefully, adjust the platen with the knob at the side and then, to
the laughter of the onlookers, begin typing with his forefingers, not
forgetting to use the carriage lever, space bar and upper case keys as
the occasion demanded. He aped the movements so accurately that
no professional mime artist could have done it better. Undoubtedly
he had great talent as an actor and people-impersonator.
58
Above: Hitler’s secretaries Christa Schroeder and Johanna Wolf at breakfast,
Haus Wachenfeld, 1935
Below: Dr Goebbels, Eva Braun, Karl Han\e, Christa Schroeder and Albert
Speer waitingfor Hitler, Berghof terrace, 1938
Dr Lammers. Hitler. Heinz Linge. From left. From left. an adjutant.Above: At the Hradschin in Prague on 16 March 1939 Hitler signed the edict creating the Protectorate of Bohemia and Moravia. Schaub. Christa Schroeder and Gerda Daranowskj congratulate Hitler on his 50th birthday. Dr Stuckart and Christa Schroeder Below: In the Reich Chancellery. 20 April 1939. Gerda Daranowskj. Dr Fric\. Christa Schroeder and Hitler .
1940 Right: Christa Schroeder at her typewriter at FHQ Wolfsschanze . Gerda Daranowski and Christa Schroeder in conversation with Hitler at the Berghof. New Year’s Eve.Above: Hitler’s personal physician Dr Theo Morell. Wilhelm Briickner.
Above: Christa Schroeder examining Hitler’s world-globe in the Berghof ‘Great Hall’ Below: Hitler’s guests. Adolf Wagner. Margarete Braun. Dr Dietrich: upper right is Heinrich Heim the stenographer who copied down Hitler’s monologues. Heim really did belong within Hitler’s inner circle . Eva Braun. New Year’s Eve 1940. Christa Schroeder. Berghof. Front rowfrom left: Wilhelm Bruckner. Hitler. Contrary to what many assert. as this photo shows. Great Hall.
1941. Walter Hewel. 20 September 1942. Albert Bormann. Christa Schroeder. behind her is Dr Morell Below: Hitler’s intimate staff in the officer mess at FHQ Wehrwolf near Winniza. Julius Schaub . unknown.Right: Hitler dictating to Christa Schroeder at FHQ Wolfsschanze. From left to right: Nicolaus von Below.
Rastenburg in East Prussia .Above: Hitler exercises his Alsatian Blondi in the open meadow east of the Wolfsschanze. August 1943 Below: The Wolfsschanze''s Fuhrerbunker. c.
This photograph shows Hitler with his would-be assassin Claus von Stauffenberg (far left) at the Wolfsschanzejust afew days beforehand on 15 July 1944.The Wolfsschanze was the location of thefailed bomb plot of 20 July. During this meeting Stauffenberg had a bomb with him but it did not detonate .
Above left: From 1936 Hitler’s home in Obersalzberg became known as the Berghof Along with the Wolfsschanze this was the place where Hitler spent most of his time during the war and was one of the main headquarters Above right: Hitler with the Berghof in the distance Below: Hitler walking out of the Berghof with Goebbels to his left .
Hitler’s principle of keeping a plan secret to the last possible moment kept us under constant pressure. For this reason we had almost no personal freedom and were on call day and night. During the long period of waiting for the announcement we would always be on tenterhooks. Even when officially off duty we had to leave a phone number where we could be reached. and existed only when the opportunity for it occurred. either Fraulein Wolf or myself Our private life was very curtailed. The trips and excursions were probably always arranged well ahead but Hitler would only announce the time of departure at the last minute. however. Hitler would put on his surprised face and U p to 59 . Even when I was taking the cure I was often recalled just to take a single dictation. Hitler knew that he weighed us down with work but did not care to enlarge the pool of secretaries because he could not stand having new faces around him. on another occasion sitting in the stands on the Odeon Platz during the October Festival I heard a loudspeaker announcement: ‘Fraulein Schroeder should report immediately to the Prinzregenten-Platz’ (Hitler’s flat). If someone ever passed a remark about how little free time he left us.Chapter 4 Travelling With Hitler 1937 H i t l e r would only take one secretary with him on his travels. Once in the train to Hamburg I was ordered by radio message to take the next train back.
HE WAS MY CHIEF assure them: ‘I allow everybody in my circle their Freedom/ but in reality he would not tolerate anybody daring to go their own way. At that time I was certainly his No.’ Receiving the same treatment. 60 . as we called her. Hitler was delighted by her skill with cosmetics and would pay her the most unfettered compliments. Since I was very economic with make-up he once glanced at me (probably hinting that I should give myself a beauty spot): ‘.’ he smiled. and knew how to goad Hitler into talking at tea. in the Staircase Room and when travelling in the Mercedes. He pressurised the senior surgeon. Sometimes she had been called to the Personal Adjutancy to take down speeches because my colleague Johanna Wolf was often off work sick: now she transferred in permanently. Dr Stoeckel. All his secretaries had a time when they were ‘in’ with Hitler. Hitler visited me the day before Christmas Eve in company with Dr Brandt and his chief adjutant Bruckner. From her work with Elizabeth Arden. and now I shared Hitler’s favour with Gerda Daranowski who had previously worked at the Private Chancellery. In 1937 a new secretary joined us. and a book with his dedication written on the fly-leaf In good humour he told me that as he got out of the car in front of the Women’s Clinic in the Ziegel-Strasse a small crowd gathered. ‘Everyone who saw me go through the Women’s Clinic will definitely think I am visiting a friend I got pregnant. . She was a young Berliner. because he needed me urgently.. and Schroeder has the intelligence of an aboveaverage man. When I was confined for several weeks at the Berlin University Clinic in 1938. we were a good team in those years. He presented me with a bouquet of long-stemmed pink roses which it was his custom to send. knew how to give her face just the right look to excite a man. a little after the invasion of Russia. into promising to do all he could to get me well again. not only very capable but attractive and always well-humoured. Dara. I was ‘in’ until 1941-2. 1 stenotyist.
Thousands of Viennese waited outside the hotel.TRAVELLING WITH HITLER Dara and I accompanied Hitler on his journey to Austria at the annexation in March 1938. Dara and I took only the rare orchids and put them in the Mercedes for the drive back because they lasted the longest: the car was a sea of blooms. ein Ftihrer (meaning ‘One People. I remember particularly the people of Linz who crowded before the Hotel Weinzinger until the late hours chanting ‘Ein Reich. When the enthusiasm had not abated by midnight. of course. yet Schroeder recites it incorrectly here as 'Ein Reich. It was overwhelming. That was not the impression I received when I saw the enthusiasm with which Hitler and the Wehrmacht were greeted in Austria. Hider did not occupy the VIP suite —he used this only for official purposes —but had instead a small apartment on the first floor decorated in the Schonbrunn baroque and completed with a magnificent floral arrangement. And Hider showed himself. It may be a simple typographical error. After that it gradually grew quieter. 61 . ein Volf{. Schaub whispered to me: ‘He needs the shout of jubilation just like the artiste does his applause. The almost hysterical outbursts of joy got on one’s nerves. typical Viennese sprays of white lilies and pink roses. The most glorious bouquets of flowers were handed in at reception for Hitler. ein Ftihrer. again and again. the 55Begleit^ommando was told to ask for quiet and get the crowd to disperse. one Leader’) was one of the most renowned of the Third Reich. After 1945 it was loudly asserted that Hitlef had dragged Austria ‘home into the Reich’ against the will of the people. Next day Cardinal 1 The slogan 'Ein Volk^ ein Reich. but it may also be indicative of Schroeder’s lack of political awareness. never tiring of calling for Hitler to emerge and speak. and the most precious orchids. It was still quiet next morning. When he left the hotel to no ovation he was clearly annoyed.’ From Linz we drove back to the Hotel Imperial in Vienna. ein Vol\. This did not seem right to Hitler. one State. ein Fuhrer!n and the ending chorus pleading for Hitler to show himself at the hotel window.
Between 2 and 9 May 19381was the only secretary in the Fuhrer’s special train3for the state visit to Italy. 1 saloon coach (the Fiihrerwagen) consisted of a wood-panelled saloon with bed compartment. I remember the wood-framed bay windows which went almost to 2 Theodor Innitzer (b. 2 coach was the military command coach in which the situation conferences were held. 3 coach was the diner. and the other at the tail of the train.1933 Cardinal. By 1943 it had no less than forty coaches available. coaches Nos 4 to 9 were sleepers for the SS-Begleitkpmmando. Hitler \outh had strewn the Wilhelm-Platz with flowers. Armament was a 2-cm quadruple barrelled weapon. guests and the OKW Hider used the train as his FH Q during the campaigns in Poland and the Balkans.1955 Vienna. It was all rather too much for me. including to the Spanish border for his talks with Franco in 1940. 62 . On our return to Berlin the jubilation of the population was deafening. they waved flags and applauded loudly as Hitler drove past. The flak wagons were positioned one between the locomotives and the leading coach. No. draping them from the tree tops. from 1938 also a command coach and two flak wagons. Crew o f each was twenty-six men. My colleague Johanna Wolfwas on Rudolf Hess’s special train for the trip to Rome. The radio rooms and telex centre were located aboard. d. During the Russian campaign it was stationed at Gorlitz within FH Q Wolfsschanze.HE WAS MY CHIEF Innitzer2 visited Hitler at the hotel. From 1937 it was stationed at Berlin Anhalter Bahnhof and had ten coaches initially. She was attached temporarily to his staff My younger colleague Gerda Daranowski came by plane. Hitler’s staff. 9. 13. Johanna Wolf and I stayed in the Quirinal in rooms between the ground and first floors apparently meant for staff. Hitler was very impressed by this visit and kept referring to it during our conversation at tea. We had to endure similar receptions in 1938 on the return from Italy.1875 Neugeschrei/Erzgebirge. 3 In 1933 as Reich Chancellor. Hitler ordered a special train built. Named America it was drawn by two steam locomotives (usually BR S 05). and travelled across France in it on several occasions. 25. No. Kripo. in 1939 from Prague and later following the successful military campaigns in Poland and France. when Hitler was at the peak of his power.10. It was destroyed on Hitler’s orders at Mallnitz on 1 May 1945. bathroom and small compartments for the manservant and adjutants.3. No.12.
We saw nothing of the parades in Rome held in Hider’s honour. Hitler used to say of this encounter later: ‘I was just about to say to the Duce what beautiful women there are in Florence when I recognised my secretaries. laughed and saluted. The Vatican was closed probably because of Hitler’s visit(?) but there was so much to see in Rome that Dara and I decided not to go to Naples for the naval review and went instead to Florence because the journey home was to begin there. Hitler had been inspired by Italian art. Hitler found the dryness and arrogance of the nobility a challenge to his self-control. both in the positive and negative sense. then change the text. less so by the court ceremonial. Ribbentrop was watching him. As we strolled the Ponte Vecchio a coach containing the Duce and Hitler and drawn by the finest horses came towards us. The Italian visit was the main topic in many subsequent conversations.’ Scarcely had Hitler’s special train steamed out of Florence for the journey home than Hitler was dictating telegrams thanking the Italian king and the Duce. We were served exquisite vegetable dishes prepared with oil and easily digestible. but once we were driven by the chauffeur of Italian Crown Prince Umberto to Tivoli to see the wonderful gardens of the Villa d’Este. The Duce did not have the same leading role in Italy as Hitler did in Germany and had no influence on the protocol. We waved. We were cared for by a round signora dressed in black who curtsied whenever she spoke to us and tended our needs. During the military parade in Rome seats had been reserved for 63 .TRAVELLING WITH HITLER the floor. The demeaning treatment ‘those courtesans’ handed down to the Duce outraged Hitler. Hitler said: ‘If you can find a better way of putting it. As he said. he had to suppress his instincts to break off the state visit prematurely because of the way in which Mussolini was continually humiliated.’ Ribbentrop then re-dictated the telegrams at least ten times but despite his best endeavours in the end he settled for the text Hitler had had in the first place. the buildings and military parades.
’ Just a couple of hours later we were aboard Hider’s special train and heading for Czechoslovakia.1939 signed the Berlin document making Bohemia and Moravia into a protectorate o f the Third Reich.HE WAS MY CHIEF the members of the royal house and for Hitler while Mussolini was forced to stand the whole time. a happy expression on his face. Czechoslovakia. 1939 Czech state president. but gathered ourselves and complied warmly with his wish.’ he went on. Shortly before Czechoslovakia was incorporated into the Reich in 1939. I shall go down in history as the greatest German.6. We were to hold ourselves in immediate readiness should dictation be necessary during the conversation. Gerda Daranowski and I had to sit in a small office concealed by a door behind Hider’s desk. ‘I have achieved something which has been striven for in vain for centuries.’ Since he had never made such a request of us before we were rather taken aback. children. We sat and sat. Vienna.1945 in a Prague prison). and the hours went by. d. ‘This is the finest day of my life. ‘That made me so indignant that I almost made a public fuss. 27 May 1945 as state president o f Bohemia and Moravia arrested by the Allies. I have succeeded in unifying Czechoslovakia with the Reich. Before Hacha was ushered in.’ pointing to his left and right cheeks. exuding a superabundance of endless joy: ‘So. Shortly after 0430 the door opened at last. 26. 64 . ‘each of you give me a kiss.7. We got out at Leipa in Bohemia where the great convoy of Mercedes from Hider’s vehicle park was 4 Emil Hacha (b.1872 Budweis.3.4 came to Berlin for a conference. Hacha. 1925 president of administrative court. The basis for his grudge against the Italians was founded in Rome on this visit and not later by the surprises which they had in store for him in the war. Hacha has signed the treaty. The talks took place on the night of 14 March 1939 in Hitler’s large study at the new Reich Chancellery. now there and there. the Czech state president. 12. 15. Only for the Duce’s sake did I exercise restraint/ he said. and Hider swept over the step. Standing in the centre of the room he said.
We returned to Berlin on the Fuhrer-train on 19 March. Inside the Hradschin it was like an army camp. In Prague we went to the Hradschin fortress. for he pulled a face and said that it was ‘too bitter’ for him.TRAVELLING WITH HITLER already waiting. like a fairytale casde set deep in snow above the houses of the city. From 1939 onwards we did more travelling. In contrast to earlier years when Hitler nearly always went by car. It was difficult for the Czech officials in the Hradschin to hide their hatred for us. now he began to extol the greater comfort of his pleasant. and about two in the morning the SS bodyguard went to the Deutsches Haus in Prague and rustled up some white bread. The great wrought-iron gates were shut. Many years later I chanced across a photo of myself which appeared at the head of a series o f ‘Christa Schroeder Exclusive’ articles in Corriere della Sera. however. This made Hider curious and he asked for a glass. 65 . In collaboration with interior minister Frick and Secretary of State Stuckart. He was in the best of spirits and presented me with a bouquet of long-stemmed roses which he had ordered by wire to be sent to a station along the way. We did the food justice and praised the icy cold beer. ham and Pilsner. Snow whirled around us but Hider ignored it. and Hitler invited his closest staff to a celebratory coffee afternoon in the saloon coach. Most of the time he stood up in the Mercedes saluting. No wonder! They found it impossible even to offer us a snack. He did not like the beer. It was so hectic that I failed to notice the photographers there. tastefully furbished special train. Then we drove for Prague past endless columns of German soldiers. Something was not right. He also gave me the present of a gold penholder and pencil engraved with the date and his name. and the SS bodyguard had to get out and open them. my birthday. Hitler worked until late in the night preparing decrees which he dictated to me at the typewriter. In 1946 this gift gave pleasure to some American souvenir hunter in the Mannheim-Seckenheim internment camp. for me a clear sign that we were not welcome.
HE WAS MY CHIEF It became his habit on these journeys to invite his intimate staff to the saloon coach in the afternoon and evening. When stopped at stations the signals crew hooked into the telephone network.1. He wanted only electric light because he found bright sunshine unpleasant. 10.11. from the end of the 1920s. Its director-general. Accordingly I spent a great deal of my existence in the saloon coach of the Flihrer-train. 10. not only because it was quicker but also because it gave him a chance to meet the common people close up. 16.12. A gramophone and radio were on hand. Werlin belonged to Hitler’s private circle at H aus Wachenfeld. He only used the special train because it was so comfortable. During conversations on the train Hitler liked to talk about car travel.1965 Salzburg). Possibly he also liked Dara’s make-up better under artificial light. On these train journeys Hitler would insist on having the curtains drawn in the saloon coach even in blinding sunshine. The coach was mahogany-panelled with a large rectangular table.1. often hours long. d.000 RM on credit.11. he would mount an enquiry into her whereabouts and the manservant distributing the invitations soon learned not to accept No for an answer.9. He was for ever paying her compliments which led to the Hitlerimpersonators amongst the officers staging their usual impressions once Hitler had retired. red leather chairs and indirect lighting.5. May 1945-9.9. or telegraphic messages could be sent.1942 Inspector-General and Plenipotentiary for Automobilism. He liked being driven across Germany in the car. 12.1949 interned. when meals and tea would be taken. If one or other of us slipped away to avoid one of these sessions. 30.5 had let him have 5 Jakob Werlin (b. 23. February 1925 sold the penniless Hider a Mercedes worth 20. April 1921. His female secretaries were never overlooked. 66 . Hitler the fanatical car enthusiast had suggested various improvements which found approval with Daimler-Benz.1886 Andritz/Graz. 24.1933 board member of Daimler-Benz AG and later director-general. Jakob Werlin.1924 visited Hitler at Landsberg.1932 joined NSDAP and SS. head of the Benz & Co branch in Munich at 39 Schelling-Strasse where the Volkischer Beobachter was printed.1942 SS-Obergruppenfiihrer.
said to me: ‘Fraulein Schroeder. You should consider whether you have any demands to make!’ Werlin. which Horch’s had declined to do.TRAVELLING WITH HITLER a car on credit during the period of struggle.’ 67 . who came into the sleeper coach where I was smoking a cigarette in the corridor. did you hear what the Fiihrer said? I must tell my mother that. it would have been impossible for me to have been it. Therefore you are the true conqueror. do you know that you are the true conqueror of Germany? If you had not given me a car then. He once joked to Werlin: ‘By the way. and so Hitler was especially indebted to him.
Paintings. The official chorus of congratulations would follow and then would come the Wehrmacht parade in the Tiergarten-Strasse. briefcases. and for the photographers the table scenes were a welcome opportunity. There was the widest range of presents imaginable: valuable. carpets. books. clocks. carnations and roses would perfume the room. he would be greeted by a host of ministers’ and adjutants’ children in their party best holding colourful posies. music scores and much more. artistic. old weapons. or legends such as Heil mein FiihrerL How many thoughts from fanatical. bedsheets and blankets finished I N the prew ar y ea r s 68 . beautiful. adoring women had been woven into this handiwork! Mountains of baby clothes.Chapter 5 Hitler’s Birthday Hitler’s birthdays would begin with a serenade by the band of the SS-Leibstandarte. useful. Hider evidendy enjoyed taking his breakfast with the children. The scent of small almond trees. rare coins. candelabras. accessories for the writing desk. Then the handicrafts: pillows and blankets with National Socialist symbols. The historical Congress Hall which separated Hider’s apartment on the first floor from the service rooms of the Reich Chancellery would have been cleared a few weeks before 20 April. The presents received would be stacked on the long negotiating table and additional tables brought in for the purpose if necessary. sculptures. When Hider then descended the staircase from his first floor apartment in the Radziwill Palace.
(TN ) 69 . but I let the material stand. * Extracts from these letters are shown here and in following chapters.* In a moment of thoughtlessness I made some of them available to David Irving.h i t l e r ’ s b ir t h d a y up later in the archive room of the Private Chancellery to be carefully sorted for distribution to needy families. That is now out of the question and for the time being I have given up. The following extracts are taken from them. Valuable items ended up in the showcases and cabinets of the Fuhrer-flats. handicrafts without National Socialist emblems in visitors’ rooms. Nowadays I am horrified at these opinions of Hitler which I thoughtlessly passed on. We have a Reichstag speech on 28th of the month and until then we are on standby for all eventualities. baskets of delicacies and more or less all the edible stuff were sent on Hider’s order to hospitals. 21 April 1939: All my plans to take the cure and convalesce have come to naught again. Cakes with artistic structures and inscriptions. Later in the war fieldgrey socks knitted by women of the Nazi Women’s organisations were piled into great mountains in the four comers of the Congress Hall. In the 1950s my friend Johanna Nusser in Berlin returned to me the letters I had written her from the Berghof and Fiihrer-HQs during the war. Dara has been in Munich since last week. How could I pass judgement on people whom I never had the opportunity to know first hand! I am blameworthy. I have no choice but to wait for the Reichstag speech and see how the general situation looks afterwards. I wanted to go in March. but meanwhile the boss has told her to stay in Munich to catalogue the birthday presents he received and write letters of thanks for them. and when that was not possible in April. The opinions they express about the Russian mentality I had assimilated from conversations with Hitler and repeated in chat. I had hoped that Wolfen (Johanna Wolf) would be coming to Berlin. Letter from Berlin.
even a glorious Titian). The number and value of the presents this year is staggering. was wonderful although like Unter den Linden I found the bunting a bit too theatrical. We left at 0930 and got back to the office at 1630. Then aircraft and ship models and similar military items which give him the greatest pleasure. or I was at least. The parade yesterday was fairly large and went on and on. and four hours’ march past. He is like a kid with them. Lenbach. then wonderful Meissen sculptures in porcelain. The boss went off in the car leaving us in the special train for three or four hours just seven kilometres from Vienna. which is very wide and has fine. goes hungry for three weeks and loses it all. reception after reception. seven hours split by three hours’ drive and waiting time. The Linden has too many of those advertising columns. I expect you will see it on the cinema newsreels. By the way. Hours without a break standing and saluting are damned tiring. radios. fruit juice. 70 . vases. It is simply amazing to me where he gets the strength from. liquor. silver tableand centre-pieces. It lasted for two days. But perhaps I have no taste and it is actually beautiful. Paintings (Defregger. Just watching we got dog-tired. huge cakes.HE WAS MY CHIEF Meanwhile I have put on a lot of weight. drawings. globes. magnificent books. The Berliners made a day of it as usual and were on their legs from dawn to dusk. a marvellous sailing ship made from fresh blooms. he calls the train ‘The Hotel of the Frenetic Reich Chancellor’. The birthday was very tiring for him. Before we came back to Berlin we were in Austria to review the troops. Most people seem to approve of it. handicrafts. Then crates of eggs. watches. As soon as he puts on a few pounds he cuts out this and that at a stroke. Waldmuller. carpets. boxes of sweets. If only I had half the willpower of the boss in this respect it would help. it is really ghastly. etc. When these theatre requisites are taken down the street will be back to normal and more imposing than it is now. sad that it will soon wither. solid lamp standards. The Charlottenburg Boulevard.
the female body. The Old Man has been giving very interesting talks recently in the evenings about the Church question. Christian mysticism had its origins in the era of the Goths. An unmarried painter would never have seen a naked female. Christianity is based on knowledge 2. The question is: Why should it not be possible to base Christianity on our modern knowledge? Luther had attempted to introduce the Reformation but he had been misunderstood. I had wanted to see the latter for a long time. hence the false and ugly representations. for example the old city musician Miller with Heinrich George. The boss knows of course that the Church question is very complicated and should war come could 71 . no standing still but advancing together. but could never get to it in Berlin. ‘Why suddenly interrupt a naturally fine arch to rise to an unnecessary and senseless point?’ he asks. abdomen and everything. developing together. I have seen for example a glorious Anthony and Cleopatra and a short while ago during Festival week Conspiracy and Love. Everything was so clear and straightforward that I regret not having made a note of it. and this knowledge is confused and layered with mysticism and biblical fable. That is obviously a matter of taste. for the Reformation was not a single event but eternally progressive reform. inaccessible and blocked off inside. hidden. And why the many towers and turrets. In that era fables and mysticism would have spread very rapidly. He does not like the Gothic style of architecture because it is strange and unnatural. The period was one of darkness and prudery. It is booked well in advance there and the boss had said one should only see it in Berlin where the setting is fabulous and the casting first class.000 years old. only there for the eye. I never really know where to go in the evenings and so I have made a habit of attending the chamber plays in the Theatre House where almost everything I have seen to date has been wonderfully staged and acted.h i t l e r ’ s b ir t h d a y Recently I have seen some fine theatrical performances and have been mainly in Munich. etc. The dark interior of the buildings favoured it.
No trouble from a serious face. I have the impression he would be happy to see it resolved in a dignified manner.. I cannot just throw in the towel. She is too interested in pleasing at all cost and for this purpose anything goes. but these were the most private things). The balloon went up on our last stay at the Berg when she started to speak for me. thank you! On the Berg recently I had enough of it. But then I told myself. nicely made-up. quite openly claiming them to be the product of her own mind. I cannot start all over again and in any case you meet struggles and resistance wherever you go. and my beliefs about this or that problem. totally unproblematical heads. after half an hour.. even in my presence. I have got used to her passing off my opinions on books as her own. It is the case today that men (and particularly those here) like to have around them pretty. Since then I have been very reserved and only speak to her if I have to. For example I have come to realise that there is a big difference in character between my younger colleague and myself. Then in all her glory in the Tm convinced of it* type of superior tone she came out with so many well-stretched out ‘Isn’t its?’ and ‘Don’t you agrees?’ that I got furious. when somebody asked me something directly she got her oar in first and answered on my behalf before I had a chance to open my mouth (if it had been on office matters it would not have bothered me.e. You know yourself best how unpleasant such things can get. or if I was sitting with somebody in serious conversation she had to come along and butt in with loud comments and so ruin everything. young. i. The worst thing is that the boss is very taken with her and she naturally used that to her advantage. So life is an eternal struggle to get my own point across and that I do not like. There is very much more of which I have to unburden my heart to you. I shall just be glad when it is over at least and I can pack my bags and take the cure . 72 .HE WAS MY CHIEF have very unfavourable effects internally.
When you write please do so to the address at the head of this letter. Now I have to go through thick and thin with the boss. 73 . Every morning he was driven to the Front to visit the most forward lines. Only towards the end of the campaign did he set up his HQ in the Casino Hotel at Zoppot. .then life has nothing more for me. In the evening he would return covered in muck and dust.. Before leaving again he would dictate exhortations and orders of the day to his troops. and at 2100 on the evening of 3 September we left Berlin in Hider’s special train for Poland.’ I wrote to my friend on the afternoon of 3 September: O n First of all receive a Hallo from me.Chapter 6 The Polish Campaign 1 S e p t e m b e r 1939 the war with Poland came as a surprise for us all. At the beginning of the Polish campaign Hitler directed operations from his special train in the vicinity of Gogolin. ‘In a couple of hours we are leaving Berlin. During the siege of Warsaw he made appeals to the population to abandon the city. I will reply from the same . That it could be the thing I do not like to think but if so . As usual we had been given no time to make preparations for the journey.
But once again it was turned down. A big transport came along full of wounded. Visible to all and sundry the boss stood on a hilltop. Half an hour before. It is assumed that the Poles saw the Fiihrer-convoy. the soldiers ran towards him from all directions shouting HeilI —and the Polish artillery was in the valley. In addition the worst is that one cannot do anything useful.Dara and I . Polish aircraft were bombing not far away. Recendy we spent a night near a transit dressing station. It is always the same: the boss leaves in the morning with his officers in the car and we are condemned to wait and wait. 11 September 1939: We have been living in the Fuhrer-train for ten days. Poland. I have got really fat. not even in the most exposed areas. How envious I was to hear about your coal-shovelling.HE WAS MY CHIEF Letter from FHQ. simply ghastly. The first day they drove through a wood infested with partisans. at least one can see what role one is playing. our people from the SS bodyguard helped out. Dara and I. an unarmed German medical team had been wiped out. The heat is almost insufferable. Our people who went into Poland with the boss can naturally see what is going on. Dr Brandt was operating all night. continually changing sidings. simply frightful. I would like to have been there. They 74 .never leave the train it is very monotonous. We. I think it is crazy but he will not listen. We have done everything possible to help out somewhere but it is simply impossible because we do not stay long enough in one place. but since we . The sun beats down all day on the roofand one is powerless against the tropical-type heat. but it is not safe because they often come under fire from ambushes. The single survivor managed to escape to tell the story. offered to write letters for the wounded to their next of kin and were hoping to be able to help out a little in this way. They cannot convince the boss not to stand up in the car as he does in Germany. the senior surgeon was very pleased and thanked us but since it is only a transit unit our offer was inconvenient.
One of the orderlies1died suddenly the day before yesterday of meningitis.7. has also fallen .1934 joined LSSA H .. If the thing with Poland is over with quickly this will take the carpet out from under their feet . 29. There are many we know amongst the dead. in my opinion the danger is too great. I hope that the French will soon see that it is not worth the price to sacrifice millions of people for Britain. 9. Half an hour later their aircraft dropped bombs near him. d. if you remember Schreck. 75 .1936 SS-Junker. The brother of Hans Junge. I heard some SS comrades say that he was only twenty-four: ‘It would have been better for him to have fallen in the field’.since it is no secret that the Fiihrer is spending time at the Front . 11. .4. 1. On 26 September 1939 we returned to Berlin. the same disease which claimed the Fiihrer’s driver. It is of course a great incentive for the forces and has a colossal effect for morale to see the Fiihrer in the danger zone.THE POLISH CAMPAIGN obviously saw the crowd forming and . All the same.3. 20. 1 This was Ernst Bahls (b. died o f meningitis aged twenty-four during the Polish campaign. 20.7.1938 Obersturmfiihrer. who was with the Leibstandarte.1915 Rugen Is. But one cannot pick and choose the way one is to die..1939 Poland).1937 SS-Untersturmfuhrer LSSA H .9. I am very interested to see how the business with the British and French develops. 30.it was not too difficult for them to guess who was there.9.4.1938 detached to Fiihrer’s Adjutancy.or at least that is how I see it.
The destination was not disclosed. Seated in a car with my colleague Daranowski and the representative of the Reich press chief we were driven out of Berlin towards Staaken. There was only a suspicion that some thing was in the wind. Generalleutnant. but there again it could be years!’ Towards evening we assembled in the Fuhrer-apartment and received the order for the off. At dinner in the dining car Schmundt2 joked: ‘Have you all got your sea-sick H it l e r h a d m a ny c o n f e r e n c e s 1 This was Heinz Lorenz. for the car drove on past Staaken and eventually pulled into the forecourt of a small railway station where the Fuhrer-train stood waiting. That was not the case.1944 Rastenburg). the inner circle.10. On the afternoon of 9 May 1940 we. were told to prepare to travel the same evening. leading us to assume that we would be flying from the airport.Chapter 7 The French Campaign with the military in April and May 1940. he said in a manner both secretive and showy: ‘It could be eight days. Apart from the military adjutants nobody seemed to know where we were supposed to be going.1896 Metz. it could be a month. 1. It was all very mysterious. nor could we discover how long we might be away. but none of the content seeped through into the Staircase Room. 13. In response to my enquiry in this respect to Obergruppenfuhrer Schaub. d. it could be fourteen days. 2 Rudolf Schmundt (b.8. 76 .
It was always done secretly like this. 3 Reich press chief Dr Otto Dietrich stated at Nuremberg on 9 August 1948: ‘An hour before the departure of the Fiihrer-train on the night o f 9 May 1940 I was told to pack for a journey with Hitler’s staff to inspect a shipyard at Hamburg. At about 0100 just short o f Hamburg the train was diverted westwards. and about thirty kilometres from Bonn and the Belgian border. The FH Q was called Felsennest. Schaub and one manservant and there was a small dining room for a nucleus of the staff. Jodi.’ It became clear that we were somewhere near Miinstereifel. The room accommodated Hitler. In all the villages through which we drove the street signs had been replaced by yellow shields with military designations. All other staff members were given quarters in the nearby village. Finally we finished up in a hilly. From the point of view of landscape it was the best situated of all FHQs. the offensive against the Western powers has just begun. fresh with spring. Hider gestured with his hand towards the West and said: ‘Meine Herren. Keitel. was filled with bird chief ^ftfehrmacht adjutant to the Fiihrer. As we stood near this bunker at dawn we could hear artillery fire in the distance. Schmundt. We left the train and continued our journey in threeaxled open Mercedes cars. I still knew nothing o f our destination until we pulled into Euskirchen station in the Eifel at 0600 that morning. (TN) 77 . you might be able to bring home a sealskin as a trophy.’ * FH Q Felsennest was occupied by Hitler between 10 May and 6 June 1940.3 Towards dawn we drew into a small station from which the name-shields had been dismounted. The spot height known as Felsennest was a hilltop at 440-metres altitude overlooking the village o f Rodert to the northeast.’ After midnight —past Hannover .the train was suddenly switched to the westbound tracks although this was only noticed by the alert few. The wood. It had been included prewar in the Westwall air defence zone and from the late 1930s had a bunker and flak installations with barracks.* The command post (bunker) was very small with simple wooden walls and chairs of braided fibre.TH E FRENCH CAMPAIGN pills?’ Was he hinting that we were going to Norway —the train was steaming north? Hitler chipped in: ‘If you are good. wooded region before a regimental command bunker which the boss had claimed for his HQ.
not totally refreshing. The first few days we had no water. The first few nights I slept with a female colleague in a former pigsty—cowshed of wooden boards and stucco. Anyway. He felt very well in this region and since his bunker room was very small he held most of his conferences in the open air. We cleaned our teeth with soda water. Hitler called it ‘the bird paradise’. 78 . As to our successes. Never again did I see fields of that kind covered over so great an area with such succulent margaritas and skirted by a wood of wonderful primeval oaks. 13 June 1940: We moved forward a week ago and are now in a small village abandoned by its inhabitants. and still half asleep I tried to put it out with my bare hands. dreadfully damp. Yesterday thank God they finished the barrack hut and now we are living in the dry. Bruly de Pesche. When that failed I used a wet handkerchief and got a shock The same happened with several of the officers. The telephone and lighting wires were close together and the damp started the fire. Letter. an uncomfortable feeling lying in bed below it. but I doubt we shall be putting down roots here. This was a village with an old church and a spacious comfortable schoolhouse set amongst fields in opulent bloom. which gave me an insight into how essential this wet element is. He was never outdoors so often as he was here. The hissing and crackling of the flames woke me up. at least the inconveniences are over and we have setded in quite nicely. On the first night we had a fire in our stall. He enthused frequently about the glorious scenery and made a plan to bring us all back on a commemorative visit every year once the war was over. The cabling cooked all night. our troops have got as far as Fourges (Paris aerodrome) from where I am writing this letter.HE WAS MY CHIEF song. On 5 or 6 June 1940 the FHQ was transferred to Bruly de Pesche not far from Brussels in order to be closer to the Front.
and above the whole thing great hordes of screeching ravens circle. The landscape reminds me of a picture by Caspar David Friedrich. Punctually at 0200 the enemy aircraft come and circle the village for three hours. There was much devastation. We do not know if the aircraft were going for us or the highway. Cattle.7. we have enough butter and milk. fate after 1945 not known). 79 . We do not really go short of anything. aircraft of all kinds. The refugees make a sad picture. ambulances. etc. in ditches right and left artillery. old ladies being pushed in children’s perambulators. etc.THE FRENCH CAMPAIGN Recently I went through Sedan. If they fail to appear the boss asks: ‘Where are our house aircraft tonight?’ Every night we stand in the open with the boss and some staff officers until 0300 or 0330 watching the nightly manoeuvres of the reconnaissance aircraft until they disappear with the dawn. Even worse are the highways along the route of the advance. we even get tomatoes and fruit now and again. A sweetish odour of decomposition hangs above these towns. Head o f Hauptamtfur Vol^swohlfahrt (Principal Office for People’s Welfare).1899 Heinitz/Ottweiler. They are apparently invulnerable because they keep so high. Namur. 2. There were about fifty 4 Erich Hilgenfeldt (b. horses and dogs all ownerless wander between the gutted houses. In the first few days when cows were not milked we could hear them at night bellowing in pain. uniforms. Philippeville. Dinant. ammunition. Yesterday I was invited with Schaub to a slaughter party. About twenty minutes from here by car is our Flight-Squadron where the airmen had slaughtered two pigs. A desolate picture of destruction. A few nights ago they wrecked a house in which some of our RSD policemen were billeted. Thank God nobody was hurt. they took cover in time. Large families living in burntout cars. Our boss does what he can for the poor people. Whole blocks of flats reduced to rubble. burnt-out trucks.. tanks. Hilgenfeldt4has been detailed to see to it. Every night we endure the same piece of theatre from ‘above’. The food is first class. war is the most terrible thing there can be.
Probably it will contain his final appeal to the British. Dara and I got a lot of surprised looks in our field-grey costumes with the Deutsche Wehrmacht armbands. By the way. Letter from FH Q Bruly de Pesche (Wolfsschlucht). Personally I do not believe that the war will last beyond June. They are billeted in farmhouses. I am very interested to see how Britain will respond. which they are naturally hoping to show off. hence our invitation tomorrow for pancakes. he would go ahead ruthlessly! I believe that he is sorry to have to wrestle the British to the ground. ^sterday in Paris General Weygand stated that the Batde for Paris was lost and proposed a special peace in which Petain supported him. Munich was lovely. I am not missing out on anything. So you see. Later a simply wonderful old French wine was served. perhaps they would be more approachable. How many mothers and wives will thank God that the war with France has ended so quickly. 20 June 1940: The Armistice came into force tonight at 0135. not to mention the schnapps. There was plentiful blood. Meanwhile the boss was in the room where 80 .HE WAS MY CHIEF people gathered in a former clubhouse (almost certainly YMCA) seated at festively decorated tables illuminated by tall French paraffin lanterns. There is still so much to tell you but which I cannot for the moment. For tomorrow evening we are invited for pancakes with the RSD. The boss will address the Reichstag briefly. he would apparendy find it preferable if they would be reasonable about it. If they will not quit.and liver-sausage and a belly of pork. great enthusiasm. he said. They have picked up a lot of housewifely talent. If only they knew that all the boss wants from them is our former colonies back. The time is not so far away however when we can sit together comfortably. Reynaud and others were violendy opposed. eat at midday from the field kitchen and in the evening have to forage for themselves.
I found her a hotel to change before our return a couple of hours later. Explaining why he had not destroyed the BEF at Dunkirk.THE FRENCH CAMPAIGN he dictated the appeal for the newspapers. we had to give it a chance. the empire would follow. Later he went to Paris to see the Invalides cathedral. That day in Bruly de Pesche Hitler was very relaxed and happy. finding them to be exactly as he remembered them. A few days later Dara and I were taken by a Wehrmacht driver. Hitler told his intimate circle: ‘Their army is the backbone of Britain and the empire.’ Hitler was scuppered. He gave himself a lively slap on the upper thigh and his laugh of relief carried to us two secretaries.5After his return he claimed with pride that he knew his way about their corridors better than the guides did: during his youth in Vienna he had made a thorough study of its ground plan and had retained all the architectural details in his head. so to speak. If we had destroyed the BEF. He composed the radio programme himself. nor can be. 81 . Then Keitel gave an address in which he hailed Hitler as the greatest warlord of all times. by his spurned love for Great Britain. the Opera House and other buildings. My generals have not been able to understand that. he travelled with First World War comrades Max Amann and Ernst Schmidt to the former German trenches on the Somme. Hitler visited the trenches where he had served in the First World War. to Brussels where we were involved in a minor accident. Next. It was nothing serious but Dara was thrown against the car roof and suffered concussion. whom Oberst Schmundt had placed at our disposal. Hitler heard about this accident and banned us from riding 5 Hitler made a lightning visit to Paris first on 23 June 1940. A little to one side we watched the scene as Walter Frentz filmed it. its successor. As we neither wish to be. Architects Speer. Giesler and Breker were with him. The news of the French offer of peace was given to him while standing with his officers on the road between the church and the schoolhouse. on 25 and 26 June 1940...
On Hitler’s directive the president of the Guild of Stage Designers. Permission to wear this badge was granted by Hitler only to a chosen few. On 23 December at Boulogne. 22 February 1941: We have been continually on the move since 21 December 1940. while at dinner in the dining car of our special train. These had the sovereign emblem (eagle with swastika) and the words Der Ftihrer below it in gold. In place of the round Party badge Dara and I wore on the left lapel the silver sovereignty emblem designed by Hider himself and cast by goldsmith Otto Gahr. When Arent left. Calais. Berghof. You are for me a bridge into a better world. At the outbreak ofwar I had a large trunk made with compartments for the office material and stocks of headed stationery. There were also cards with the same design. etc. Since we were now constantly at FHQ. while the private notepaper had Adolf Hider instead of Der Ftihrer. Christmas on the French coast. Dunkirk.HE WAS MY CHIEF in Wehrmacht cars. Hitler would talk with him about the artists they knew. 82 . He showed such concern for us. Benno von Arent. It was a good relationship and one felt protected. Hitler would always shake his hand warmly and say: ‘I am glad to have you visit me from time to time in my loneliness. I have already told you about Christmas Eve and New dear’s Eve. designed for us a costume in Italian officers’ grey cloth with gold buttons and cord trim. where the mood was less than pleasant. the British bombed us and our flak roared back. Even later Benno von Arent visited Hider frequently at FH Q and also received invitations to join the evening tea sessions.’ Letter. Hitler wanted us to wear uniform. Although we were sheltered in a secure tunnel I had ‘funny feelings’. even at the beginning of the Russian campaign before much changed. It consisted of a slim eagle clasping a swastika in its claws.
THE FRENCH CAMPAIGN The six days I spent in Paris with Schaub. We had almost too many invitations.. dull and ossified.. therefore I really do envy you. The boss is in Munich today and so it is really desolate . At the moment it looks as though I shall not be going to Niederlindenwiese. We went there on Saturday for the signing of the Bulgarian Pact. and scarcely had time to come up for air. Vienna. 83 . that would have made it better. Probably we will not be staying up here too long. even if only for fourteen days. We should have arranged for a rest day afterwards. I have just heard today of the heavy work the women have to do in the bomb factories. on 1 March 1941. At the moment Daranowski is resting. We shall be in Berlin probably mid-month. I accept it. War is war. I hope you received my letter from Vienna.. I am here with (Johanna) Wolf. if I cannot go. Now we have to be immunised against cholera and typhus (this happened before all our big journeys). Letter. I think it would also be good for me to spend a few weeks with normal people. from the German embassy and the staff of General Hanesse. 7 March 1941: I am pleased your holiday was so harmonious and that you were able to be with so many nice people. One should also definitely maintain contact. we have been here long enough. Up here we have an unpleasant thaw with gloomy overcast sky. Well.. Berghof.6 On Sunday we were travelling and I could not call you. It is time we went back to Berlin. Dara and Kempka were free of duty. By being so cut off from things I feel lonely. it makes one feel quite insignificant. Meanwhile we had a hefty 6 Signed at Schloss Belvedere. Since we shall be spending the whole year sitting in the bunker with nothing to eat day after day but thick pasty stew I would like to take the cure at Niederlindenwiese.
Nothing surprises me any more. He ought to be able to understand the problem in itself. . He seems to be very disappointed not to have heard from me. . We are all sitting on a powder keg. I am returning Lav’s letter to you with this one. when Yugoslavia joined the Axis. Imagine it. Rather skilfully he sent me a few short lines directly through a business friend who visited him there.7 On this last journey he gave Wolfen a rare outing but now he has arrived and probably we will be off south again in the next few days. He does not seem to be very satisfied but this pessimistic undertone you find in all his letters. All I am short of is somebody suitable. it is too wet and the sun is trying to break through to melt it.HE WAS MY CHIEF snowfall which spoiled our spring mood. He is six years her junior. I did not hear of it until he had already gone. where he arrived on 26th. Berlin. has a terrific temperament and is in the Luftwaffe. Gretl Slezak8 secredy married three months ago without her parents’ knowledge. looks years younger and keeps advising me to do the same.. 28 April 1941: I was hoping that the boss would not come back so soon. but of course he knows nothing about the OKW and Gestapo investigations . 8 See Chapter 11. . a conductor who composes heavy and light works. and if you have not passed on my aquamarine ring I would be glad if I could hold on to a memento of Bruckner. and in Vienna on 25th. She is happy. He left immediately afterwards for Berlin. I do not think it will settle long. A short while ago I got from L(av) a small packet which somebody sent me in Berlin of his behalf Ahrens at FHQ forwarded it for me to Niederlindenwiese and now I have received it by this roundabout 7 Hider was in Munich 21-24 March 1941. Letter. The fourteen days when I was alone in Berlin simply sped by . 84 . Wernicke was also swept out with another colleague in the whirlpool of clearance and reorganisation.
An amount like that M. I mentioned this to the boss. What Schaub had done to merit this note was not recorded. Owambo9has now finally cleared out his room this week. and no sooner said than done. Probably he will have handed it over in February. Berghof. 9 Nickname o f Wilhelm Bruckner. they are laying the table. there is still much to be said about it. . Also the certainty that in our circle there is nobody who will lift a finger to help if one falls into disfavour. he bought them for 10. I kept him company and got the last bits of information I was missing. The boss joins us for coffee every afternoon . He is completely in the dark. Well.THE FRENCH CAMPAIGN route.’ No date or other message. I expect it will be the last sign of life from him.A. . . would naturally not have got anywhere else . It contains twelve socks and a kilo pack of tea with the note: ‘On behalf of Herr L. and here I mean those who were once degraded10 themselves. 20 May 1941: The boss left today for Munich. as my friend now needs money. I was very sorry for Owambo. 10 In a footnote to her papers Schroeder commented: ‘Schaub’.. she decided to sell the handwritten poems by Dietrich Eckart which he had sent to old von Wolzogen. and do not even have the will to imagine what it must be like in the other’s shoes. Letter. 85 . who was very close to Eckart. for now he will scarcely dare write. It is disgusting when people are so selfish and have no sympathy for the sufferings of others. with warmest greetings. apparently nothing military has been arranged for him.. now I have to stop. nobody amongst his comrades who once sent him photos signed ‘in undying friendship’ will have anything to do with him. Damn.. But that is all forgotten.000 RM. I have stayed behind .
a small Siemens radio with a wide choice of stations. 86 .6. Because the noise 1 FH Q Wolfsschanze in the woods at Gdrlitz was the largest H Q built by the end o f 1944.1 eight kilometres in the woods from the misera little town of Rastenburg in East Prussia: h e w ar w i t h t h e After five days here at HQ I can give you a short report on morale . Every division set aside for itself Our dormitory bunker is the size of a railway compartment and has light-coloured wood panelling. not yet connected up. .1944 as military overlord. eye-catching wall lamps and a narrow hard mattress filled with eel-grass.11. At first there was no hot water and as usual we slept in until the last possible moment anyway. it was continually expanded until the installations were destroyed on 24.1945. the bunkers are dispersed through the woods. The bunker even has electric heating.1941 to 20. Originally intended for a four-week Blitzkrieg. Common shower rooms are available but until now we have not used them. On 28 June I wrote to my friend from the new FH Q Wolfsschanze. above it a mirror. There is a discreet washbasin. With various absences elsewhere Hider inhabited this H Q from 24.Chapter 8 The Russian Campaign 1941—1944 T Soviet Union began on 22 June 1941 and next day we left Berlin after making brief preparations. divided up into work sections. The room is narrow but all in all it will have a nice look once I have hung a few pictures. .1.
one medical doctor and two secretaries) Hitler accompanied us to outside the bunker doors. The men have better protection than we do (long leather boots and thick uniforms). Suddenly I realised that I had left my flashlight in Hitler’s room. which I always hate especially because of the rheumatic pains I have so often. pointing to ‘difficulties in jurisdiction’. One night after the usual tea hour at Wolfsschanze ended (it always followed the military situation conference and was attended by one personal and one military adjutant. There we stood chatting for a while in the darkness (blackout was always strictly observed). The awful biting-midge plague did not leave Hitler unaffected. Despite that it is all fine except for the damned plague of biting midges. Some wear a mosquito net all the time. The anti-midge precautions last us only a short while. I tried it one afternoon but it becomes a burden after a while. but not of lamps. And it is better 87 . I may be a thief of lands. after all hands went for the midges. and concluded. If we spot a midge the hunt for it starts immediately . He returned empty-handed. Nevertheless he had not yet lost his humour at that time. Hitler. we requested that it be turned off at night with the consequence that we now sleep in a fug and suffer all next day from a leaden heaviness in the limbs. He said that they had searched out for him ‘the swampiest. I have midge bites all up my legs which are now covered in thick swellings. in jovial frame of mind. defended himself with a smile: ‘I have not stolen it.THE RUSSIAN CAMPAIGN 1941-1944 from the fan in the bunker disturbed us and the draught passed continuously above our heads.. ‘in this work only the Luftwaffe is competent!’ Actually in the initial stages of the Russian campaign I found that Hitler was nearly always good-tempered and ready for a joke. and asked the manservant to fetch it. ‘Where could it be then?’ I said. Their only vulnerable spot is the neck.. most climatically unfavourable and midge-infested region possible’.
the boss with his generals. dining room 1. They are saying that this is only a smaller breed and by the end of June an even more unpleasant kind comes and the stings will be even worse. an elongated whitepainted room set quite deep in the ground so that the small gauzecovered windows are quite high up. Now for my ‘busy schedule’. In this room with seats for twenty at the table. I am pleasantly surprised by the temperature. The walls are decorated with marquetry: one shows Hutten. it would probably have been too late. a captured Soviet flag was fixed to the wall. God help us! However. Shordy after 1000 Dara and I go to the officers’ mess bunker. FH Q Wolfsschanze. rather like the ghosdy ship in the Flying Dutchman. It is almost too cool in the rooms. but for the bigger one they let you goF Letter. A few days after moving in. which naturally spurs him into new monologues about Soviet Russia and the dangers of Bolshevism. The trees deflect all the heat. adjutants and doctors eat at midday and evenings. One has to dry out the bed first by body heat. always emphasising the great danger which Bolshevism presents to Europe and that. for they hang you for the little item. Just how much one realises only when in the open on the highway. At breakfast we two ladies join them. Then the heat hits you. general staff officers. had he waited another year. He must have suffered very much in the period after the signing of the so-called Friendship treaty with Russia. In reply to my question why he always insists that this was his most onerous decision (namely to 88 . Now he speaks of his fears from the heart. the other Heinrich I.HE WAS MY CHIEF that way. The boss seats himself so that he can gaze at the map of Russia on the opposite wall. 28 June 1941: Some wire fly-swats have arrived and whoever is free has to join in the great midge hunt. Recendy he said in Berlin during the usual coffee hour which he takes daily in our room that Russia seemed eerie to him. it always feels damp.
from the experience so far one can say that it is a struggle against wild beasts.500 aircraft and 1. it is important to know that the 89 . he answered: ‘Because one knows next to nothing about Russia. Statistics about the enemy aircraft and tanks destroyed are delivered (the Russians seem to have enormous masses. which is held in the map room where reports are made by either Oberst Schmundt or Major Engel (army adjutant). is not the case. 28 June 1941: \es. deftly exchange the cutlery so that we get three portions instead of two. up to now they have lost over 3. These reports are extraordinarily interesting. Therefore in the morning we wait in Dining Room I until the boss. thank God. after wolfing down our allotted portions (small pat of butter). So. After that we let the boss explain the new situation to us and afterwards attend the general situation conference at 1300.TH E RUSSIAN CAMPAIGN 1941-1944 proceed against Russia). it might be a great soap bubble. FH Q Wolfsschanze.’ Letter. ’ The beginning has been so promising. consists of a cup of milk and a peeled apple. In the first two days at Wolfsschanze Dara and I even attended the military situation conferences when the improvised sessions took place in the mess. isn’t he? We girls on the other hand cannot get enough and. by the way. or just as well be something else . now I have wandered completely off the subject. So we heard the boss. coming from the map room (where he will have received the situation report).000 tanks including heavy 40-tonners) and the progress of our troops is demonstrated on the map. standing by a large map of Europe and pointing to Moscow.. say: ‘In four weeks we will be in Moscow. Easily satisfied and modest. It is made clear how furiously the Russian fights. If one asks how it is that we have taken so few prisoners. Moscow will be razed to the ground. arrives for breakfast which. he could match us man for man if the Soviets had proper military planning which.
Towards 1700 we are ordered to join the boss for coffee. were intelligent and gave up when they saw there was no point in going on. Belgians etc. they simply stay on his tail. They are instructed to fight to the last and if overwhelmed to shoot themselves. Back to the daily routine: at the end of the situation report the time passes slowly to lunch. Whoever eats the most gets a word of praise! 90 . for example. After that they blew themselves up. and he treats us to cakes. but the Russians keep fighting like madmen. That is how it plays out and the following happened at Kovno.500 Russian aircraft. which usually lasts into the early hours. Better death than surrender.as I said previously we have destroyed 3. what remains is a mob.HE WAS MY CHIEF Russian soldiers are stirred up by their commissars. If we have nothing important to do we take a nap for a couple of hours after lunch so that we are well rested for the remainder of the day. In the Russian squadrons. Each unit is controlled by a GPU commissar to whom the commander is subordinate. If he is shot down they cannot find the way back because most of them have not been trained to read a compass. As the meal is very often stew we give that a miss particularly if peas and beans.that is in any case what Moscow has threatened. A Russian prisoner sent by our troops to a bunker in order to ask the Russians there to surrender was probably shot by the commissar himself for having volunteered to carry the message. who tell them atrocity stories about our ‘inhumanity’ which they will experience should they be taken prisoner. They cannot take advantage of having so many aircraft because they lack intelligence. which we take in Dining Room II. trembling with fear lest something should happen to their families if they surrender . This is naturally a danger in itself and leads to bitter fighting. The French. the squadron commander leads the way and the rest follow without knowing the objective. Meanwhile . totally primitive but which puts up a dour fight. Cut off from the leadership.
156. As a rule at teatime the guests of the boss would be a medical doctor.2. was a large fireplace with a round table before it and rattan chairs.1944 when relieved of his post by Hitler and Bormann.5. After that we have a walk or see a film to kill time until we are invited for ‘tea’ after the evening situation conference. he had to make surreptitious notes of Hitler’s conversation to keep Bormann abreast of Hitler’s thinking. the Monologe4 2 Heinrich Heim (b. deputised for Heinrich Heim at FH Q 21.28).1942-31. 1920 NSDAP Membership No. one military and one personal adjutant.).5.2 Bormann’s adjutant. d.1942. Hermann Giesler: Nachtrag (Heitz & Hoffkes Verlag. Heim had been given the task to record ‘secredy’ the gist of Hitler’s talk after the tea session was over. NSDAP member from 1. 17—18) states however that ‘Picker’s place was at the adjutants’ table and not with the nighdy tea guests. secredy noting Hitler’s table talks for Bormann. 1222. Here I have to make some observations about Dr Henry Picker.7.1988 Starnberg).4. opposite the main windows. Whatever one may think. we two women and Heim.11. 1940-end 1942 Martin Bormann’s adjutant at FH Q (absent 21. Hitler Youth Bannfuhrer and Reichsamdeiter to 1. Hamburg 1980.’ 4 Werner Jochmann (ed. from 1927 Munich lawyer.1930.1912 Wilhelmshaven. 3. Verlag Albrecht Knaus. 91 . These were first published subsequently under the title Adolf Hitler: Monologe im Fiihrerhauptquartier 1941—1944 by Werner Jochmann. pp.1945-mid 1948 interned.3 For a four-month period in 1942 Picker deputised for Heim as temporary adjutant to Martin Bormann at FHQ. 2. 1928-end 1930 attorney on staff of H ider’s lawyer Hans Frank.3. Martin Bormann. In Hitler’s study. Picker claimed in his book (third edition.7.3.TH E RUSSIAN CAMPAIGN 1941-1944 The coffee hour usually lasts until 1900 but often longer. On Bormann’s instructions but without Hitler’s knowledge. 3 Henry Daniel Theodor Picker (b. Diisseldorf 1988.1942). Then we go back to Dining Room II for dinner. 6. various offices at NSDAP. 1943 to end April 1945 head o f commission in Munich investigating basic questions o f law for the reconstituted Europe.1942-31. A dolf H itler: Monologe im Fuhrerhauptquartiere 1941— 1944: Aufzeichnungen Heinrich Heims. 1933 staff o f Rudolf Hess.1900 Munich). 1976) that he was ‘Hider’s constant guest’ and that Hitler had approved his taking verbatim notes of H ider’s conversations (p.
92 . .. extract from Kluter-Blattem. p. taped recording. Many historians have relied on them in the past. then I would not be able to speak so freely” etc. . I remember one night at Wolfsschanze when after some highly interesting talk you said to him something like: “I would like to have got that down in shorthand” and he replied: “No. later edition with extensive commentary and notes by Picker. Monatshefte fu r Kultur und Zeitgeschichte. experiences and ideas expressed in his table talks were naturally the major component of his life story. Stuttgart 1976. The events. What they may not know. first published Athenaum Verlag.’.HE WAS MY CHIEF (Heim) and the Tischgesprache5 (Picker) are valuable sources for following Hitler’s thinking. for it is not true to claim that in 1942 Adolf Hider gave Henry Picker the exclusive rights to write up the table talks. 6 14. you know how he (Hider) hated having his thoughts committed to paper.6 (b) a letter from Gerda Christian nee Daranowski to Christa Schroeder dated 19 March 1975: ‘.9. That he did not know. The facts are that Adolf Hitler had no knowledge of his monologues being secredy noted down. Issue 12. however. December 1981. i.e. is that a red line must be drawn through the Foreword and Commentary of Tischgesprache. . do you remember?’ (c) Adolf Hider often said that after the war he would dictate his memoirs to his two senior female secretaries Wolf and Schroeder. A signed statement in my possession made by stenotyist Gertraud Junge reads: ‘The worse the situation got at the fronts. ‘In the spring of 19511 met Julius Schaub in the street just after a magazine had published an extract from (Picker’s) Bonn book. etc.29.1953 for the BBC. and many will in the future. which was on the point of being released. is proved by the following: (a) a conversation between Heim and Schaub after 1945. in the small circle at the evening table 5 Hitlers Tischgesprache. Bonn 1951. Schaub assured me that Hider had had no idea that I was making notes. London. he stricdy forbade it. Seewald Verlag. Jahrgang 32. and did not wish a record to be kept.
’ (d) Another myth is that Adolf Hitler allegedly instructed Martin Bormann to give Picker special treatment by ordering that his bags were not to be searched whenever he left FHQ. and mentioned in this context repeatedly that he would then surround himselfonly with civilians. 93 . and never again with ‘uniforms’. There never was an order to search baggage of FHQ personnel upon entering or leaving FHQ or Sperrkreise I and II (Fiihrer-bunker and accommodation of Adolf Hider’s personal staff). His two long-serving secretaries Wolf and Schroeder would help him in this. and their hand baggage (file and attache cases) was examined. the women would be able to keep up with his tempo. Upon entering Sperrkreis I (Fiihrerbunker) after the assassination attempt of 20 July 1944. to where he was planning his retirement. As he would then be older and slower. (b) Eva Braun was Hider’s ‘great love’. In fact the bags of FHQ staff were never searched: AFFIDAVIT.’ Signed. and (c) Hitler broke off his friendship with Gred Slezak in 1932 because of her Jewish background. so that he could then finally dictate his memoirs. the younger girls would probably marry and leave him.THE RUSSIAN CAMPAIGN 1941-1944 talks the happier the Fiihrer would be to talk about his plans for after the war. 26.3. He talked about the painting gallery and reshaping the city of Linz. I hereby swear on oath that during my service as personal adjutant to Adolf Hitler from 1943 to April 1945. This was true for all other personnel at FHQ. artists and academics. To rebut all of Picker’s false assertions would require another volume.1982. visitors from outside were required to surrender their pistols to the RSD. my bags and personal effects were never subject to controls on entering or leaving FHQ. I point out here just three glaring examples: (a) Eva Braun was the lady of the house at the Berghof. Otto Giinsche.
HE WAS MY CHIEF
All three statements lack any basis in fact and are discussed at length
later in this book.
It was the custom of Dr Picker to throw a party every year to
celebrate his birthday. In the Foreword and Commentary to
Tischgesprache, Picker includes a tract allegedly signed by the three
former military adjutants, von Puttkamer, von Below and Engel, to
the effect that all have read the material of the book and vouchsafe
its accuracy to the best of their knowledge and belief In order to
lend credit to this authentication, these three former officers were
invited to attend the birthday parties. It is unfortunately the fact that
hardly any of them had read the Foreword and Commentary. When
I asked the wife of one of the former ADCs she replied: Ah, you
know Christa, we never read stuff like that. We put the book straight
on the shelf!’7 Thus historians may rely on the authentication and
in good faith repeat Picker’s assertions as historical fact.
Letter, FH Q Wolfsschanze, 28 June 1941:
It is a companionable reunion in the inner circle, coffee and cakes
again, etc. You can be sure after reading this that we shall not be
returning any slimmer. Occasionally we visit our chef,8 who came
from the Mitropa and who cooks for us on our travels and follows
us in all the HQs, in his highly professional, white-tiled kitchen
equipped with the most modern electrical equipment, and scrounge
whatever catches the eye.
We were very keen to give him a hand the other day, cutting
bread, apportioning butter or making the salad garnish, but he
simply does not want help. He is a small, slim, agile man whom
the boys of the SS-Begleit^ommando call ‘Krumel’ —Lump - I do
7 Frau von Below, wife of former Luftwaffe adjutant to Hitler Nicolaus von Below
(statement by Schroeder to editor).
8 Otto Gunther, 1937 employed on the Fiihrer-train, and then at FH Q . H e was on
Kannenberg’s staff and cooked for the 150-200 personnel at FH Q Wolfsschanze.
94
THE RUSSIAN CAMPAIGN
1941-1944
not know why - and the more work he has to do the happier he is,
and the better he feels. He is a cook from passion, so to speak, and
it is a joy to see how quickly and skilfully everything flows from his
hands. In a trice he arranges something, not tossed together with
a prayer, but always into a beautiful garnish. When one sees the
happy Lump one realises how important work is for fulfilment and
a feeling of contentment. On the other hand I often see myself as
useless and unnecessary. When I think how much I do in a day’s
work I come to the devastating conclusion: nothing. The wife of a
plutocrat is active compared to me. I sleep, eat, drink and converse if
I can bring myself to it. In a quiet moment - 1 cannot really change
anything since duty condemns me to eternal waiting and readiness,
until another blow is to be struck - I set myself a job (I have 1,000
words of French to learn) - but even here it is hard to get involved.
I lack verve and motivation. Today I had to really force myself to
finally provide you with a long report...
Meanwhile you have already heard the batch of Special
Announcements for a whole week. The boss said this morning
that if the German soldier deserves a laurel wreath it is for this
campaign. Everything is going better than anticipated. We have
had a lot of luck, e.g. the Russians stood at the frontier and did not
allow us to make a deep penetration, which would have caused us
problems on all our supply lines, and then by failing to destroy two
bridges at Dunaburg.9That would have caused a great loss of time
if we had had to rebuild the bridges first. I believe that once we have
occupied Minsk we will then go forward all out. If there are a few
Communists hidden in our soldiers’ ranks then they will certainly
be converted when they see the ‘prosperity’ over there. I have talked
to several officers who had the chance to look around Moscow.10
It must be a miserable, harsh life for the Russian people. Their
9 On 26.6.1941 the German 8.Panzer Division captured the bridges over the Duna
intact.
10 Photographer Heinrich Hoffmann and adjutant Richard Schulze.
95
HE WAS MY CHIEF
insecurity has been used to rob them and lead them astray. It would
be interesting to experience something more authentic about it.
Letter, FH Q Wolfsschanze, 13 July 1941:
In our evening discussion with the boss the Church plays a major
role. It is a pity that you cannot be there. It is all so enlightening
what the boss says when e.g. he explains that Christianity with its
lies and hypocrisy has held Western humanity back 2,000 years in
its development —from the cultural standpoint. I really must start
making notes afterwards about what the boss said, but the sessions
last a ridiculously long time and one is by then —if not actually
ready to drop - well at least so enervated and bereft of energy as to
not feel like writing.
The night before last when we left him it was dawn. Instead of
going to bed as normal people do we had a couple of sandwiches in
the kitchen and then went for a two-hour run direct into the sunrise.
Past horses and cattle in corrals, past hills of red and white clover
simply fabulous in the morning sun. I could not get enough of it.
Then we went to bed and spent three hours exhausted, unable to
bestir ourselves. A mad existence, don’t you think? Such a weird
occupation as Daranowski and I have would probably never offer
itself again. Eat, drink, sleep, now and again write something and be
sociable for hours on end. A new idea is to make ourselves useful for
the boss picking flowers ‘so that his bunker does not look so bare’.
Letter, FH Q Wolfsschanze, 28 July 1941:
The last few days I have been miserable again. It is a thorn in the side
of certain people that even in wartime the boss has his personal staff
around him which obviously includes two females. An orderly told
me about comments made at a late hour after excessive drinking in
the officers’ mess and which have incensed me. At first I was going
96
THE RUSSIAN CAMPAIGN
1941-1944
to take it up with the boss, for it is really a mutiny against him, a
criticism of his directives and orders. We are not here from choice
but only because the boss wants it and maintains that he can only
work with us. He has emphasised more than once in the presence
of these gendemen that without us (Dara and me) he would have
been in a pickle. Thus I find it arrogant and stupid of these officers
to deprecate our presence.
I am exercising an iron reserve towards the parties involved
and now they have a bad conscience. Probably it was not a pleasant
situation for them when, just a few days after the comment, the boss
asked the Wehrmacht adjutant if a tent was available for his ladies at
the next HQ. Receiving the answer ‘No!’, in indignation the Fiihrer
ordered that a possibility for our accommodation had to be created
immediately —yes, they had been thinking it would be just a short
stay for a few days under canvas and we would not be needed. In all
these excuses one sees their hope of ditching us by the wayside. But
the boss would not let himself be persuaded. A coach will have to be
provided for our beds and work, he said.
Earlier when I drank with them I laboured under the delusion
that these people were friends, but now I see that the chats we had
in those hours were not the outpourings of comradely sentiment but
just the effect of the damned alcohol. These social periods changed
nothing and created no friendships. The day after, I came across
more hostility. Why such deception? It is a bitter fact to realise that
one is abandoned and alone and that with the best will in the world
and with the purest intentions no friendship is possible.
The men are all obsessed with one thing, to seize the best
possible advantage for themselves and appear in the best light. They
all want to be more than they are and do not realise how silly they
look to those who see through them. The most ridiculous thing is
when the boss is standing amongst some of these gentlemen and
the photographer picks up his Leica. Then they all come streaming
to the boss like moths to the lamp, just to get into the picture. This
97
we can hope for the best to happen. litde work. the camera showed the enormous fires. have been destroyed. The war with Britain can only lead to each of us reducing the cities of the other to rubble. The commentary said that the British could take it because they knew that Berlin looked the same. now I have had a good moan. But you can understand how this hollow society revolts me and therefore I had to let off steam again. I am sure they would not want to carry on. for I kept the shop alone for years. Well. warehouse after warehouse a sea of flames. It showed the awful devastation caused to whole sections of streets in London.admit it.HE WAS MY CHIEF morbid need to be noticed is simply disgusting. Captured British officers say themselves that their own government is acting irresponsibly. the Parliament. 98 . Letter. If the poor British only knew that the damage they inflict on Berlin is a mere pinprick compared to London. etc. All the warehouses. always the same faces. I would like nothing better than that the British should sue for peace once we have disposed of Russia. preventing me from making my point that I should spend the war employed usefully somewhere —either in a hospital or an armaments factory. That is really a wretchedly long time. Yes. We have been here nine weeks already and we gather that we will be staying here until the end of October. Wandering over whole districts of the city. the same conversations.and moreover their officers . I have no choice but to soldier on here. And Mr Roosevelt laughs and looks forward to his British inheritance. A few days ago we saw a British newsreel which came from the United States. But he stopped me at once. It is really incomprehensible to me that the British do not see sense. often nothing to do all day. If the British . I am so sick of this being condemned to inactivity that recendy I attempted to convince the boss that he really needs only one secretary. FH Q Wolfsschanze 20 August 1941: Life has become rather monotonous.
30 August 1941: . . and as the compound there cannot be fenced off as well as at our present HQ the danger is too great. then it was mid October and now people are saying we will not be getting away before the end of October or perhaps even later. I would find it much more practical if we worked together. At first we thought we would be back in Berlin at the end of July. we spent a couple of days in Galicia and I found your letter on my return . rounded and protected against the wind by a thatched roof and scarcely a window * During a visit to the Eastern Front. (TN) 99 . Barracks for the security personnel and a tea house for Hitler were located near Strzyzow. I pray to God that the British soon see reason.THE RUSSIAN CAMPAIGN 1941-1944 After we have extended eastwards we do not need their colonies. Hitler and Mussolini spent the night of 27 August 1941 on their special trains at FH Q Askania-Siid. pp. cocoa. we can grow everything we need there and barter for the rest (coffee. he gets too little fresh air and is now oversensitive to sun and wind whenever he goes for a few hours’ drive. Our stay here at HQ is dragging on and on. This ‘living for ever in the bunker’ is healthy for none of us. Seidler and Zeigert. It is so clear and simple. On one side forests and on the other gently rolling hills. The countryside there is so lovely it really surprised me. Letter. Incidents occur every day.218—21.) with the South Americans. The boss does not look at all well. but it is more difficult to guarantee security there. On the hilltops cattle were silhouetted against the blue sky and the farmers followed the plough. The Ukraine and Crimea are so fertile. a purpose-built surface tunnel to house the train coaches near the village of Frysztak in Galicia (tunnel and other structures remain in existence). .* nearly everybody was in favour of it. etc. . Die Fiihrer-Hauptquartiere. FH Q Wolfsschanze. tea. twenty kilometres north of Krosno. . The peasants’ huts are quite romantic. A perceptible autumn chill is already in the air and if the boss decides to stay for the winter we shall all freeze. I would love to have remained in Galicia.
and then it is grim for those who have lost contact with the outside world. Hider was frequendy depressed. When the German armies were surprised by the terrible winter of 1941. here in the woods the atmosphere is depressing after a while. Excuse me for going on about this. suntanned and all barefoot. but totally in keeping with the landscape. wear a long dark cloth over the head and down to the hips. but when one is out one does not know where to begin because one is so utterly and completely set in this fixed existence and no possibility exists for a life beyond this circle. of course. but remained hopeful as before of a quick victory: ‘It is no more than a quite thin veil which we have to penetrate’. That whole region there is freer. a great dilemma: one longs to get out.’ The veil was not torn asunder and our stay at Wolfsschanze grew ever longer. we remain perpetually isolated from the world wherever we are: in Berlin. ‘we must be patient.HE WAS MY CHIEF anywhere. always the same limited circle. The circle around the boss is held together by the common experience. on the Berg or travelling. Another thing that struck me there was that I did not have the feeling of being locked in. and stuck fast in the Russian ice. but woebetide us when he goes away. I could see the farmers working in the fields and this gave me the feeling of being free while here we are always coming across sentries and having to show our identity cards. for then everything comes apart (this is also the opinion of Dr Brandt). the womenfolk. which somehow reminded me of home. but I see in it a problem for later which will not be easy to resolve. he said. a little shady. Even so. always the same crowd inside the wire. 100 . The Russian resistance will not endure. In front a well with a rusty chain. . a little secretive. . a few sunflowers. And therein lies the danger of becoming shy of people and losing contact with real life and . They keep close to their cows.
I can well imagine that the churches are full. but very clear diction.. I found very interesting. you must use every hour!’ I should like to have told him: what does he imagine. I have a very special liking for the Heimliche Aufforderung by Strauss sung by Schlusnus and on another occasion by a tenor from Graz who tends towards being baritone: Peter Anders (you should remember the name when buying records!). the Church etc. Incidentally a gramophone was introduced into the Fiihrerbunker a fortnight ago and now almost every evening we hear the songs of Strauss. for yesterday evening he said to us girls: ‘Children. year in year out and never get away. yes. . fawning voice. Letter. . I can do to enjoy my youth when we crouch down with him day in day out.. The boss has a principle of not making Special Announcements until a battle is definitely won because premature claims can alert the enemy to his danger and imperil lives. but I share your opinion (which is also that ofthe boss) that nothing can be undertaken at the moment.TH E RUSSIAN CAMPAIGN 1941-1944 Letter. Hugo Wolf and primarily Wagner of course. That will have to wait for after the war. but on the other hand deny the enemy any details. your other observations about morale in the Reich. I believe that the mood will very soon revive once more great successes begin to be announced. These songs are wonderful. one is quite lulled into love and warmth which apparently has an effect on the boss too. e. 6 January 1942: . I should like to know... which I read voraciously. FH Q Wolfsschanze. I wrote to you in reply at once a 101 . Yes.g. He often finds himself in a dilemma over this: he would like to calm the country. 15 January 1942: Scarcely had I posted my letter of moans and groans than your dear letter arrived. when Leningrad falls. The harvest will ripen in the next ten days anyhow. FH Q Wolfsschanze. theory and practice . he has a very soft.
’ 102 . which I cannot imagine is good for the soul. In the pre-Christmas period the Fiihrer took over supreme command. The record was set a few days ago when the boss had lunch at 1800. now usually gets under way after midnight (record to date 0200). In a way I am sorry but it is better if I save up all these things for my visit in March. which means we turn in between 0400 and 0500. but is postponed increasingly to an hour when normal people have their evening meal. Daranowski has gone on leave now and I shall have the pleasure in March. Then we were ordered to the tea session where the boss was exhausted. He explained: Anybody can handle the little bit o f operational leadership. but next I had a crying fit in my bunker and went back to the officers’ mess where I found a couple of brave 11 After dismissing Generalfeldmarschall von Brauchitsch on 19 December 1941. which is very important for health. which used to begin at 2200.HE WAS MY CHIEF long. I will just tell you today that the holiday here was miserable. no longer exists. To my way o f thinking there is no army general who can fulfil the role. The natural rhythm of life. Dinner had to be put back accordingly and our tea session in his bunker. and the mood swings from high to low without a transition period. which meant we had to keep quiet. and after a while nodded off. and were forced to suppress our merriment. Lunch will now be taken at 1400. long letter which I held back a few days because my outpourings would surely have been depressing for you. At New ^fear for example we were in officers’ mess for supper in a contented mood. I cannot describe exactly why. The task of the army supreme commander is to educate the Army to be National Socialist.11 His workload has grown immeasurably and scheduled mealtimes have gone by the board. The boss spent three hours in the situation conference and the officers who had arrived to wish him happy New Year waited around with long faces which they dared not crease into a smile. I have agreed with my colleague that from now on we will relieve each other regularly so that we have at least some private life. Hider took over supreme command of the army.
No office atmosphere. bare room. Now I am beginning to pity myself again. into a really snug lounge. Two vigorous men who cheered up the monotonous behind-the-front atmosphere wonderfully. I really could not stand the bunker any longer. and so I prefer to stay in the warm bunker. it made a terrible din. When working. Then we sang together that heart-rending sea shanty ‘We were lying off Madagascar and had the plague on board/ One can keep swearing never to touch another drop. who naturally detected that I had been in tears and I prompdy started again. I needed to exercise my persuasive powers quite often . so I will stop there . The fan whirled all night and swept my head constandy until every hair hurt. It is too cold. I have transformed our office. . but at least I have a window in the room ..whenever I saw something I fancied I gave the owner no peace until it was sacrificed to me. Therefore I slept in the office at the bunker entrance and had a window. we were told we would suffocate.THE RUSSIAN CAMPAIGN 1941-1944 lads from the SS-Begleitkpmmando. They attempted to comfort me with words and alcohol and finally succeeded. I noted down the following: A cabin in the bunker with fan. there is too much snow. . the roads are so iced over as to make a run a nerve-racking business. but in this miserable life it often seems to me to be the only way to overcome depression. If it was turned off. The so-called couch is not an ideal bed. I have not been doing much running.. although fresh air came in. which was formerly a stark. The women who have to work in munitions factories or are recruited for the trams or the subway trains have a damned difficult job but they have a big plus over us in that when their working day is over they can move freely and do what they want. a few days ago Sepp Dietrich and General Died were here for two days. Now I have taken to sleeping in the office. no fixed 103 .
4. My colleague. i. d. 8. FH Q Wolfsschanze. from 17. and that is essential in this monotony. but now with its blanket of snow looks rather romantic. 27 February 1942: ‘. Our mood is eternally Up or Down. he does not spend much time in bed which is often a nuisance. whose ordinariness was extremely depressing in the summer. Although the boss is always very tired.9. but since Todt’s unfortunate end12 the music evenings are rare. Despite that we now go for at least a one-hour run through the countryside daily.The rest of the day one spends more or less idle moping around. is now terribly depressed about the life she is missing.1940 Reich minister for armament and munitions. All resolutions to accept with a good demeanour whatever cannot be avoided soon dissolve after a few days.2. 104 . Letter. he took off in his personal He 111 next morning in adverse weather against advice and crashed on the airfield boundary. its expanses. which has nothing to do with indiscipline. From 1939 major general o f the Luftwaffe. The giant fields of red clover at sunrise. so inured have we become to it. but I found East Prussia very attractive. After two days of warm weather it got cold very suddenly. who always used to seem fairly nonchalant about it.1942 Gorlitz). but with many other things which I hope to be able to discuss with you in March .. After visiting Hider at FH Q Wolfsschanze on 7 February 1942.e. Previously we would often listen to records in the evening and could muse the time away. the blue sky and in winter the undisturbed snowy landscape.HE WAS MY CHIEF work hours.3. usually to the next village... Since 12 Fritz Todt (b. In itself the cold does not really bother us. Hitler often maintained that he had been found the swampiest and most climatically unfavourable region rich with biting midges possible. the daytime temperature is 17°C. but the keen easterly wind makes you really feel the cold. it is only the accursed wind.1891 Pforzheim. .
afternoons tea-house. Then we spent the evenings listening to his monologues. Politics never discussed. the history of humanity. His favourites were Beethoven symphonies. apparently because they went for birds. and nobody has anything personal to relate. If Hitler said: 'Aida. eyes closed. and in fact anything connected to the war was taboo. dragging. Hitler could no longer relax to music. the conversation is often rather indifferent. World events. Whoever dared was cold-shouldered. Before the disaster at Stalingrad on 2 February 1943 Hitler would organise an evening of record music from time to time. then one of the guests would call to the waiter: ‘Record number 123. On most topics we knew what was coming next and so the evenings required endurance. Hider’s influence was felt everywhere: either nobody had a private opinion or feared to express it. last act.TH E RUSSIAN CAMPAIGN 1941-1944 the tea circle always consists of the same people and no fresh ideas come in from outside. Es hat der Stein sich iiber uns geschlossen . 105 .. He would then sit. extracts from Wagner operas. He did not actually like cats. tiring and burdensome. Hider was the driving force for everybody in his environment. It was always the same records which were played and the tea-hour guests knew the catalogue numbers by heart. and songs by Hugo Wolf. macrocosmos-microcosmos and so on. the years of struggle. These were invariable: his youth in Vienna. or the adventures of the cat which suddenly appeared at FH Q Wolfsschanze one day. listening to the music. the battle front: these were not to be discussed during the tea hour.’ After Stalingrad. . It was advisable to broach innocuous themes such as his shepherd dog Blondi’s turbulent behaviour and disobedience. I noted later: Entertainment: every evening cinema. The talks go along the same old tracks .
jumping a two-metre high wall and climb a ladder. She was a very docile and clever dog. Hitler had no time for smaller dogs. for her devotion was limited to him alone. [I wrote to my friend. Eva Braun’s two Scotch terriers Negus and Stasi he denigrated as ‘hand-lickers’. . After breakfast every morning Hitler walked Blondi in the wild area around his bunker.HE WAS MY CHIEF but he gradually accepted ‘Peter’ to the extent that in the end he would get jealous if the cat selected somebody else’s lap to sit on. he said. ‘I am accused of sympathising with the Japanese’.. Many interesting subjects were addressed which one can read in Heim’s Monologe.] that we have a cat which often comes to sit and whose funny little games . able to do some tricks such as balancing on a pole. ‘but what does sympathising mean? The Japanese are yellow-skinned and slit-eyed.are something we are grateful for when the conversation palls. He is not allowed into the talk circle because of the cat but even when he is absent he enlivens the conversation . He would then tend to suspect that the dog’s affections had been undermined by a titbit of meat. He was very fond of the dog which he entrusted to a keeper (Tarnow). I like it especially when he jumps onto my lap.making us aware of a change in his situation . How fortunate. it was useless for anybody else to seek Blondi’s affections. Hider would often speak about the Japanese. an act which was strictly forbidden. His jealousy for Blondi was evident from his anger should the dog take an interest in anybody else. According to Hitler. but they are fighting against Britain and the United States 106 . for then I place my aching hands under his soft warm fur: that feels good. to which their owner responded: ‘Blondi is a calf’. We do have a Scotch terrier as well but nobody fawns over him because he is recalcitrant and obstinate (and the boss has sworn never to be photographed with him because the terrier looks like a ‘hand-licker’).
Ribbentrop intended to make a big thing of it with the radio and press. Ribbentrop appeared before Hider to deliver a report. One has to think of the time centuries ahead when we shall have to setde the score with the yellow race. Hider also spoke frequendy about photographer Heinrich Hoffmann. Ribbentrop. ‘then he was still slim and agile and went tirelessly about his work with his complicated old apparatus. intelligent. he told me. he reflects a while and then says: lJa.’ Hider often spoke of people in his wider circle. While Hitler lived. This promise extinguished all feelings of guilt in Hider’s followers.TH E RUSSIAN CAMPAIGN 1941-1944 and that makes them useful to Germany. In that sense I sympathise with them. mein Fiihrer.’ Hoffmann liked his drink. If I show Speer a plan and give him the job. it cannot be done like that’ and then provides the full reason. He had to slip under the black cloth and go through the most neck-breaking operations with the heavy camera to get good photos. or he objects: ‘Nein. modest and not a dour military head. I have the closest human relationship towards him because I understand him so well. but he has a great talent for organisation and grew to the task. He is a man of architecture as I am. Hider 107 . I did not think he would master his great objective so well.’ After the fall of Singapore to the Japanese. I believe it is possible’. but with Hitler’s death Speer’s fascination for Hitler died too. O f Speer he once remarked: He is an artist and his soul is linked to mine. Speer saw in him ‘The Extraordinary’. ‘Hoffmann was once a crazy young man’. and imbued in them a kind of faith equivalent to belief in God. In the small bunker office Hider told him: ‘I am not in favour of overdoing this. Speer was a convinced follower of Hider and even in internment I could see how deeply Hitler’s words ‘I take full responsibility for everything!’ still had their effect on him.
and it shocked Hitler to see Hoffmann in such a state. Professor Hoffmann obtained the picture recently in Vienna. It was not my ambition 108 . I also remember conversations in which Hitler told Hoffmann not to pay such exorbitant sums for his watercolours since he himself had only received 20 or 30 RM for each. but I think it probably finished up together with all the other paintings and works of art which I saved from destruction at the Berghof after the war. your nose looks like a rotten cucumber. On visits to his villa on Munich’s Ebersberg-Strasse he never neglected to show them.HE WAS MY CHIEF told him once: ‘Hoffmann. Finally he ordered Schaub and Bormann: ‘Please ensure that Professor Hoffmann is sober when in my presence. I hope you did not buy that picture? Hoffmann: I received it as a gift. He had not done so before in Hitler’s presence. and not so that he can let himself go. 12 March 1944 Rii/Wag During lunch today Professor Hoffmann showed Hider a watercolour painted by the Fiihrer in 1910. Professor Hoffmann collected nineteenth-century paintings and bought up all the watercolours Hitler had painted. the seller told me that for the price it is a gift. that is to say. A footnote about a conversation between Hitler and Professor Hoffmann on 12 March 1944 at the Berghof which I noted down indicates Hitler’s attitude to his earlier works: Obersalzberg. Der Fiihrer: Even today these things should not fetch more than 150 to 200 RM. What became of Professor Hoffmann’s collection is a mystery. and soon red wine will replace blood completely in your arteries/ This was said after Hoffmann turned up the worse for drink at the dining table. I have invited him so that we can converse. He was extraordinarily proud of the collection. It is madness if one pays more.’ How wounded Hitler must have been only became clear much later. Der Fiihrer: Hoffmann. I think that if I put a lighted match to your breath it would explode.
109 . 14 August 1942: I am only glad that you are sympathetic to my mental inertia. evolved from the concepts created in night-long work in those years. One should not forget that all my thinking today. In the four weeks since we have been at the new HQ I have not found the energy for writing private letters. If I am in a position today to sketch the ground plan of a theatre. I lack inner calm and the will for it. Unfortunately nearly all my sketches of that time are lost to me . Since the two thick Benrath tomes I have not really read anything. FH Q Wehrwolf. Hitler advanced his command post to FH Q Wehrwolf at Vinnitsa in the Ukraine. Letter. . I did not keep them. Unfortunately so many here have fallen victim to languor that no help can be expected from this quarter. yet I feel really good physically and mentally. I just lack somebody to plug the drain on my spiritual resources and revive me spiritually. and I saved a bundle from Schaub’s bonfire. ! I can confirm that Hitler was very attached to his architectural sketches and would not have disposed of them. however: Albert Zoller failed to return half and the rest I rather stupidly sold to Dr Picker. it is exclusively the result of my earlier studies. 1 RM would have bought me lunch and supper. it is not done by me while in a trance. the fruit of my mental efforts which I would never sell as I did the paintings. I used to study all night. many of Hitler’s architectural sketches were amongst them.. I would not have received much over 12 RM then. 80 RM would have kept me for a month. When at the end in 1945 Schaub emptied the contents of Hitler’s strong box at the Berghof and burned the material on the terrace. In the summer of 1942. those were my most precious possessions. I only ever painted enough to cover my necessities. I only painted these things to support myself in my studies.THE RUSSIAN CAMPAIGN 1941-1944 to be a painter. My architectural sketches which I made then. my architectural plans.
Here we had to search for our car. sixteen or seventeen aircraft got ready to fly to the east. I have wandered completely off the subject. etc. but the reality has a confusing mass of detail which makes it difficult to match the two. For Johanna Wolf. but only because there is nothing better. the air filled with the deep humming of vibrating wings and wires until one machine after the other rolled down the airstrip and lifted off into the air. all ready to take off. The worst is when you get hot under the collar at the stupid films and start to itch everywhere but stay seated because the only alternative is bed. People who understand it impress me very much. This is a science I would never be able to master. It was a very impressive scene on the airfield. Here and there the landscape is darkened when clouds hide the sun. spiritless. On 17 July. Naturally there is a certain similarity. stupid. And here you really feel that you are flying. and eventually set off in a heavy Krupp which is not at all suitable for Russian ‘highways’. The pilot invited me to sit in the cockpit which naturally I accepted gratefully. motors running. for to say that the landscape below looks like a map is a platitude. Right. for from there you get a quite different picture. but the panorama from the cockpit is greater and freer. She was totally exhausted and unable to lend a hand for the first few hours. now I shall give you a short report on our new HQ and about the removal to here. I found it interesting to follow the flight on a map. all the great machines clustered together. this was the last straw. who had not felt well during the flight. and a small section at that. 110 . or ground mist obscures the ground for a while until a piece of terrain reappears: but where we were on the map I could never determine. The last two evenings Johanna and I have reverted to watching the old silent movies.HE WAS MY CHIEF The films served up are ancient. Highways coloured red on the map prove to be grey and inconspicuous below (the easiest to spot were railway lines). After many hours we reached the destination airfield. The fuselage windows give a view to one side only.
two chairs. airless bunkers. colourful engravings and prints on the walls.say it quietly —into the most snug room in the whole HQ. crates and five typewriters filled it up completely. many flowers but mainly zinnias. This was our world. and then for contrast thistles in a black earthenware jar. Instead. when we saw our office. giant office cases. Thank God we could have a look round. . We had a housewarming which lasted until 0600 . By virtue of my organisational skill and experience I have been able to convert it . and often the weather changes as quick as a flash. our hopes were for bright rooms with large windows. the bedroom had a single square window twenty-five centimetres along each side and covered with a green gauze. you shiver terribly and it is quite certain that later one will be disabled with rheumatism. To the left and right a door opened to reveal a small aperture containing a narrow bed with nightstand and a rack for the cases. one upholstered. Only I could have done it: a couch (sofa with coverlet and dark-green/blue padded back rest. I will tell you orally. Ill . covered with a red-fringed and spotted blanket. and after I moved into another room temporarily for eight days finally I ferreted out a decent office with an alcove behind a curtain. Since we have lived long enough in dark. . It is always the same whenever you start at a new HQ: the beds are always damp. The office was so narrow and small that we could hardly move in it. above it some wall drapes which would probably be better put to use as bed mats. This window’ was our greatest disappointment. Daytime temperatures are really high (it is not unusual to have 45-50°C) but at night it is disproportionately cool. and mine began. Our luggage. They look really attractive but are awfully damp inside. the other with a rattan seat. a carpet.TH E RUSSIAN CAMPAIGN 1941-1944 Her depression got worse. The living accommodation is similar to Wolfsschanze except we have fortified houses instead of concrete bunkers. in front of the couch a little table I made myself from a suitcase rack and a wardrobe shelf.
Unfortunately the water drains away frequendy and is in any case barbarously cold. On the evening of hot days we have a mad purge on the insects which enter despite the gauzed windows: they get in through every crack and hum around you in bed.a fifteen by ten metre swimming pool. The food has improved enormously. the largest of its kind in Europe. a process that takes two hours in Germany. We have a wonderful innovation . if you get malaria. and once the whole army of them has gathered I draw the curtain again and creep back to bed leaving the light burning. They skin a cow in the ridiculously short time of thirty seconds. Some 250-300 catde are 112 . A large market garden provides us with fresh vegetables. As we live from the local products of the land we have plenty of butter in the morning and often an egg. and keep on and on until your nerves can stand no more and you get up cursing. That was a damned resdess night! Frank Thiess wrote in one of his books that all women are stupid. they shriek equally loudly for an innocent mouse as a tiger. With a loud cry I ran out to the couch and lit the lamps in the bedroom to attract the mosquitoes there. The other night scarcely had I laid my head down than I heard a rustling and a nibbling near my bed: I had left some milk to curdle and the mice had found it. The factory is designed on American lines. one revolts against taking it each evening but you have to force yourself.HE WAS MY CHIEF The mosquito plague is worse here than last year. He is probably right. a serious disciplinary offence. that counts as a self-inflicted injury. this attracts the mosquitoes out of the alcove and into the light. and here we have the dangerous Anopheles strain whose bites can give you malaria.000 hectares. In the city there is a slaughterhouse on 100. I had a chance to visit and watched the whole process from stunning the animal to the final sausage or meat paste. a continuous production line. Recently at night I have taken to opening the curtain to the living room and lighting all lamps. There is a prophylactic called Atibrin which tastes ghasdy and bitter.
As it weighs seventy tonnes. where they are kept for twenty-four hours in tropical heat. chosen because they are more industrious . A few sample tins are taken from each run for airtightness testing. which is done in a culture cabinet. in La Traviata) are a cross-section from the twentieth century: short. turned every day and freshly salted. it is a ghastly hopping affair which they should drop. They cannot waltz.g. naturally terribly neglected with woodworm in the ceiling. The actors are like wax figures. The skins are salted and stored for four to six weeks. It is interesting that every opera house has a large installation for ballet.000-15.. The experts are unable to be precise.g.TH E RUSSIAN CAMPAIGN 1941-1944 slaughtered there daily and cooked to make 12. The costumes (e. it will be a notable event.. three-quarter length. I got to know the German city and regional commissars at the beginning of our stay and had the chance to see a few things. Provided no defective tins are discovered. combs and cigarette butts. The honest presentation allows all these defects to be overlooked. in buttons. and it is just a question of when it will fall in. I saw La Traviata and Faust. fringed (like we had in the 1920—24 period). In the city there is a theatre dating from the Tsarist era. the batch is then consigned to the Front. the men with fixed expressions and mechanical gestures making them appear wire-operated. The performers make the best of what they have at their disposal. e. They are outstanding in their own field. These were not a success. Most of the employees are women. the ballet is grandiose in parts. long and patchwork. This factory uses every last piece of the animal. which ends up as soap. and in a way one finds it enthralling. The orchestra plays cleanly. It is really an enormous business. Perhaps it is the training. tomorrow or in a hundred years. The ballet master and prima donna could perform in Berlin and receive rapturous applause. a crass characterisation of the Asiatics. 113 .000 tins of meat. The pair does a Mongolian dance which brings their racial origins to the fore in the mime. Most of the voices are outstanding.
sunflowers. for example. the more the question presents itself as to who will be carrying through these great projects in the future. Soya bean growing has failed so far. There was German rump steak. One comes to the conclusion that the foreign people* are not suitable for various reasons. * Foreign people = Frem dvol\ i. it does not ripen. and therefore our generation will not be able to sit back and relax. The longer one spends in this immense region and recognises the enormous opportunity for development. It was a glorious day. has now been introduced. (TN) 114 . the German element and the foreign people would occur. breakfasted with a district farmers’ leader who lives by the inland sea ninety minutes away. The fields are so beautiful with black wheat in bloom. The fields needed a lot of initial work because the Bolsheviks never spread manure.HE WAS MY CHIEF I took part in a tour of various collective farms. We started off at 0800. Then we did the tour. It will take much toil until the yield reaches the hoped-for targets. but there are many possibilities to achieve great things. Our people immigrating here do not have an easy task. which ripens six weeks earlier. must be at least as large as during the war. and their territorial gains. and ultimately because in the course of the generations an admixture of blood between the controlling strata. the Bulgarian variety. washed down with a glorious egg liqueur. it makes me feel at home somehow. presumably the settled inhabitants of the Ukraine before the Nazis arrived.e. the Roman Empire. That would be a cardinal breach of our understanding of the need to preserve our Nordic racial inheritance and our future would then take a similar course to that of. the red and pink poppies were wonderful but have now started to seed. Everybody who takes a closer look at things comes to the conclusion that the achievements of our people after the war is won. scrambled egg and cooked cheese. I love the countryside here very much.
TH E RUSSIAN CAMPAIGN 1941-1944 Now I have gone wandering off track again. After lunch we toured one of the giant sugar factories destroyed by the Bolsheviks. It offers a really entrancing view of the city in the distance and over a fairly broad river which winds through hilly meadows and woods and reminds me of the Weser. the only female. Anyway. the wild garden romantic (I just loved it. I have a soldier’s dictionary and try to make myself understood. and it is situated on a small mountain (the infantry have named it ‘Obersalzberg’). The unmade streets are miserable: 115 . In the evening we often walk to the nearest village where the children always look out for us. a very sharp fellow. then coffee and doughnuts were followed by a visit to the inland sea. The others laugh at me but I succeed. an extremely well-fed Schleswig-Holsteiner who has kept the business in wonderful order. and therefore the hen in the basket! It did me really good. told us. The house is a ruin. The women and young men have had Bolshevism hammered into them and I should not like to run into them alone on a dark night. In the evening we sat at a long table in the garden by candlelight. He lives in a former convalescent home for children. mostly blond and blue eyed. I am beginning to favour smaller circles where people can get to know each other. We received invitations to visit the city commissar. It was a cheery event! I. In the evening the table almost sagged under the weight of the plates. They are strikingly beautiful. but now that the mood has caught me I will tell you a little more. and so back to the district farmers’ leader. which was quite romantic except there were too many people there. The district commissar has just rung me with his praises. I am not so keen on circular paths and borders). it gives us a lot of fun. and we laughed ourselves silly at the stories the regional commissar. saying that everybody on the collective farm tour found me inspiring and I should come alone next time too! I think that this letter has gone on too long for you. Most of the old men from the Tsarist time have fine heads and are very polite.
and gradually life began to be more acceptable for us there. I promised to return to the mess afterwards. all made me aggressive. I rebelled inwardly and then something happened one evening at tea which exposed this aggression to everybody. then I went to the officers’ mess from where Hitler’s manservant winkled me out just as I was getting comfortable. this eternal monotony and the repetitive daily tea hours. When the bitter winter of 1941 halted the advance. . the interiors simple. I knew that he would be in a bad mood. How awful a smoker’s stomach must look. Personally I was suffering very much from the constant inactivity and was glad whenever Dr Brandt. . In the hope that the tea session would perhaps not last too long. Unfortunately I had not been able to convince the boss that he only needed one secretary. Gradually along came a cinema and tea-house. Today’s theme was that old chestnut. like soap in which one’s vehicle bogs down. like encrusted lava over which the vehicle rocks and shakes. forcing them 116 . for the situation at the Front was not good. This enforced indolence. Torn from a convivial environment. white with a thatched roof. but he would not release me. As already mentioned. The day had been as dull as any other. when dry. Smokers lacked consideration for others.HE WAS MY CHIEF after rain. smoking. the more FH Q Wolfsschanze began to be more permanently equipped. this affected his demeanour. in the early phase of the Russian campaign Hitler was nearly always in good humour and not averse to the odd joke. That’s enough about the land and people . who had a substantial correspondence as president for hospitals and health. I now came to a Fiihrer who wore a frown. The longer the Russian campaign lasted with its to-jng and fro-ing. From afar the houses look quite enchanting. After dinner I saw a film in the hope of relieving my boredom. He would start out with special reference to narrowing of the arteries caused by smoking. I was anxious to do useful work elsewhere. gave me a few hours’ work.
let the poor boys (I might even have used the word ‘swine’ here) have this pleasure. chipped in and declared: ‘Ah. Hans Junge gave Johanna Wolf and myself a long look and said that tea would be taken today without the ladies. he often said. Without another word he rose quickly and took his leave ‘ice-cold’ and with an aggrieved expression. They should be given chocolate. ‘that Eva were secretly smoking. they don’t get any others!’ Ignoring my idiotic outburst. but I. Now I brought up the big gun and said.THE RUSSIAN CAMPAIGN 1941-1944 to breathe in polluted air.’ When her sister Gretl made him the pledge never to smoke again. already in a rather spirited frame of mind from my visit to the officers’ mess. he made her the present of a valuable sapphire ring with diamonds. mein Ftihrer. from which I finally saw what I had done. emphasising the depth of his antagonism to smoking. The campaign would begin by having a death’s head printed on every cigarette pack. Hitler said that because tobacco products were distributed to them freely. not cigarettes. saying: ‘There is no need 117 . Albert Bormann had been told to inform us officially. Later that afternoon when Hitler called me for dictation I attempted to apologise but he cut me short. Next afternoon when I enquired of the manservant in what mood the boss found himself today. mein Ftihrer. Hitler went on to explain how nicotine and alcohol ruined people’s health and addled the mind. ‘If I should ever discover’.’ At that Hitler understandably clammed up. Everybody nodded in agreement. When I asked him. Hoffmann smokes and drinks all day yet is the most agile man in the shop. Bormann admitted in embarrassment that the boss was annoyed with me and would not be requiring the ladies’ company at tea. He had really toyed with the idea of outlawing smoking anywhere in Germany. referring to photographer Heinrich Hoffmann: ‘One cannot really say that. even young soldiers who had not been smokers previously had now taken up the habit. At that time I was a heavy smoker. then that would be grounds for me to separate from her immediately and for ever.
It was to be many months before Hider forgave me for myfaux pas. During the night flight he dictated his orders to the troops to stand firm and spoke to me for the first time again on a personal note although the actual reconciliation did not follow until March 1944. as the Front began to pull back. and went to the dining car thinking that all was forgiven. Winfred Wagner etc.’ I misinterpreted this as a request and a gesture of reconciliation.HE WAS MY CHIEF for you to apologise/ maintaining an attitude of cold reserve.1 had severe sciatica and had gone to Bad Gastein to take the cure. who had meanwhile married. I was very moved 118 . Frau Troost. but there he continued to ignore me. In September 1943. On the evening of my return I sat at Hider’s right and left of Frau von Exner. resumed her duties. This made me ill. During my absence. Frau von Exner had been given employment and the convivial tea sessions had been resumed. Dara. I no longer went to the dining car but had the meal served to me in my compartment. Frau Goring. When Johanna Wolf tried to repair the damage. This white card bearing his name and the sovereignty symbol engraved in gold was a very special honour which he used only for messages to ladies he held in high esteem such as Frau Goebbels. This went on for some time until one day Albert Bormann appeared and said: ‘Little Miss Schroeder. On my birthday he sent me a bouquet of long-stemmed roses and a handwritten message of good wishes. A dietician-cook skilled in specialised diets. After the usual kiss of the hand in greeting and an enquiry after my health he did not speak to me again. he decided to fly to the most advanced line near Zaporozhye-Dnepropetrovsk and requested me to accompany him. and I was away from FH Q for a few weeks to take the cure. Henceforth I no longer existed for him. he replied bitterly: ‘that he had the feeling that it was a bore for us to be with him and he did not want us to be forced to sacrifice our evenings’. the boss has asked me why you do not come forward. Since for example on train journeys he would ignore me even when we were sitting at the same table.
During the Russian campaign Hitler’s stomach troubles had begun to cause him concern. which everybody agreed tasted wonderful (very thin pastry with thick layers of apple slices and if possible a small topping of whipped cream). especially the Viennese desserts and the wonderful apple pies. On a visit to FHQ. Frau Marlene von Exner and later Constanze Manziarly. This letter apparently impressed him. for it became a conversation piece on several evenings around the fireplace at the Berghof where he was then staying temporarily. Hitler enthused over the varied menu. this being very acceptable to Hitler. and he had discussed the matter with the Romanian head of state Antonescu who had suffered for years from the same thing. This delighted him and he made her the present of a tiny dog similar to a \brkshire terrier. A small diet-kitchen was set up at FH Q and Frau von Exner set to work with a will. Frau Marlene von Exner. who had cured him by means of a strict but tasty regimen. After the cure at Bad Gastein I was told to take a slimming course with Professor Zabel at Bischofswiesen near Berchtesgaden. On Hitler’s instructions Dr Morell sought a good dietician-cook at the Vienna Clinic and succeeded in hiring Frau von Exner. but when I returned I found that it had been resumed. She enlivened the conversation especially when she spoke about her home town of Vienna. which terminated with a special diet course at Bircher-Benner. very temperamental and intelligent. Hitler considered this dog to be unworthy of a statesman because it was below Hitler’s approved size for dogs. with Frau von Exner as an extra guest. Marshall Antonescu met Frau von Exner again. Here I would like to add something about Hitler’s two dieticiancooks.THE RUSSIAN CAMPAIGN 1941-1944 and mentioned in my letter of thanks that I had now made a vow never to smoke again. The nightly tea session had been abandoned some time previously after an altercation when Hitler had gone into reclusion. Antonescu recalled an assistant in special diets at the University Clinic of Vienna. and Reichsleiter Martin Bormann was given the job of finding a prize-winning fox terrier for 119 .
1913 Diilseberg/ Altmark).SS-Panzer Division Wiking. 8. 15 Helene Maria ‘Marlene’ von Exner (b. Reichsleiter Bormann was ordered to ‘arianise’15the von Exner family. end 1943 Aryan genealogy examined and found defective (Jewish grandmother). young brunette.4. It is assumed that Hitler was not happy with this arrangement and on 28 July 1944 Darges found himself on the Eastern Front with 5.5.5. This all happened at a time when consideration was being given to reinforcing the bunker at Wolfsschanze against air attack and therefore FH Q was transferred temporarily to Obersalzberg.14 Frau von Exner was sent on leave using this as an excuse. 120 . tall.HE WAS MY CHIEF Frau von Exner.1917 Vienna). 13 This was SS-Obersturmbannfuhrer Friedrich Darges (b.1943 employed by Hider. Frau von Exner survived the war and was living in Austria when this book first appeared in Germany. Hider would no longer touch the food she prepared. 15. 8. to the Swiss Bircher-Benner recipe and then brought up to the Berg by car. During Hitler’s stay on the Berg his food was prepared by the young Tyrolean Constanze Manziarly (not Manzialy as often misspelled) who was employed at Professor Zabel’s sanatorium in Bischofswiesen.1944 dismissed from service. and his stomach symptoms reappeared. which called into question her pure descent under the Aryan Law. and it was discovered that a grandmother of hers had been a foundling. Unfortunately I recommended that she should accept and so this beautiful.1948 released. and she was dismissed from service shortly afterwards. his last day there. Hitler wanted Darges to marry Eva Braun’s sister Margarete. 30. 14 Hider left FH Q Wolfsschanze on 23 February 1944 and remained at the Berghof with short breaks until 14 July 1944. 16. Unfortunately the luck of the charming Viennese cook took a tragic turn when she fell in love with one of Martin Bormann’s adjutants. 8.4.1945 interned by U S Army.2.13 Her racial origins were examined. Fraulein Manziarly was invited to join the staff I was taking the cure at the Zabel sanatorium at the time and she asked my advice. Bormann was ordered to ‘arianize’ the family. Shortly before returning to the Rastenburg HQ at the beginning of July 1944. This was easier done in Austria than Germany and involved juggling old birth certificates to change the line of descent.7. but Darges preferred Frau von Exner.
’ At the end in 1945 Fraulein Manziarly had her diet-kitchen in the Fiihrerbunker in Berlin and often dined with Hitler. after April 1945 fate unknown. It was a very hot summer with swarms of mosquitoes and biting midges in the swampy meadows. Nothing more was ever heard of her. 14. The sentries wore mosquito nets over their heads. Greek father. Austrian mother. This often happened because landmines were laid off the paths and wild animals frequently set them off.THE RUSSIAN CAMPAIGN 1941-1944 a gifted pianist. He always had premonitions. When I said ‘alone’ he invited me to dine with him in his bunker.4. and again: ’Nothing must happen to me. 121 . he was not feeling quite well. He told me this and even said: ‘I note that there is something afoot’. although it is said that she took her own life using a cyanide capsule provided by Hitler.16 After completing the supplementary cure with Professor Zabel in July 1944 I resumed my duties at FHQ Wolfsschanze where the bunkers had been reinforced against air attack. probably in the guest hut!’ Suddenly the barriers 16 Constanze Manziarly (b. After leaving the Reich Chancellery at the beginning of May 1945 she disappeared mysteriously. The flat roofs had been camouflaged with grass and trees to prevent their being spotted by air reconnaissance. September 1944 employed by Hider as dietician-cook. saying: ‘I have a cook with a Mozart name. the day before the assassination attempt. Knowing that I was also persevering with the Bircher-Benner diet he asked me if I would be eating in the officers’ mess or alone. Upon my return Hitler was as warm to me as he had been in earlier times. He felt that an attempt on his life was being planned. there is nobody who can carry on the business.’ The situation conferences at that time were being held in the social room in the guests’ barrack hut. People were shouting excitedly for doctors: ‘A bomb has gone off. served Hitler as his dietician-cook.1920 Innsbruck). Around midday on 20 July I heard an explosion. He was quite taken with her. On 19 July 1944. This time it was different.
A visit by the former Duce was 17 Wilhelm Arndt (b. A square piece of cloth had been torn from the tunic. 1944 appointed manservant in rank of SS-Hauptscharfuhrer. The stenotyist sitting near me had both legs blown oft I had extraordinary luck! If the explosion had happened in the bunker and not in the wooden hut.4. towards 1500 that afternoon he summoned me. nobody would have survived it.1945). When I said I had not. 6.7. 22.HE WAS MY CHIEF were up everywhere.17 Dr Morell was terribly shaken and emotional after the incident and Hitler had to calm him before the doctor could tend to Hitler’s injuries. it was wrecked beyond imagining. he refused to lay up in bed as the other officers had done and was kept going by Dr Morell’s injections. d. As I entered his bunker he rose with some effort and gave me his hand. Although Hitler suffered concussion. He looked surprisingly fresh and spoke about the assassination attempt: ‘The heavy table leg diverted the explosion. I was just thinking that today I would definitely not be dining with the boss when I heard: ‘Nothing has happened to the chief. but the hut has been blown up!’ Contrary to my expectations. don’t you remember?’ Hitler then asked if I had seen the conference room. since the area was cordoned off. a ruptured eardrum and flaking of the skin. Killed when a Ju 352 of the Fiihrer-Staffel from Berlin-Staaken in which he was a passenger crashed at Bornersdorf. Hitler then described how the attempt had affected his valets: ‘Linge was absolutely furious and Arndt stood there with tears in his eyes. He had his manservant bring it to him and showed me the trousers. 122 . H e was tall and blue eyed. as I confirmed from him at lunch. He was proud of these trophies and asked me to send them to Eva Braun at the Berghof with the instruction that they should be carefully preserved.1913. and Schroeder stated o f him that he was Hitler’s favourite valet. But haven’t I always anticipated that happening? I told you yesterday. he said I should at least see his tattered uniform. in strips and ribbons from top to bottom and only held together by the waistband.
Keitel with bandaged hands. but in response to my enquiry he assured me: ‘Certainly I shall receive him. I will ensure that nobody will ever again be able to displace me. then they are deceiving themselves. and the only person who can avert it. They do not know the plans of our enemies who intend to destroy Germany so that it can never rise again. Shortly before midnight we went there with Hitler. I always told Schmundt but he is a Parsival and would not believe it. It is the salvation of Germany. for imagine what lies they would tell the world about me if I did not!’ When we assembled with Hitler for afternoon tea we had already received news of StaufFenberg’s arrest. The lightly wounded officers who had survived the attempt were also there: Jodi with bandaged head. but when he found out that this had led to the arrest of all the close conspirators he stated in satisfaction: ‘Now I am calm. At first Hitler was infuriated that Stauffenberg had managed to make it as far as Berlin. I have no choice. I am the only person who knows the danger. Now I have the proof: the whole general staff is infected.’ Hitler continued: These criminals who wanted to rid themselves of me have no idea of what would happen to the German people. And if they think that the Western Powers without Germany are strong enough to resist Bolshevism. and I expected Hitler to postpone it. 123 . It was thanks to Providence that the German people had been spared great misfortune. A radio van was ordered from Konigsberg and a transmitter unit installed in the FH Q tea-house. Now I finally have the swine who have been sabotaging my work over the years.THE RUSSIAN CAMPAIGN 1941-1944 listed for the afternoon. Just after midnight on 21 July 1944 Hitler made a short speech to convince the German people that he had survived unscathed.
surround myself with intelligent. In September 1944 Himmler provided him with a report on the Resistance involving the military in 1939. Every day enemy aircraft overflew the HQ. one should take a leaf out of Stalin’s book. Towards the end of 1944 the stay at FHQ Wolfsschanze became increasingly anxious. and let somebody else take over the affairs of government. Hitler lay apathetic for several days but then made a gradual return to work at the beginning of October 1944. The death of Wehrmacht chief adjutant Generalleutnant Schmundt made a deep impression on Hitler. And so long as they know that 124 . That has been our great sin of omission. for he had held weighty and portentous conversations with him. He did not want to hear talk of transferring the FH Q to Berlin although he was being urged to do so from all sides.’ Here he was talking more to himself and suddenly changed the subject as if he had said too much. Dr Morell diagnosed retention of bile caused by gall bladder spasms. and when I am old the elder ones can fall in with my tempo. ‘We liquidated the class enemy on the Left’. he purged his army ruthlessly. ‘but unfortunately we forgot to do the same with the Right. He explained: ‘It is my duty to remain here. Then I will write my memoirs. At the Berghof he once said: After the war I shall hang my uniform on a peg.HE WAS MY CHIEF In early September 1944 Hitler suffered severe stomach and intestinal problems.’ He went on: ‘One cannot fight a war with incapable generals. He put himself to bed but did not improve. withdraw. Hitler did not like the officer caste. Hitler said. Hitler expected a surprise air raid at any moment and warned people to use the air raid bunkers. My two senior-serving secretaries will stay with me and write for me. My soldiers will also never permit the frontline to be pulled back to the Fiihrer’s HQ. clever people and refuse to receive another officer. They are all strawheads and simple-minded. The younger ones will get married and leave. It keeps the people calm.
It was near Bad Nauheim.’ All the same the HQ was removed to Berlin at the end of November 1944 as the Front edged back ever closer. which Hitler promised would bring the turn in our fortunes in the West. Towards the end of 1944 he waited impatiently for the right moment to give the order to strike. the nearest railway station was called Hunger. which favoured the concentration of troops before the Offensive began. 19 Hitler left Berlin on his special train on 10 December 1944 and returned to Berlin aboard it on 16 January 1945. received a gold watch in gratitude for his correct forecast. The expert who predicted a period of fog during December 1944. however: this was left to the meteorologists. 18 Hitler left FH Q Wolfsschanze on his special train on 20 November 1944. At first Hider held situation conferences in his study in the new Reich Chancellery and his meals in our Staircase Room. From mid December 1944 to mid January 1945 we inhabited FH Q Adlerhorst19 and spent Christmas there. His intuition played no decisive role in setting X-Day. He consulted them daily. I asked the Fiihrer: ‘Do you believe. that we can still win the war?’ He replied: ‘We have to. mein Fiihrer. they will be all the more determined in their struggle to stabilise the Front. The enemy remained unaware of the location of FH Q Wolfsschanze throughout its period o f occupation. Hitler. After the failure of the Ardennes offensive we returned to Berlin. The FH Q consisted of small fortified huts in wooded terrain and also had subterranean bunkers.THE RUSSIAN CAMPAIGN 1941-1944 I am holding out here. 125 .’ Dara reminded me of this conversation later and said she had wanted the ground to open up beneath her when she heard my question.18 The preparations for the Ardennes offensive. he then tended to remain in his bunker. Since both events were later interrupted frequently by sudden air raid alarms. Dara and I once stood under the trees in the open watching the great formations of Allied bombers heading into the Reich in bright sunshine. were begun at FH Q Wolfsschanze.
The boy discovered from his mother shortly before her death the identity of his father —allegedly Adolf Hitler. As I have said. but it seems likely from the moment when he decided to become a politician that Hitler renounced such pleasures. It may be that before and during the First World War he had sexual experiences with women. For Hitler. ‘My lover is Germany’. he emphasised repeatedly. and an illegitimate son. that Emilie was an ugly name by observing: ‘Don’t say that. Emilie is a lovely name. these two cases may be true.1 Perhaps the frequently rumoured missing M a n y l ie s hav e b e e n 1 Walter Buch mentioned after the war in 1945 that Hitler had told him: ‘The lady I love is called Germania/ 126 . gratification came from the ecstasy of the masses. He was erotic with the women by whom he surrounded himselfj but never sexual. Jean-Marie Loret. In December 1933 he contradicted my assertion. as already described. it was the name of my first sweetheart!’ In 1917 during the First World War Hitler is alleged to have deserted an eighteen-year old French girl whom he had made pregnant in France. is supposed to have been the result. Subsequently he attempted to establish Hitler’s paternity by genetic research at a Heidelberg institute and elsewhere.Chapter 9 The Women Around Hitler presented to the world respecting Hitler’s relationships with women under this alluring heading.
Bis zum Untergang.’ 4 Emil Maurice (b.1972 Starnberg). d. in December 1927 terminated friendship with Hider following an argument over Maurice’s engagement to Geli Raubal. which Linge had seen on a picnic when both urinated against a tree. which led to his abandoning all further sexual activities. It is possible that Hitler might have been mocked by a woman.). ‘What type of wood was it that everybody used the same tree for peeing?’ she asked.1.’ This happened allegedly in the 1920s.2 When Professor Kielleutner the Munich urologist returned to Henriette von Schirach a book he had borrowed from her about the residences of well-known Munich townspeople. Herbig.THE WOMEN AROUND HITLER testicle is also true. Werner Maser (ed. 594 (Hitler was No. Maser quotes Linge as saying that Hitler had perfectly normal genitalia. He used eroticism. 6.3 In my opinion Maser puts these words in Linge’s mouth in order to prove the possibility of the Hitler-son. and the doctor had never seen or examined his lower regions. sexual gratification occurred mentally. Munich-Berlin 1980.2. he Maurice —had to search for girls for Hitler while he was engaged in 2 Dr von Hasselbach. ‘Who would have dared to make a point of looking at Hitler’s genitals while he was urinating?’ And in any case: ‘Every man I asked assured me that it would not be possible to catch sight of a man’s testicles in the manner stated. 127 . 555). Undoubtedly Hitler enjoyed the company of beautiful women and was inspired by them. she asked him: ‘What did you treat Hitler for?’ Kielleutner replied: ‘Hitler had only one testicle but I was not able to help him because he was too old.1897 Westermoor/Schleswig-Holstein. he told her that he had underlined in pencil the names of all the prominent people he had treated. Because of the great objective he had set himself and to which he was totally committed.4 Hider’s chauffeur. When she read through and saw Hitler’s name underlined. 19. 3 Heinz Linge. told me that whenever he drove Hitler to this or that town. imprisoned at Lansberg with Hider for his part in the 1923 putsch: 1925 entered SS. stated after the war that Hitler had a definite aversion to showing his body. Schroeder wrote that she considered Linge’s ‘looking at Hitler’s genitals while he was urinating’ to be a fabrication. 1919 N azi Party member No. but not sex. from 1921 H ider’s chauffeur. Emil Maurice. one of Hitler’s official surgeons.
Afterwards he would sit down with them and converse. When she announced her intention to marry a painter from Linz.5 Hitler brought along his old landladies Frau Reichel and her mother Frau Dachs. These passages appear in Zoller’s book and are therefore authentic. Hitler aus nachster Nahe . Later Geli Raubal occupied one of these rooms. H ider’s chauffeur Emil Maurice in 1927). the man who wrote this letter was a violinist from Linz sixteen years Geli’s senior. After moving from Thierschstrasse. who would have liked her to have become a Wagner opera singer. He paid them. According to Ada Klein it is also incorrect for Dr Wagener to have said that Hitler would not allow Geli to perform on stage. According to a statement by Geli’s mother to American CIC interrogators in 1945. 7 Schroeder had this letter with her in internment at Augsburg and lent it to Albert Zoller who failed to return it.7A letter from the painter which I 5 Hider rented a room at Thierschstrasse 41/1 from 1 May 1920 to 10 September 1929.g. Geli did not want to take singing lessons! Finally she allowed herself to be convinced by her uncle. the household was run from the outset by Frau Winter and not Frau Raubal.98: in the apartment at Prinzregenten-Platz 16 (actually two apartments. but never requested services. Geli was flattered that her famous uncle should be so devoted.HE WAS MY CHIEF conferences. p. the daughter of Hitler’s half-sister Angela Raubal.6 Hitler convinced Geli’s mother to impose a one-year separation so that the couple should prove their love for each other. 6 Geli Raubal had several relationships with men whom she hoped to marry (e. He loved this girl very much but apparently did not have sex with her. He pampered her and did everything he could for her out o f fondness. but he controlled her every move and jealously fended off all her admirers. The exception was Angelika ‘Geli’ Raubal. left and right). 128 . Here I must correct an error in the book by Dr Wagener. From 1929 this attractive lusty girl was installed in Hitler’s flat at Prinzregenten-Platz 16.
Your uncle has an overbearing personality. Another mystery about the letter writer is the fact that whereas Schroeder confirmed in her shorthand notes that the suitor had previously obtained the consent o f Frau Raubal to her daughter’s marriage.THE WOMEN AROUND HITLER salvaged from Schaub’s bonfire at the Berghof in 1945 contained the following extract:* Now your uncle.. I find it difficult to accept the existence of these faults in others. whose influence on your mother is well-known. but if she did one must question her motives in including it at the place in the narrative where it appears. this extract from the letter of her unnamed fiance must have been written long before the suicide. and the identity o f the writer. I do not understand * In fact. (TN) 129 . He always puts obstructions in our path to block our mutual happiness although he knows that we are made for each other. Whether Schroeder knew the actual date when the letter was written. The year of separation that your mother has imposed on us will only bind us closer to each other inwardly. As I always make the effort to think and act honesdy. Unfortunately we are not able to respond to this repression until you reach your majority. the miraculous saving of the letter from Schaub’s bonfire (see Chapter 15 for the full story) and its use in Schroeder’s narrative. and the extent to which Schroeder knew the circumstances. we shall never know. Since the period of one year’s separation would fall entirely within the period when the girl was not of legal maturity. the date of the letter must have been before 4 January 1928. However I can only explain your uncle’s actions as being grounded in selfish motives towards yourself He simply intends that one day you will belong to nobody but him .. pose some intriguing questions about Geli Raubal's death. is attempting to manipulate her weakness with unlimited cynicism. by 1945 Frau Raubal remembered nothing o f the man except that he was a ‘violinist from Linz’ sixteen years older than her daughter. In his Party they all cower before him like slaves. for Geli Raubal reached her majority at age twenty-one on 4 January 1929. The mystery of the fiance’s identity. And at another place: Your uncle continues to see you as the ‘inexperienced child’ and cannot understand that you have matured meanwhile and want to shape your own future.
I found very interesting. 8.1929 married Georg Winter. who wanted to study singing. 29.1945 interned by U S Army. was installed by Hitler in his apartment. and he needed to speak about her. 17.1970 Munich). He hopes that during this year (of separation) he will change your mind.10. This had nothing to do with any immorality between Hitler and Geli.8 She was discreet and tight-lipped and thus enjoyed Hitler’s confidence during the period between 1929 and 1945 when she was his housekeeper-cook at Prinzregenten-Platz 16/11.HE WAS MY CHIEF how. a former N C O and manservant to General Epp the Freikprps leader. During the Prinzregenten Theatre festival in early 1930 a beautiful silver-fox fur she was wearing caught my eye. Geli. with his keen intelligence. 130 . One inferred distinctly that he was grooming her to be his wife.2. but how litde he knows your soul. According to Frau Winter.10. Geli accompanied him everywhere and was the only woman at his side on his visits to the theatre. During the tea hour in the Staircase Room at the Radziwill Palace. d.1905 Pfakofen/Regensburg. the daughter of Hitler’s half-sister Angela Raubal.1929-May 1945 Hider’s housekeeper at Prinzregenten-Platz 16/11. for one day Geli could stand the pressure no longer and shot herself on the day of a quarrel with her uncle. but of a platonic love saturated with jealousy. When concluding some anecdotes about Geli he said once: ‘There was only one woman I would have married!’ and for me the sense of this declaration was unmistakeable. What she told me about Geli Raubal. And in that he was surely right. During internment postwar I got to know Frau Winter. Frau Winter was firmly convinced that Geli 8 Anni Winter nee Schuler (b. he can deceive himselfinto believing that his obstinacy and theories about marriage can break our love and determination.6. Hitler’s thoughts very often turned to Geli.5. 1. I also understood now why he had watched over the activities of the beloved like a hawk. 1. He had a room converted for her there.
He did not return until four that afternoon. There they found Geli shot dead. 131 . he had to go into town. and at this point he converted to vegetarianism. After the war the US archives declassified invoices for extravagant purchases of clothing made for Geli. who was visiting her mother at Berchtesgaden. Frau Winter stated that the circumstances surrounding Geli’s suicide were as follows. Hitler was a completely changed man and his supporters feared that he might also take his own life. Until the outbreak of war he carried 9 According to Schaub’s statement in 1945. She asked Hitler for permission to go to Vienna for a vocal test which she had had planned for some time but he refused outright. Hitler asked Geli. when he informed her that he had to travel immediately to Nuremberg.9 His memory of Geli became a cult for Hitler. After Geli’s death. Geli was upset because she could have stayed with her mother at Berchtesgaden. Geli now went through Hitler’s possessions and found items of correspondence. Geli’s suicide hit Hitler hard. She told Frau Winter that she was intending to go to the cinema. When Frau Winter brought her breakfast next morning. Seeing the key in the lock on the other side of the door she feared the worst and asked her husband to break in. but promised to return for lunch. but instead stayed in her room. a sure reason why she was prepared to be submissive and allow Hitler to drive off all her other suitors. Thus they parted under a cloud.THE WOMEN AROUND HITLER dreamed of marrying her uncle. Her room at his Munich flat had to remain precisely in the condition it was at the moment of her death. Heinrich Hoffmann took a close interest in Hitler’s well-being and succeeded in the next few months in bringing Hitler out of his self-imposed isolation. for no other man was in a position to pamper her permanently in the manner to which she had become accustomed. there was no answer to her knock. After her arrival on the morning of 18 September 1931. to come to Munich. lying on a chaise-longue.
Hitler appears to have kept his love life platonic throughout. I find that the descendants of a genius mosdy have it very difficult in the world. . toilet items and whatever else had belonged to her remained in their place. then Maria Reiter. Moreover I do not want children of my own. .’ there was no doubt for me but that Geli had been this woman. the part where Geli’s room was located was left untouched. In the Staircase Room we asked Hitler once: ‘Why have you never married ?’ He replied: I would not have made a good father and I would consider it irresponsible to have founded a family if I had not been able to devote myself sufficiendy to the wife. All her clothes. Towards the end of the war Hider gave Schaub the job of destroying Geli’s personal effects. beginning with the blonde Stefanie in Linz. Ada Klein. and when I heard him say in the Staircase Room: ‘There was only one women I would have married . Beside the photos there was a bust of her. He even refused Geli’s mother the return of mementoes or letters. His custom of throwing a 132 . and in wartime took great pleasure in having parcels of coffee and food delivered to them. Apart from that they mostly turn out cretins.HE WAS MY CHIEF the key to the room on his person. When I knew all this and that Hider came between the couple whenever a love relationship threatened to take solid form. whom he worshipped from afar. His admiration for famous actresses and dancers was sincere. Sigrid von LafFert to the various female theatrical performers and artistes who were invited to be entertained in the Fuhrer-apartment at the Reich Chancellery in the first years after 1933. relishing the letters of gratitude they sent him for the gifts. and the room which Geli used to occupy at Haus Wachenfeld remained permanently locked. At a premiere and on their birthdays he would send valuable presents. When the structure was enlarged later into the Berghof. One expects them to have the same ability as their famous forebear and do not forgive them for being average.
but when he began to find less time for her while electioneering she made some sly suicide attempts. Unity Mitford and Eva Braun — yes.11 10 Two statements made after the war show unequivocally that Hitler was not the lover o f Eva Braun. the film actress Jenny Jugo.’ In 1945 Heinrich Hoffmann said: ‘From 1930 onwards Hitler often came to my studios and on such occasions took the opportunity to get to know Eva Braun and saw her often. There were never sexual intimacies between them. I repeat. Eva Braun’s calculations worked out: Hitler drew her increasingly into his life. In my opinion Hider’s relationship with Eva Braun was always platonic.THE WOMEN AROUND HITLER brilliant reception for the German art world every year had to be abandoned once war came.” Did he love her?’ Schaub: ‘H e was fond of her. 133 . Gretl Slezak. These were successful. even his relationshiop with Eva Braun was a fagade. This protected him against future suicide attempts and was also a shield against all his other ardent female admirers. In 1945 Julius Schaub was asked: ‘Did Hider love Eva Braun?’ Schaub: ‘He liked her. Hitler’s personal photographer Heinrich Hoffmann was convinced that Hitler had nothing with Eva Braun. Magda Goebbels. and Hitler exercised the same abstinence towards Gretl Slezak.’ 11 See Chapter 11. I remember for example the dancers the Hopfner sisters. her sister-in-law Elio Quandt. who was friendly with Hider in the 1920s. for Hitler as a politician could not afford a second suicide of a young woman in his close circle. Eva Braun confided to her hairdresser (statement by Klaus von Schirach) that Hider never had sexual intercourse with her. Leni Riefenstahl. the only woman he loved and would later have married was his niece Geli Raubal. wife of Bormann’s gynaecologist Dr Scholter. Ada Klein said the same to Nelly Scholter. contrary to assertions in the literature and periodicals.’ Q: ‘What is that supposed to mean? What did you mean when you said in Munich “He liked her.10 He went out with her.
As she told me. and stood in a visible position on a stool listening to him spea did many others. Volkjscher Kurier . from where Max Amann recruited her to the Volkjscher Beobachter. Munich. there were never any intimacies.8. Ada Klein worked for a small ethnic-racist newspaper. 12. On another occasion he invited her to Emil Maurice’s two rooms. Once she was alone with him in the old Haus Wachenfeld on the Obersalzberg where he prepared the coffee himself and discovered that Schaub had left the biscuit tin empty. from August 1927 worked as a secretary for Max Amann at Fritz Eher Verlag. but in this he was unsuccessful. The door to the second room was open. He exclaimed: Ah.Chapter 10 Ada Klein H i t l e r saw A d a K l e i n 1 for the first time at the refounding ceremony for the NSDAP at the Burgerbraukeller on 27 February 1925. 134 . but also: ‘You make me more light-headed than when 1 Adelheid Klein (b. Educated in Switzerland. He told her: ‘that he could not marry’. Shortly after their arrival Emil Maurice took his leave.1902 Weingarten). and Ada saw a bed in it. here you are!’ Subsequently they met frequently at Party occasions. Hitler noticed her and asked Emil Mauric chauffeur to find out about her. She was a very beautiful Geli-type girl. As she was leaving the Schelling-Strasse offices one day she bumped into Hitler. 1936 married D r Walter Schultze.
Hitler said: ‘Then Dr Schultze has found himself a good comrade!’ Dr Schultze was later head of the Department of Health at the Bavarian Interior Ministry. d.1. but it is easy to deceive oneself in such things. 1. 135 . SS-Gruppenfuhrer. While out walking with him in the Blumenau.1979 Krailing). in May 1945 as head o f the Department of Health at the Bavarian Interior Ministry he was interned. 2 Walter Schultze. He called her ‘Deli’ and wrote her a few short letters which she kept.2 I met Ada Klein in 1930 on a gymnastics course on Munich’s Carolinen-Platz which was frequented by many employees of the Braunes Haus and the Eher Verlag. After that we lost contact and it was not until the late 1970s that we met again.11. sired during a sexual relationship during the First World War with French girl Charlotte Lobjoies. (b. When one of her nieces (the two pretty Epps girls were revue dancers occasionally invited by Hitler to his flat on the Prinzregenten-Platz) told him in 1936 that Ada was going to marry Dr Walter Schultze. when he went ahead of me I think I saw a similarity to Hitler in the gait and posture.27. One day when she visited me in my apartment I told her of my meeting at Easter 1979 with Jean-Marie Loret who was hoping that I might recognise him as the illegitimate son of Hitler. As neither he nor I spoke the other’s language I was unable to make the identification for this and other reasons.1894 Hersbruck. and subsequently tried and convicted as a war criminal on two charges o f collaborating in the euthanasia programme.ADA KLEIN I add the strongest rum to my tea!’ and: ‘It was you who taught me how to kiss!’ Ada Klein’s friendship with Hitler lasted two years (1925—6).
Although a quarter-Jewish. 136 . in 1930 came to the Deutsche Staatsoper in Berlin. who had inherited the devastating humour of her father. Without his agreement. as a person of some Jewish racial heritage she would never have obtained years of successive contracts at the Deutsche Oper in Berlin in the 1930s.’ The contrary was the case! Hider maintained his friendship with the charming singer. Here I must contradict Dr Picker’s assertion on p. 9. Hider continued to receive her until the war’s end and often invited her to the Reich Chancellery.288 of Hitlers Tischgesprdche1 where he says that: ‘Hitler’s convictions forced him at Christmas 1932 to break off his especially warm friendship with the much-loved Berlin singer Gred Slezak. She exuded a magic so captivating that Hider was blind to her having a Jewish grandparent. even after he took power. Was trained by her father as a soprano. d. third expanded and fully revised edition.1.1953 Rottach-Egern). and he looked forward to every meeting with her. 1933— 1943 appeared at the Stadtisches Opernhaus in Berlin Charlottenburg. Hitler got to know his daughter at the Munich Gartner-Platz theatre where she played the leading role of the sweet Viennese maiden in Goldene Meisterin. G r e t l S l e z a k 1 w as t h e 1 Gretl Slezak (b. 30.Chapter 11 Gretl Sleza\ daughter of the renowned heroic tenor Leo Slezak who even when old remained an inspiration.1901 Breslau. 2 Seewald Verlag.8.
apart from the close staff. and since we could not remain forever at the fireplace I asked Hitler if he would like to see my apartment. In the so-called Music Room. used for film shows in the evenings at which. to bridge the time gap. He agreed immediately and arrived during the evening with a manservant who withdrew after handing me a bottle of Fachinger. The tea hour had already gone on far longer than scheduled. I had no suspicion that he was on the edge of his seat waiting for the off with Austria and as I see now he was doing what he could. child. Shortly before they were completed it occurred to me how practical it would be if we secretaries could also live there. the tea table before the fireplace was crowded. It always enraged me when I had to driye to my flat on the Savigny Platz not only to fetch my trunk but to pack it first. I would always have you 137 . Hitler invited Gretl Slezak and myself to tea at his flat in the Radziwill Palace. on the Sunday before the annexation of Austria to the Reich. In accordance with Hitler’s ruling ‘Nobody should know anything he does not need to know. i. trips out were always advised at very short notice.GRETL SLEZAK In March 1938. In 1936 Hitler had commissioned Speer to build two houses in the English country-house style on the park side of Hermann-Goring-Strasse. These were originally to have been occupied solely by members of the SS-Begleitkpmmando and their families. That Sunday nobody knew what Hitler had afoot for the coming week. the 55Begleit%ommando and the house personnel were also present.e. Hitler enjoyed hearing about the interminable scandals from the performers’ circles and delighted in the stories which Gred Slezak knew how to deliver with just the right amount of charming malice. suppress his impatience. and so one day after dictation I asked Hitler if it would not be possible for his three female secretaries also to have a flat each on the Hermann-Goring-Strasse. My apartment was located in the Reich Chancellery park. and if he does need to know then at the last possible moment’. which I had been promising to show him for some time. that would be good. He thought about this and said: ‘Yes.
To return to that tea night. Gred would not give up hope and thought she might at least have a closer relationship with Hider. What it said I have no idea but it would have done her courtship no good whatever. When these were ready for occupation. After taking power Hider would never have committed himself to anybody in the theatre because the risk would have been too great. gave me a photograph of herself in costume with a message in a large. He was always careful to maintain discretion with regard to his position. He had neither 138 . from her Gred.000 RM to furnish them and promised to pay a brief visit to see the final result. Hitler instructed Schaub to make me an allowance of 3. to my first Lady at Court. In 1932 when he is supposed to have painted Gred Slezak he was on the hunt for electoral support and in a single day might have spoken at three different locations. No effort was to be spared! Sitting next to him on the English sofa she tried to stroke his hand but he fended her off gently saying: ‘Gred. all of them would have used it to advance their careers. She was playing the lead role of Catherine the Great at the Deutsche Oper in Berlin and before her next performance. only architectural sketches.HE WAS MY CHIEF people with me!’ Speer was asked to call by with the architectural plans and Hitler told him to include three apartments for his secretaries. After leaving the Reich Chancellery. In the 1920s he produced no more watercolours.’ Just before New Year 1939 she gave me a letter to forward to Hitler at the Berghof. Now I would like to address the assertion that Hider painted Gred Slezak. you know that I cannot allow that!’ Although I had discreetly left the room a few times Hitler maintained his reserve and a few hours later his manservant retrieved him intact. convinced of her ultimate victory over him. Gred Slezak had driven quickly to her apartment on the Kurfurstendamm in order to dress for the evening. triumphant hand: ‘Tinchen (her nickname for me). She arrived with two large five-armed candelabras which she placed strategically in the hope that the candlelight would have a magical effect on Hitler when he arrived.
139 . and was sent to report on the newly formed Deutsche Arbeiter Partei of Anton Drexler. Margarete Slezak was a divorcee with a daughter. Hitler’s alleged letters to her are crude forgeries. In any case he always called her ‘Gretl’ and used the formal pronoun ‘Sie’ and not the familiar ‘D u’ when speaking to her.GRETL SLEZAK the time for. and in any case in the past had only turned out watercolours to survive. He never called her ‘Tschapperl’ .‘little idiot’ . From 1935 Margarete Slezak was my close friend. She shared my opinion that he had never painted flowers. Hitler knew all about it. To suggest otherwise is an unprincipled deception. In the 1920s she was a regular visitor to his flat in the Thierschstrasse and knew from these visits that Hitler had given up painting. nor interest in. only buildings and landscapes. He had not found that necessary from 1919 onwards when he was active in the Reichswehr. If Hitler had ever painted her I would certainly have found out about it. From then on his life was devoted to that Party and politics.an obvious fabrication. He was not so ignorant that he would have written to a divorced woman as ‘Fraulein Slezak’. painting. I knew Hitler’s erstwhile lady friend Ada Klein.
His name was always in the newspapers. She found him to be a very interesting man. where they sometimes ate ice-cream together. he had men to protect him and he was driven about in a large Mercedes by a chauffeur.Chapter 12 Eva Braun % H ew p e o p le k n e w a n y th in g about Eva Braun before the end of the 1 ^ Second World War. Hider met Eva Braun at Hoffmann’s business establishment in 1929. was a competent skier. she was employed upon completing her education as a salesgirl in Heinrich Hoffmann’s photography business.1Eva Braun told her friends however that JL 1 See Dr Otto Wagener. Eva Braun enjoyed sport. whom Hitler had often invited to the ice rink when Geli was alive. Her boss Heinrich Hoffmann forecast a great future for Hider. The daughter of a Munich teacher of commerce. Although outwardly soft. Six months after Geli Raubal’s death in September 1931. outstanding swimmer and a passionate dancer. I first knew her in the summer o f1933 on the Obersalzberg. she had great energy and will and to get her own way she could be very persuasive if necessary. H itler aus Nachster Ndhe. He had met her afterwards now and again without having any serious interest in her. Hider never danced. photographer Heinrich Hoffmann often took along his petite laboratory 140 . Hider’s friends finally succeeded in rousing him from his lethargy. Heinrich Hoffmann took him to a cinema one day and ‘purely by chance’ sat Hider next to Eva Braun. blonde and womanly. 'On Hitler’s election tours in 1932.
1899 Vienna. but in his opinion she ‘played no role’. Hoffmann was naturally very anxious to protect his commercial relationship with Hitler. Hitler’s half-sister assistant Eva Braun. 141 . and the first meeting between Hitler and Eva Braun after her suicide attempt was held at Hoffmann’s house in the Wasserburger Strasse. Pittsburgh). but the fear that a second suicide by a young woman of his close acquaintance must cast its shadow across his political career disturbed him. Daughter of opera singer Maria Petzl. Marion Schonmann2 who was there told me in the 1960s of the manoeuvre: Heinrich Hoffmann’s wife Erna had used make-up on Eva Braun upstairs so that she appeared to be ‘in distress’ for Hitler’s arrival. whom Hitler liked to have at table in the evening for diversion’. 19. Duquesne Univ. Frau Raubal. Univ. 17. 2 Marianne Schonmann nee Petzl (b. Initially Hitler rented her an apartment on the WidemayerStrasse. Hitler was left with no choice but to concern himself more for Eva Braun. H ider was present at the ceremony. 1935-44 often invited to the Obersalzberg where Marianne befriended Eva Braun. 3 Frau Winter.. but never stayed at Haus Wachenfeld because of Frau Raubal’s antagonism towards her. Hitler’s housekeeper in Munich. Hitler had no hint of her intentions and was therefore more than surprised when Heinrich Hoffmann informed him one day in November 1932 that Eva Braun had attempted suicide because of him. She was subsequently an occasional guest at Obersalzberg.EVA BRAUN Hitler was enamoured of her. said after the war that ‘despite her submissiveness. and she now spun her web.12. Hitler was of the opinion that he had given her no cause for her action. d. whom Hider knew and admired from his youth in Vienna. Success was guaranteed when Hitler saw Eva Braun ‘still pallid’ coming slowly downstairs.3 and henceforth he included her in his life and cared for her. Library. August 1937 married architect Fritz Schonmann. Hitler would have found some way to have rid himself o f her had the war not intervened’ (Musmanno Papers. and some years later made her a gift of a small house and garden at Wasserburger-Strasse 12.1981 Munich).3. With female cunning Eva had realised that fact after Geli’s suicide.
She was quite open about her feelings and once told Goring: ‘I envy you two things for my brother: the first is Frau Sonnemann4 and the other Robert. 6 The Seventh NSDAP Reichsparteitag covered the period 10-17 September 1935 at Nuremberg. Schroeder recounted a conversation with Eva Braun subsequently in which Eva had become aware of the campaign to uproot her. Hider intervened and when all the women. Frau Raubal was of the opinion that Eva Braun had drawn attention to herself. Frau Goring and we secretaries assembled.7 This backfired. 142 . Perhaps by now he had had enough of Geli’s mother and so 4 Emmy Goring nee Sonnemann. If obliged to speak to her she would address her only as ‘Fraulein’ without using her name. In the second year of the war. Emmy Goring invited all the Berghof ladies to tea at her country house. but never Frau Sonnemann. Frau Morell. and they were not invited to enjoy the hospitality at Haus Wachenfeld again for a considerable time. and this was the gist o f Frau Raubal’s complaint. and Frau Raubal was ordered to leave the Berg together with all the other women who had made adverse comments about Eva Braun in the affair. At the 1935 Nuremberg Rally.’ From the beginning Eva Braun had an aversion to Goring and particularly his wife Emmy. the first ‘suicide attempt’ by Eva Braun had had the desired effect. made no secret of her dislike for Eva Braun and would deliberately ignore her. and she was now integrated into Hitler’s circle. As previously mentioned. Hitler’s sister and Eva Braun and their friends sat on the tribune for guests of honour. we found that Eva Braun and her sister had stayed away. The real reason was to subject Eva Braun to close scrutiny. and said so to Hider in the hope that he would rid himself of her afterwards. 5 Robert was Goring’s capable manservant. 7 In her notes.’51 heard Goring reply: ‘If necessary I would give up Robert.HE WAS MY CHIEF and his housekeeper on the Berg. For this reason she had been making the fuss on the guests’ platform. Afterwards Eva Braun took Veronal in anticipation of the possible reaction but ‘was found in time’. Frau Brandt.6 the wives of ministers and Gauleiters.
Often one would hear Eva Braun complain: ‘I never know anything. employed a hairdresser and always gave the impression of being well-groomed. Her wardrobe was always well-stocked with 8 Jochen von Lang. Eva changed her clothing a couple of times daily. she moved into a room on the first floor of the annexe adjoining Hitler’s bedroom. When Haus Wachenfeld was revamped into the Berghof in the summer of 1936. Her friendships with women were very variable and generally short-lived. In 1936 Frau Raubal left Obersalzberg and. From now on Eva Braun’s position was apparendy assured. She was forced out when Bormann converted the Berghof. particularly of artistes. and only officially on his birthdays. 143 . Der Sekretar.’ No further commentary is necessary. Deutsche Verlags-Anstalt. She rarely saw her half-brother again. where she met and married Professor Hammitzsch of Dresden University. She looked after their needs herself but her gratitude was tangible if one accepted them wholeheartedly. when she was forced to wait at the Hotel Kaiserhof like an outsider for one of the adjutants to convey her to the Reich Chancellery. she took the cure at Bad Nauheim. Like all other females in Hider’s circle she was ignorant of politics. This was noticeable at Haus Wachenfeld even if she did not appear at official functions. In the presence of women Hitler avoided all political talk regarding ongoing or planned operations.’ In her appraisals. For a large house appropriate to a head of state. everything is kept secret from me. p.EVA BRAUN used the campaign against Eva Braun instigated by his half-sister as an excuse to remove Frau Raubal from the Berg. It is suggested elsewhere8that: ‘his half-sister Angela Raubal kept house for him for years in Munich and on the Obersalzberg. her heart weakened by all the excitement. 122. he or she had to go. 1977. she lacked objectivity: if a face did not fit well with her that person’s good qualities were irrelevant. she was no longer adequate. while her sisters and friends who were always around her even had guest rooms at their disposal.
All accounts which allege that Eva Braun was employed as a housekeeper and ran the Berghof outstandingly well have no foundation in fact.10 Waffen-SS liaison officer to Hider at FHQ .8.1.1.1941-end 1943 leader. house manager Kannenberg and his wife Freda would travel down from the Fiihrer-apartment in Berlin to do the necessary in their expert. Herr and Frau Dohring and later the Mittelstrassers were the competent housekeepers.1944 Waffen-SS liaison officer to Hider at FH Q . he asked Marion Schonmann how he could arrange to be invited for lunch.1945 Berlin). SS-Totenkopf-Reiterstandarte. which she often walked. 27. 30. Stasi and Negus. 144 . When Hermann Fegelein. Kampfbrigade Fegelein. 1.1936 SS-Sturmbannfuhrer. 21. SS Cavalry School. 1937 commander.1940 SS-Obersturmbannfuhrer and commander. executed by firing squad in Reich Chancellery gardens for desertion.4.6. 10. practising frequendy. She had two Scotch terriers.HE WAS MY CHIEF clothing ‘for materials testing’. 1935 founded SS Cavalry School at Munich. That was at the beginning of 1944. 10 Herrmann Fegelein (b. p. For special receptions.1906 Ansbach. Hitlers Tischgesprache.4.1945 arrested by RSD at his Hat in Berlin. 5. 28.1933 joined SS. was on duty for the first time at the Berghof.4.6. particularly the tragic songs of Mimi Thoma.1944 Generalleutnant der Waffen-SS. SSCavalry-Brigade and commander. d. at which Eva Braun never appeared.1944 married Eva Braun’s sister Margarete at Salzburg. She liked listening to gramophone records. Marion introduced Fegelein to Eva Braun and he obtained his lunch invitation through her.9After Frau Raubal’s departure. and kept up to date about the latest film releases.4. 25. 3. She also had a bullfinch which she taught a popular song by whisding to the bird through pursed lips.3. Frau Endres. when he arrived in Obersalzberg with Himmler. routine manner.1945 absented himself without leave from Reich Chancellery bunker. 30. reading periodicals and crime novels. She was keen on sport. 1. then I should let 9 See Picker. third edition.10.228. After Fegelein had left the Berghof she confided to Marion Schonmann that Fegelein had made a big impression on her and added: A few years ago the boss said that if I fell in love one day with another man. and so filled her time well.
to diplomat Hewel. minister Wagner).g. Today I can recall clearly the unforgettable scene. At eye level they would gaze at each other full of tenderness and loving: Eva was obviously strongly attracted to Fegelein. as one would say today. Eva Braun now matched her sister with Fegelein. sexy. After a dance Fegelein would lift Eva chest high. but I do not believe anything went on between them. but as Fegelein’s sister-in-law there was a basis for her presence in Hitler’s circle. She expressed the wish for music but had no gramophone.EVA BRAUN him know and he would release me. Eva said: ‘I would like this marriage to be as wonderful as if it were my own!’ And so it was. Now I am somebody. adjutant Darges. She was never permitted to appear in public. Hermann Fegelein was frequently amongst those who danced with Eva Braun. I lent her mine which had been in the Voss-Strasse bunker. After the failure of various efforts to marry off her younger sister Greta to men in Hitler’s wider circle (e. Eva expressed her gratitude thus: ‘I am so grateful to Fegelein for marrying my sister. Greta Braun was. and she could now be close to the man who had won her heart. While Hitler was attending his military conferences we used to play records.’ Now she said to Marion: ‘If I had known Fegelein ten years ago I would have asked the boss to let me go!’ But the problem was to be resolved in another way. Against Hitler’s wishes Eva came to the Reich Chancellery in February 1945 and moved into her apartment next to Hitler’s private rooms. Thus the marriage took place and was celebrated as a great occasion on the Obersalzberg and in the tea-house on the Kehlstein. He was a recognised heroic figure for women. I am convinced that her feelings for him went well beyond those feelings for a brother-in-law. drink champagne and quite often dance with off-duty officers. and Fegelein might have been thinking of the advantages of one day being Hitler’s brother-in-law. Upon her arrival in 145 . I am the sister-inlaw of Fegelein!’ Clearly she suffered from the anonymity to which she was condemned.
The fact that Fegelein.HE WAS MY CHIEF Berlin in February 1945 she said to me: ‘I have come because I owe the boss for everything wonderful in my life/ In my opinion she remained faithful to him although undoubtedly she and Fegelein had to struggle against the overwhelming feelings that attracted them mutually. after deserting his post at the Reich Chancellery in April 1945. A tragedy. for at this time and place they were made for each other. a red-haired woman was found with Fegelein. shot by firing squad on Hitler’s order. What thoughts must have assailed her when it became known that Fegelein had been found with another woman at his flat!11 Her decision to die alongside Hider was that much easier to take knowing that Fegelein was dead. The most amazing thing of all at this time was how normally things proceeded as the end of the Third Reich approached. 146 . rang Eva Braun there and urged her ‘to leave the Reich Chancellery and come to him* supports my presumption and observations. 11 Upon his arrest on 27 April 1945 at his flat at Bleibtreu-Strasse 10—11 by RSD officer Peter Hogl. She was allowed to escape on a pretext and her identity remains unknown.
In the 1920s Adolf Hitler and senior NSDAP men Hermann Esser and Christian Weber came often to the Obersalzberg because the hunted NSDAP fugitive Dietrich Eckart. She turned the Steinhaus into the first hotel on the Obersalzberg. had an all-weather alpine chalet built there. Herr Winter.* The Berlin piano manufacturer Bechstein built a house there. Rich people from the city arrived as a result.Chapter 13 Obersalzberg 1877 M a u r it ia ‘M o r it z ’ Mayer bought the equestrian establishment and Steinhaus estate together with all the summer pasture around the Kehlstein mountain. set up a sanatorium for children. buying up old farms or building their own mountain retreats. later called the Professor von Linde Weg. Under her proprietorship ‘Pension Moritz’ became a much-visited resort for guests and convalescents. to the Hochlenzer. was an old settlement on the salt road from Hallein to Augsburg which crossed the Obersalzberg. Hitler told us the story at tea one day. A Buxtehude businessman. It was through Christian Weber. (TN) 147 . He was fascinated by the scenery. One can read all about it I N * The Hochlenzer. had found shelter there. Professor Karl von Linde for example purchased the so-called Baumgarten estate and laid a road. Hider’s mentor. built in 1672. and Dr Seitz. that Hitler came to the Obersalzberg for the first time. a paediatrician. who found lodgings for Eckart at the Bruckner house.
259. pp. (TN) * * Obersalzberg overlooks Berchtesgaden from the northern foot o f the Hoher Goll. Dietrich Eckart introduced Hitler to many of the local inhabitants including Frau Bechstein. pp. In an obviously distressed state she told me that Hider had gone off on a car trip with the gentlemen of his staff and some ladies. At the time I was working with the Liaison Staff. A wooden balcony decorated with bright geraniums encircled the structure. The living room was typically Bavarian. she was apparendy glad to see me as it would help to take her mind off the matter. and in 1927 he transferred it to his own name before eventually purchasing the house outright from the executors of Frau Winter’s estate in 1934. The terrain o f about 1. who taught in Linz.000 hectares was 278 hectares farmland and 716 hectares woods and mountainside.202-5.HE WAS MY CHIEF in Heim’s Monologe im Fuhrerhauptquartier* since a stenographic note was kept. active and a person who maintained discipline. Herbig. and were overdue.265. In August 19331 was summoned by telephone to Obersalzberg** unexpectedly. although he did not seem to want this particularly. (TN) 148 . Frau Raubal ran the household for Hitler. Gready worried that some accident had befallen them. The mountain was owned by the NSDAP and was never the seat o f government. with whose help he rented Haus Wachenfeld from Frau Winter of Buxtehude for 100 RM. I arrived at Haus Wachenfeld in the afternoon to be welcomed by Frau Raubal. She was a widow six years older than her half-brother. Orbis edition 2000. Leo. She was a figure who inspired respect. * Table-talk o f 16 January 1942. She volunteered to show me the ground-floor rooms of the Bavarian shingle-roofed house. The tenancy was put into the name of his half-sister Angela Raubal at first. and a son. often hitting the table with her fist impulsively at mealtimes to make a point. Seider and Zeigert. She was capable. A green dresser with farming scenes. She controlled her staff with a rod of iron and also felt responsible for ensuring the well-being of her half-brother. She had had three children by her marriage to a taxation official: Friedl and Geli. Die Fiihrerhauptquartiere.
The balustrade had supporting columns to the roof. and only after the conversion work to the house and the departure of Frau Raubal in 1936 did they disappear. three guest rooms and a large dormitory for the 55Begleitkpmmando. During my stay I was able to confirm what a careful housekeeper and outstanding cook Frau Raubal was. She took me to the glass veranda annexed to the employee’s rooms. statuettes of a farmer with canary and a Moorish dancer. this latter mountain being the seat of legend. all presents from Hider’s female admirers. she told me.OBERSALZBERG a commode and rustic chairs. Frau Raubal had apparently not had the heart to throw out all this evidence of the love and affection which these handicrafts manifested. the place where Barbarossa is said to be entombed awaiting the day of his return. a grandfather clock and. which were something new for me. A real delicacy were the little apple pies she made. To the right of it was the Salzburg region. Opposite the house was the very impressive sight of the Watzmann (2. rather like King Arthur). Not very Bavarian on the other hand were the many cushions and rugs embroidered with the swastika and mountain blooms in all colours which lay everywhere in abundance. Meals were taken in the glass veranda. gloomy mountains to the south of the house. Later two of the guest rooms were converted into 149 . wooden annexe fronted by a wooden gallery decorated with a mass of red geraniums. low.715 metres) and Untersberg (today Ettenberg. elongated. Then she led me to the terrace and showed me the view over Berchtesgaden which stretched out below in the valley to the north. the Hohe Goll and the Steinernes Meer. living contrast to the brooding. on a corner table. It was built by Munich architect Neumayer together with the garage and terrace in April 1933. It formed an enchanting. This single-storey structure adjoining Haus Wachenfeld had five rooms: a simple office. Well-maintained paths led from the terrace to the lawn at the side of the house: there used to be a rock garden on the southern slope with a number of paths crisscrossing it. At the foot of the northern rock wall was a weathered.
O f the last. Finally some cars came up the mountain. On that occasion I remember Hitler’s photographer Heinrich Hoffmann with his wife Erna. awaiting the return of the overdue excursionists. dressed in Tyrolean costume. the small house filled with the voices of the arrivals and a short time later Hitler’s guests assembled in the veranda.HE WAS MY CHIEF a medical surgery and the surgery of Dr Blaschke. Hitler invited them both to stay for a few days on the 150 . setting the table for dinner in the glass veranda. Reich press chief Dr Otto Dietrich with his wife. At sunset that day Frau Raubal and I stood on the terrace overlooking the road leading upwards. I would like to say something. In the summer of 1933 all guests booked into the nearby pensions on the Obersalzberg. and encouraged her to visit whenever she was in Bavaria. After their release a meeting took place at which Hitler was present. Hitler and Frau Raubal occupied the table ends while the guests sat where they fancied. I could hear one of the maids. Hitler’s dentist. Eva Braun and Anni Rehborn. A telephone switchboard was located on the ground floor. She took him up on this offer frequently. When the Berliner Illustrierte published her photograph on the title page —it was seen by Hitler’s followers sharing his imprisonment at Landsberg . ‘Rehlein’. Hitler’s long term chauffeur SS-Staffelfuhrer Julius Schreck and female friend.Hitler’s chauffeur Emil Maurice was inspired to send Anni Rehborn his congratulations. and at Christmas 1925 he sent her a copy of Mein Kam pf bound in red leather with the inscription ‘To Fraulein Anni Rehborn in sincere admiration’. In 1923 and 1924 she won the German swimming championships in the hundredmetres crawl and backstroke. At the end of the elongated annexe was the socalled ‘adjutants’ shack’. A narrow wooden stairway on the outside at the front led up to two small rooms: a bedroom with bath and an office for the duty adjutant. Julius Schaub. In July 1933 while touring Germany in her small red DIXI car with her fiance Dr Karl Brandt.
OBERSALZBERG Berg. but now he saw the necessity. How lucky he was to have had Dr Brandt along as a passenger. did everything necessary to make the casualties comfortable and carried out the operation himself at Traunstein hospital. It was therefore not surprising that he should ask the pleasant young Brandt if he would like to join his staff as doctor (Begleitarzt) and he agreed. While Sophie Stork escaped with a broken arm. and came up to Haus Wachenfeld for lunch and dinner. was so impressed by the skill of the young doctor that he exclaimed: ‘If ever I have to be operated on. Calmly and carefully he took the initiative. where they would sit in 151 . sustaining a skull fracture and losing an eye. Both Hitler and Goring were guests at the wedding. then only by Dr Brandt!’ Until then Hider had never had a medical aide on his various trips. He matured to a greatness in which he overshadowed the death sentence which awaited him at the end of the road. where they were booked into one of the pensions as his guests. In the true sense of the term he embraced the higher life and let it embrace him too. At this time Hider and his guests used to go on short rambles. Bruckner was seriously hurt. The ability of Dr Brandt was proverbial. as was his joviality: a doctor with the soul of a Paracelsus: to the last his life was devoted to his calling. Goring. Bruckner had fallen asleep at the wheel and collided with a stack of wood. One afternoon a telephone message brought the news that chief adjutant Wilhelm Bruckner and his friend Sophie Stork had been badly injured in a road accident at Reit im Winkel and had been taken to the hospital at Traunstein. A favourite destination was the Hochlenzer. Brandt was the Fiihrer’s ‘emergencies-only doctor’ but his role was actually only as a surgeon while Hitler was travelling: otherwise he worked at the Surgical University Clinic in Berlin’s Ziegel-Strasse where Dr Werner Haase and Dr von Hasselbach also worked as surgeons and occasionally deputised for Brandt on journeys and when Hitler was at the Berg. A short while later Brandt married Anni Rehborn. who was also a passenger.
It was a rare delicacy. At the stroke of midnight Hitler would touch glasses with his guest and sip. The meals were festive. In the 1930s Hitler would always spend Christmas on the Berg although after Geli’s suicide in 1931 Christmas was a difficult period for him and awkward for his guests. In later years the walks were dropped. 152 . He would allow a tree to be erected in a corner of the Great Hall but no carols were sung. which glittered in the distance. At Hochlenzer a very refreshing curds and whey was scooped up and served in brown earthenware bowls. They were glorious little treks. and after lunch he would venture no further than the small tea-house on the Mooslahner Kopf. He would then lead his guests to the terrace to watch the fireworks display at Berchtesgaden. Hider would wear a bright blue corduroy jacket. The milk was never moved until it curdled to prevent bubbles forming in the curd. Afterwards he would autograph the table-cards of all his guests and a group photo would be taken before the fireplace. Other walks went to Scharitzkehl and the Vorderbrand. though he always pulled a face as he did so for he ‘could not understand how a person could take pleasure in drinking vinegar water’. and everybody was served sparkling wine.HE WAS MY CHIEF front of the small house on wooden benches in the sun and enjoy the glorious view to Konigssee. New Year on the other hand was celebrated in the traditional manner.
At his wish the small old house was left untouched by the extension work creating the Berghof which began in March 1936 after Hitler conferred with architect Degano from Gmund am Tegernsee on the plans. Beyond the Roman arch. widow of Professor Paul Ludwig Troost. Its interior furnishings carried the hallmark of Professor Gerhardine (‘Gerdy’) Troost. hung with heavy bordeaux-red velvet curtains. or rather the extension.Chapter 14 The Berghof e f o r e H it l e r b e g a n w it h the conversion. A breach was made in the wall of the former staff room on the first floor allowing a Roman arch and corridor to be built for access to the Great Hall of the new structure. of Haus Wachenfeld. (TN) 153 .* the steep road from Berchtesgaden to the Obersalzberg. rather larger. Amongst other things it was Hitler’s idea to install heating below the road. were broad wooden steps leading into the Great Hall. the smaller being kept bright blue and white. which was very dangerous in winter due to ice. When Hitler equipped his Munich apartment B * According to Hider in Heim. We had two secretaries’ rooms in the old house. the apartment of the house manager and the staff rooms. the house was built in 1917. Monologe. On this new floor were also located the private rooms of Hitler and Eva Braun. was painted red and had a balcony. whom Hitler valued highly. mine. was widened.
often used to resolve arguments. it was always cool especially when the house was fog-bound or when it rained. Although the seating below the underpart of the bookcase did not project much and was very uncomfortable. temperamental woman. Another well-loved spot was the bookcase to the right of the window which contained Meyer’s Lexicon. Troost showed him his plans for the reconstruction of the burned-down Munich Glass Palace which the City Jury had rejected. The former staff room at Haus Wachenfeld became the living room. Frau Troost and Heinrich Hoffmann exhibited a display of sculpture and photographs in the Haus der Deutschen Kunst. was a very gifted artist and had painted various scenes on the stove tiles. and so the female guests particularly would settle on the sofa near the warm stove. and his marshal’s baton. Hitler awarded him the honorary title of ‘Professor’ which passed to his wife after Troost’s death in April 1934. She was a very intelligent. most people were keen to 154 . and which impressed him by its simplicity of style. Once the ban on smoking was lifted for the early and late hours it became a great favourite. Hitler was enthusiastic about the design and included it later in the construction of the Haus der Deutschen Kunst. Hitler. Bruckner’s friend.HE WAS MY CHIEF he had been referred by Frau Bruckmann to the Vereinigte Wer^stdtten where he saw furniture which Professor Troost had designed. painfully exact on all matters. particularly the Great Hall. Should the guests have a difference of opinion on details such as the length of a river or the population of a town. Troost also built the NSDAP Braunes Haus and the Fiihrer-building in Munich. In the interior of the house. She designed tapestries and interior furnishings on commission for Hitler. Sophie Stork. The green stove with its much-admired tiles made it the most comfortable room at the Berghof. would then consult the two different editions of the Lexicon just to be on the safe side. as well as the document appointing Goring as Reichsmarschall. Frau Troost was an interior designer and for a while continued her husband’s work. the Lexicon would always be called upon.
After the conversion. alpine roses and lady’s slipper. This was an assembly point for guests waiting for the appearance of Hitler before mealtimes in fine weather (in inclement weather the living room was used instead). The second pair was always Martin Bormann and Eva Braun. After Hitler and Eva Braun retired upstairs the guests would gather for a glass of sparkling wine before going to bed. This was a chance to relax after the ‘official fireplace session’ in which not everybody felt free and unrestricted. The long dining table had twenty-four red leather armchairs. passing through the former veranda now renamed the ‘Winter Garden’. including the secretaries. the door next to the bookcase led to the terrace.THE BERGHOF secure a place there because it adjoined the sofa under the window favoured by Hitler. . would announce: ‘Mein Fiihrer. gentian. In fine weather breakfast was taken on the terrace. although most took breakfast in their rooms. Here on the wooden sofa covered with cushions one could sit comfortably and rest one’s arms on the table. ’ Hider would then offer this lady his arm and lead her forward. thin-shell porcelain with hand-painted alpine flowers. The train of guests then moved through the sizeable vestibule. e. its beautifully curved ceiling supported by imposing columns. the round table in the ante-room would be used 155 . past the broad stairway leading to the upper rooms and into the dining room finished in finely grained pine. . If the big table in the dining room lacked places for all lunch or dinner guests. it is arranged for you to escort Frau X .g. Crockery was white. dressed in white dinner jacket and black trousers. The window front of the elongated dining room ended in a semi-circular balcony where the early risers breakfasted in inclement weather at a round table. Once all were present the manservant. its two wing doors flanked by two servants. Hitler would always greet the women by kissing the hand of each. Eva Braun would usually come down last. The volume of conversation would often build up. particularly when Schaub and Hoffmann went for each other. The other guests chose a partner freely.
a present from Winifred Wagner to Hider. while at his left Eva Braun and Martin Bormann had a permanent place together. e. Hider’s household functioned like a well-run hotel. meat. When I think of the almond bushes. vegetables. At the Berghof Hitler always sat at the centre of the table opposite the window overlooking the Untersberg mountain. They bore the sovereignty symbol. together with hand-painted crockery.and blackcurrant juice. That at least was what was whispered. When Hider recognised the medicinal qualities of hops he would indulge himselflater in a beer brewed for him specially. rare orchids and gerbera amongst other expensive blooms which transformed the rooms into a literal paradise of flowers then I definitely believe that these decorations far exceeded the costs of the menu on such occasions. was displayed. red. eggs. The porcelain and silver cutlery were made to Hitler’s design. the eagle with spread wings with right and left the initials A’ and ‘H ’ in the old script. salad and dessert.HE WAS MY CHIEF additionally. The farm provided milk.g. the secretaries also had their turn. There was also a built-in glass showcase in which very beautiful porcelain. the design on the porcelain being in gold. He laid stress on having a beautiful floral decoration at table. grape and apple juice. He would have a different female partner at his right hand for each mealtime. carrying a bowl of heaped meatballs. honey from hives in the wooded regions of Obersalzberg and the Kehlstein. 156 . Excellent floral decorations were set for state dinners. The fare was simple and traditional: as a rule soup. From Martin Bormann’s market garden on the Berg fresh vegetables and salads were delivered daily. His favourite meals at the beginning of the 1930s were white beans. It was essential that the best blooms should be supplied from the most exclusive florists in Berlin and Munich. primarily to seat the adjutants. some showing Frau Endres. Nearby was a sideboard with hand-painted tiles depicting scenes from Berghof life. The special invitees were placed direcdy opposite Hider. who ran the household for a short while after the departure of Frau Raubal. the long-stemmed roses.
He was sincerely opposed to meat eating. all plant-eaters. ‘This picture 157 . Once I discussed this with Ada Klein. which had great strength and endurance.’ After Geli’s death he actually did convert and never tired of holding forth from time to time during meals on the brutal methods of slaughter. The waiter brought a giant portion. Hitler ordered kid liver. after a bit of effort. finish up panting with their tongues hanging out/ In his opinion meat was dead. how the broadcast seed fell to earth. and according to Julius Schaub became vegetarian after the death of Geli Raubal.THE BERGHOF peas and lentils. He was absolutely convinced that meat eating was harmful. bulls and elephants. Afterwards they ate at the Cafe Viktoria in the MaximilianStrasse opposite the Thierschstrasse (now the Restaurant Roma). ‘which are confirmed meat eaters and. I believe I shall become vegetarian one day. The farmer sweeping the seed fan-wise from his hand in that great gesture with his arm as he bestrode his fields. from two!’ At that Hitler remarked to Ada: ‘The human is an evil animal of prey. this confirmed the correctness of his opinion. During the war when a dietician-cook was employed he followed the Bircher-Benner diet. sprouted and grew into a green sea of waving stems turning slowly golden yellow in the sun. ‘Contrast them with dogs/ he would say. Hitler asked: ‘Is that the liver from one kid?’ The waiter replied: ‘No. putrefied matter. and in addition he disapproved of the cruel manner in which animals were slaughtered in the abattoirs. Two small innocent animals were deprived of life to provide a glutton with a gourmet dish. vegetable dishes and salads. As an example he cited horses. When I mentioned Hitler’s remarks about meat eaters she recalled an incident at Easter 1926 when she visited a matinee of the Zigeunerbaron in the Gartner-Platz theatre. When Eva Braun then gave him a pleading look to not go on about it so at the meal table because it put many guests off their food listening to the discourse. On the other hand he would go into almost poetic rapture whenever he described how his own vegetarian meal had been grown.
Next day wearing a chef’s white outfit she caused uproar in the kitchens. far too long and several sizes too big for him. a native of Vienna very often the guest of Hider and Eva Braun at the Berghof. These included bread rolls with meatballs and sorrel sauce. In the war years when her influence on Hitler was more certain she would even go so far as to cast looks of disapproval in his direction or ask in a loud voice what the time was. ‘should tempt Man back to Nature and her produce. \fears later he still relished retelling the story of Frau Schonmann’s meatballs. Later when her self-confidence grew she would talk if she felt so inclined. Marion Schonmann. he would always kiss the hand of Eva Braun first. Hitler would wear a ghastly khaki windcheater. he believed.’ He would always round off by saying that he did not intend to convert anybody to vegetarianism. This hat was the curse of the photographers. once joked that she would make some for him. Hider would then quickly abandon his monologue and rise from the table. Until the war. set the staff in high dudgeon and created an awful mess.HE WAS MY CHIEF alone’. who enjoyed getting the better of his female compatriot. Hitler. at least in the earlier years. He would often recall the meals he enjoyed most as a child. and a nondescript hat with a wide brim to protect his sensitive eyes. She would allow her impatience to show if at the end of the meal Hitler embarked on one of his favourite topics instead of rising. for it only allowed 158 . and suggested she should use her recipe to defend the turreted casde she owned near Melk on the Danube. which is given to mankind in wasteful fullness. for if he did in the end nobody would accept his invitations to dine any more. When the diners rose. and then that of his female partner at table. did not miss this opportunity of berating her much-vaunted skill in cooking. the result of which was meatballs as hard as iron. which his mother used to make. During the meal Eva Braun took litde part in the conversation. on his walks on the Obersalzberg which led to the ‘small tea-house’ on the Mooslahner Kopf.
As a source of warmth it was superfluous. It would take a comfortable half hour to reach the tea-house. Once everybody had looked their fill —far below the river Ache curled through the valley —Hitler would lead the way to the tea house. It was at 2.000 metres. very conscious of appearances. tower-like pavilion. the lead of Blondi his German Shepherd in the left. Speer is mistaken when he says that Hitler had no feeling for the beauty of the landscape. the fireplace was on the north side. would often criticise his clothes. chintz-covered armchairs at a round table. I never saw the grate lit. On a rocky promontory equipped with a guard rail he would then stand enjoying the view over Berchtesgaden and Salzburg. He would always go in company with the newest arrival amongst the guests. both hands resting on the walking stick. the tea-house on the Kehlstein was rarely visited. Furnishings were deep. There was a cloakroom in the porch and then one entered a room of bright marble with a large fireplace. While the visits to the small tea-house on the Mooslahner Kopf formed part of the daily ritual.THE BERGHOF them to get a shot of the lower half of his face. above it a gold framed mirror reflected the crystal crown lights in the ceiling and the beeswax candles in wall holders. built by Professor Fick in 1937 and resembling a low. Hitler would always wait at this promontory for his guests to catch up and then all would enjoy the view together. Eva Braun. narrow windows in the south face of the tea-house allowed a good view of the mountains. for central heating was installed below the red marble floor tiles. He kept to well-maintained bridle paths at the sides of the farm meadows. and he saw it as a criticism of his taste would he let his annoyance show. and Hitler felt unwell in the 159 . When Eva once spoke disapprovingly of his hunched shoulders when walking he brushed this aside with: ‘Those are the great worries of state which weigh me down!’ On these walks in wartime he preferred a black cloak. Tall. a walking stick in his right hand. Only if she repeated her criticism too often. but he ignored her.
Herbig. While the guests to the small tea-house drank mosdy tea or coffee. often skirting the edge of the precipice. but Hider always had apple pie. A road six and a half kilometres in length climbed 1.710 metres to a parking place at a gallery entrance to a lift. I have lost seven kilos in the last fourteen days!’ Battling his tendency to corpulence was spurred less by vanity than his awareness of people’s disapproval of well-fed orators. just as the farm was also developed on his initiative. (TN) 160 . low in calories. both of which kept him on the path of moderation. I am back to my old weight. Hider and Eva Braun preferred cocoa. he would reject anything sugary and eat very little. This lift rose 124 metres direcdy into the Kehlstein tea-house. for he found both Goring and Dr Morell well proportioned. I must lose it!’ His iron will would bring about the hoped-for result. To be a couple of kilos overweight was a serious political matter for Hitler and if it suddenly became difficult to button his jacket at the midriff and the scales confirmed an increase in weight. The selection o f cakes and pastries was very tempting.261. with thick slices of baked apple. Further on they would be impressed by the tunnel drilled into the mountain with its imposing metal lift and then the overwhelming sight over the majestic mountain world of Berchtesgaden. Goring’s corpulence on the other hand did not worry him.HE WAS MY CHIEF thin air at that altitude. its pastry breath-thin. and most of all his fear of being ridiculed. Die Fuhrerhauptquartiere. Later cognac and liqueurs were offered. Seidler and Zeigert. * The Kehlstein tea-house was a gift to Hitler from the NSDAP for his fiftieth birthday. I am putting on fat. This little house on a mountain top was like a fairytale with which he enjoyed surprising foreign heads of state. He would always proclaim a diet by declaring: ‘I have to eat less. and then he would announce: ‘So. especially if a Party rally was in the offing. p. The construction work on the Kehlstein was Martin Bormann’s masterpiece.* Hitler would often proudly relate the fascination of his visitors for the road which led to the Kehlstein.
Goebbels responded: ‘Then you should bathe much more frequendy. The spiciest stories he tolerated were the ‘G raf Bobby’ kind. and people who could tell them were very welcome. Dr Dietrich had stated that his best ideas came to him in the bath. I remember a conversation between Dr Goebbels and Dr Dietrich. or be seen in bathing trunks. a nobleman had been invited to a dancer’s flat where they had taken tea and afterwards taken a bath together. In the tea-house Hitler loved to hear amusing stories. Then he would want to know about it at once: ‘What’s new there?’ Awareness of this curiosity on his part was often used to skilful effect by clever guests. 161 . or hold an illustrated magazine in the hand and point to a particular section. although as soon as conversation died away he would waken immediately. The Schirachs liked to bring along American magazines. In this way certain matters could be brought to his attention which were otherwise delicate to broach. New arrivals at the Berghof were very welcome at the tea house.THE BERGHOF One saw that the same fear of ridicule was the reason for his decision not to wear leather shorts. where conversations gradually degenerated into monotonous repetitions for lack of fresh blood. Now the nobleman had no peace wondering whether there had been something more on offer from the lady. or perhaps discuss a document in an undertone. Often those present would score points off each other. To his mind such articles of apparel were inappropriate for heads of state. Hider also showed great interest should two people get their heads together at the big round table in the tea-house. the so-called ‘shorts regalia’ of Bavaria. Herr Doktor Dietrich!’ Sometimes in these sessions Hider would laugh till he cried. Hider would listen to stories like these with a contented smile. Talk would become a murmur if Hitler fell asleep in an armchair. For example. It would have been unthinkable to tell obscene stories or a dirty joke in his presence though —the bold comedian would receive an ‘if looks could kill’ look and be wise to excuse himself. the Reich press secretary.
The procedure for dinner was similar to that at midday. As soon as Hider entered. While in the tea-house. and which lady Hitler was to accompany at table. Hitler made fun of both but found the latter particularly objectionable. Eva Braun would get a manservant to find out what new films had arrived from the Propaganda Ministry in Berlin. in another two women boxed while standing in a sea of herrings. after our return (usually by car. Hitler’s talks always had priority. In 1926 when Ada Klein was walking in Munich with a female friend they chanced to meet Hider. and it was not an infrequent occurrence that dinner would begin very late. A hanging lamp spread warmth and helped create a pleasant atmosphere. who never economised on the lipstick. If Hider did not require the Great Hall for a conference. one contained illustrations of American women working in the armaments industry. When a lady 162 . The mood at dinner was freer and the conversation less forced. Hitler’s vehicle would have an adjutant. the midday ritual would be re-enacted: the manservant would appear and announce that dinner was served. Guests sat near the warm stove or on the sofas with their many cushions which surrounded the great rectangular table. not again!’ The effect of this fable appeared to give Hider a lot of amusement. Everybody would be waiting for Hitler who might be talking with a conversation partner either in his room on the first floor or in the Great Hall. Eva Braun’s younger sister. which was why he repeated it so often. The ladies would have dressed a litde less formally and applied make up to enhance their appeal. often motivated Hider into recounting the children’s fable about how lipstick was manufactured in the Paris sewers. who joined them.HE WAS MY CHIEF Once. Eva Braun would hold her nose and plead in feigned despair: ‘Oh please. the manservant and Blondi besides himself as passengers) she would arrange a film show before the guests retired to dress for dinner.
some chairs near the great window. then a piano and some 1 Schroeder noted that: ‘the response would usually be muted. During kissing they eat all that stuff on women’s lips!’ One day he selected a very beautiful bloom from a table vase and tossed it rather insolently to a lady. for the Great Hall was only separated from the living room by a velvet curtain. After the meal. a grandfather clock. This was rare. opened it. Conversation had to be carried on in low tones. The guests would descend five steps from the living room into the Great Hall. however. brooding silence. There was little other furniture there. On another occasion upon seeing a woman wearing a flower he offered her another which he thought suited her better. Two large cabinets. in an oppressive. The floor was laid with a strawberry-coloured pile carpet. took her hand. In the earlier years Hitler took pleasure in such gallantry. as mentioned. if there was a meeting in the Great Hall a film would be shown in the bowling alley provided there was no bowling. of which Hitler was particularly fond. for the sessions round the fireplace tended to go on and on. and ended. Hitler exclaimed: ‘Now I know why so many men have stomach complaints. In the evenings one would remain seated at table a litde longer.’ 163 . Ada Klein recalled that in the so-called Eckart Room at the Braunes Haus at Easter 1933 he withdrew a small yellow chick from the table decoration. Three marble steps led to the armchairs around the fireplace. if Hitler was not in a mood for conversation. It had a high ceiling and a floor area of almost 200 square metres. this would be drawn aside by a waiter and Hider would then ask: ‘Shouldn’t we sit at the fireside a litde?’1That was always the prelude to an evening spent there. his expectation being that she would put the flower in her hair or jacket. a large conference table.THE BERGHOF wearing heavy make-up passed in an open car. placed the chick very tenderly inside and closed the hand again. a globe. for the noise from the alley could be very distracting in the Great Hall and generally we would retire to the living room and wait for Hitler’s conference to finish. When Hitler was ready.
Hitler. Amongst the seating about the marble fireplace. the wife of a cobbler).2 The mammoth rectangular table standing in front of the window had a top of Untersberg marble and proved very useful at conferences for spreading out large maps on its surface. was a black leather sofa. red carnations in the same shade of deep red always stood on a commode nearby. It could be sunk down to show the majestic panorama of the Untersberg mountain as if in a frame. I built a house around a window here. but was extremely uncomfortable. a gift from Mussolini. It was of gigantic proportions. Certificates of citizenship and old weapons were displayed in it. At the beginning of the fireplace session one would have to sit bolt upright on the edge of the sofa. which had a dark brown ceiling. Very often Nana by Anselm Feuerbach (Feuerbach’s long-term lover from Rome. On the long wall of the Hall was a wonderful likeness of a woman dressed in red by Bordone.’ 164 . was undoubtedly the magnificent window. hung near the fireplace. who was very proud of it. and in relation to the size of the Hall it looked good.HE WAS MY CHIEF small commodes. The square footage available for sitting on was so enormous that it was not possible to sit and lean against the back rest. The most impressive thing in the Great Hall. a particular favourite of Hider. The sets consisting of upholstered chairs each with a small table and suitable for small groups of guests were much more acceptable. but as the evening wore on the ladies would find it more comfortable to lean against the sofa back with their legs tucked under them. 2 This large window was subdivided into ninety individual windows. once remarked to his adjutant Wiedemann: ‘Really. Magnificent Gobelin tapestries depicting hunting scenes covered apertures in the walls necessary for the film shows. One of the large cabinets had handles carved in the shape of human heads. The large old masters in the Hall were changed regularly. nine metres wide. In the other were old artefacts in tin behind a glass front.
In first place for him was Tristan and Isolde. Hitler considered Wagner to be ‘the man who re-awoke German culture from the spirit of music’. Hitler’s place was on the right side of it between two ladies (Eva Braun always at his right). Hugo Wolf. and the last act from Aida. Beethoven. He usually started the conversation or would intervene once a particular topic caught his interest. so to speak. The Deutsche Arbeitsfronty the official organisation for German workers. If the argument became too loud. Brahms. The music cabinet was controlled by Martin Bormann and was located at the side of the window. Hider also enjoyed light classical music such as The Merry Widow. From the long repertoire he had drawn up the greatest favourites were the symphonies by Bruckner and Beethoven. Die Fledermaus and Zigeunerbaron. the songs of Richard Strauss. He had seen some of Wagner’s operas very frequently and nothing in the world would induce him to miss the annual Bayreuth Festival (not even the Spanish Civil War in 1936). He would say when it should be lit. The frequent confrontations between Heinrich Hoffmann and Julius Schaub seemed to be provoked by music. Hitler was very partial to Richard Wagner’s works of course. he would often burst the tension with: ‘Should we listen to some music for a while?’ and all would agree with enthusiasm. Schubert and Schumann. a national pilgrimage. A number of the male guests preferred to retire to the lounge on evenings when music was to the forefront. Wagner’s musical language was to Hitler’s ears ‘like a divine manifestation’. and was planning to make visits to the Festival available to all sections of German society. a work of which he once said that he would like to listen to it in the hour of his death. If he did not feel like talking. arranged trips to Bayreuth for workers and employees to develop enthusiasm for Wagner’s works throughout all strata of society. and there were evenings which palled into awkward silences.THE BERGHOF The fire was not lit every evening. Hitler would send a manservant to the lounge with 165 . He sponsored Bayreuth financially.
3 At New "fear 1938 Gretl Slezak gave me a letter to hand to Hitler privately without anybody seeing. This would also happen if she thought that Hitler was paying too much attention to another woman.HE WAS MY CHIEF the request either that they should reduce the volume or return to the fireplace. added to which my silverfox fur cape must have looked magnificent. Bruckner was behind me snoring. supported by a small tipsiness which I had got from the dinner. As he was about to leave the Hall I detained him. It was dreadful!’ Hitler was very good at telling anecdotes like these and everybody enjoyed listening to them. for after I had handed him the letter I broke into hymns of praise about Gretl Slezak. he took my arm and strolled up and down with me in the Great Hall. If conversations were mentioned of which she disapproved this would be immediately evident and then even Hitler would notice. I had to wake Schaub up to tell him to give Hoffmann a shake. which must have seemed close to an attempt at matchmaking. mein FiihrerV 3 In her stenographic notes. Once all the guests had gone below to the bowling alley in the basement for drinks. ‘Whenever I visit the opera I have to take care that my officers do not snore. Schroeder stated: ‘If any woman was present in whom Eva feared a competitor. These occurrences would often remind Hitler of awkward situations which tended to develop at musical presentations when his escort did not like listening to music. My evening dress of roe deerbrown fluffy material with a small train. lent me a large slice of self-confidence and courage. He would stroke her hand resting on the arm of her chair. even Eva Braun. then she either retired very soon to her room or became so unpleasant that Hitler would notice and persuade her to withdraw “because she was tired”/ 166 . Convinced that he must share my opinion. whisper a few words and then she would disappear upstairs. Heinrich Hoffmann nearly fell over the ledge out of the box. One day during Tristan and Isolde. I finished with: ‘Eva is nothing for you.
we are all waiting for you!’ Hitler did not forget this episode. a plausible explanation for the flight of his deputy Rudolf Hess to Britain eluded him. for he made no move to leave the Hall.’ Hans Baur. gave me a scowl and said in hurt tones to Hider: ‘Where have you been.THE BERGHOF Instead of annoyance at this impertinent remark. Martin Bormann told me at the tim e. It would be a catastrophe for humanity.. it seemed. I had never known a dictation cause him so much trouble as this one. Hitler looked at me in amusement and replied: ‘But she is enough for me!’ Enough? Where was ‘the great love’ of which so many writers have been in the know since 1945? Clearly.. Despite innumerable attempts. In 1926 he had told his closest colleagues: ‘It is not my wish that a pearl should fall from the crown of the British Empire. for a few weeks later he brought it up and said to me with a smile.4 Hitler was a great admirer of British colonialism. He tried out all the possible motives he could think of and tried to encapsulate them in words. he must know that by doing that he has stabbed me in the back!”’ 167 . We had been alone together for rather too long.’ In the prewar years when German public opinion was 4 On the question whether Hess flew to Britain with Hitler’s knowledge or on his own initiative: one o f Martin Bormann’s secretaries wrote in a letter to Schroeder: ‘I am o f the opinion that Adolf Hitler knew nothing of the flight. It was the last New Year’s celebration at which so many guests would be present. Martin Bormann was always straight! It is unlikely that Hitler would have been so stupid as to send Hess to negotiate with a man neither knew and who was a friend of Churchill. said: ‘I overheard a conversation in the Reich Chancellery garden between Hider and Goring: Hider did not realise I was nearby when he screamed at Goring: “He has simply gone mad. Hitler’s personal pilot. ‘That night you had a certain something’. for Eva Braun appeared suddenly. Another unforgettable experience in the Great Hall was Hitler’s dictation of 11 May 1941. but nothing seemed to fit properly. That night the New \ear’s Eve photo was taken in the Great Hall before the fireplace. my attempt at matchmaking that New ^fear’s Eve amused Hitler no end. Only when he viewed the flight as the act of a madman did he seem satisfied.
he said to Hess in my presence: All my work is falling apart. One does not win independence with spinning wheels.HE WAS MY CHIEF very favourable towards the Indian independence movement.’ From several of his statements it was possible to conclude that he thought of an alliance with Britain as the most ideal solution to the problems of world politics. Deutsche Verlags-Anstalt. In the 1920s Hider had begun writing a book about foreign policy. and that Hess. because of his intimate knowledge of Hitler’s thinking. The duchess wore a simple dark blue woollen frock of excellent cut. visits and conversations. Weinberg.6 In the afternoon from the office window I saw Hider with the couple on the terrace apparently pointing out to them the various mountains by name. Stuttgart 1961. He considered the Royal Navy and the German Army in combination to be a power factor sufficiendy strong to give world politics a new foundation. Undoubtedly she made a lasting impression on Hider. Hitler was very impressed by the visit of the Duke and Duchess of Windsor. for in the evening he said: ‘She would definitely have made a good queen’. She looked chic and impressive with her hair centre-parted and styled in a bun. but with guns. undertook his flight to Britain. That evening at the fireside he also told us of the visit a few days before by the Indian prince and Muslim leader the Aga Khan. shortly after the British declaration of war. with a commentary by Gerhard L. I have written my book for nothing. particularly since he could have relied upon the sympathy of the working class.5 In 1939. 168 . one of 5 Hitlers Zweites Buck. The Great Hall was often the venue for interesting events. he said: ‘I forbid my people to go along with this Gandhi nonsense.’ I believe that Hess was the only person to whom he had explained the ideas developed in his manuscript. H RH the Duke o f Windsor had abdicated as King Edward VIII on 10 December 1936. He saw in the Duke a friend of Germany and regretted that he had not fought the Establishment rather than abdicating. 6 This visit took place on 20 October 1937.
its furnishings and above all the view from the gigantic window over the mountains. 2. the opinion of his visitor that it would have been best for Europe if Martel had lost the eighthcentury battle of Tours/Poitiers against the Moors. During a meal. also impressed him. 11.11. as well as other social advances. After initial reluctance Hider agreed and Knut Hamsun came. for then Europe would have become Muslim. Norway. after the war convicted of collaboration and fined. d.8. 1920 Nobel Prize winner for literature. by the house itself. retained its scientific knowledge and its peoples would have lived in peace with each other. reduce working hours and introduce state health insurance. 9 Knut Hamsun (b.7The conversations with the Aga Khan gave Hitler much food for thought. d. The Aga Khan had given thought to the European relationship and that pleased Hitler. 169 . German measures to curb unemployment.1859 Lom. 8 This visit took place on 4 September 1936. On the other hand the visit of Knut Hamsun9 to the Berghof left a bad taste in the mouth.6. 4. The Aga Khan III (b. Dara Christian and I heard a heated exchange —we were 7 This visit took place on 20 October 1937. This happened in June 1943. member of Norwegian Quisling Party. During the conversation between Hamsun and Hider. during the Second World War N azi sympathiser.g. in particular the ban on drinking and eating the flesh of swine.2. e. Baldur von Schirach had mentioned Hamsun’s visit to the Journalists’ Congress in Vienna and urged Hider to invite the Norwegian to the Berghof. He found himself in agreement with many non-barbarous aspects of Islam.1952 Grimstad). Another of the visits by prominent statesmen to the Berghof which Hider was fond of describing was that by Lloyd George8 in 1936.1877 Karachi. Novelist. Dr Ley had acquainted Lloyd George before his visit to the Berghof with the work of the Arbeitsfront. and the practice of periodic fasting. He had been impressed by the geographical situation of the Berghof. the official workers’ organisation.1957 Geneva) was the forty-first imam of the Ismaeli sect.THE BERGHOF the richest men in the world. 19.
which she was now doing. and there was visible relief when a waiter appeared suggesting that he might refill the glasses. Another great sigh of relief went up when just after midnight Dr Goebbels arrived. 170 . while the other guests were talking. urging in emotional tones that Terboven be recalled. She had been awoken at night by an unusually loud disturbance and had watched from a hotel window as some weeping women were ordered forward across a bridge and disappeared into the night. in one thousand years?’ In a tone which made it evident that he considered the matter closed. or possibly because Hitler would tolerate no contradiction. Maybe because he was rather deaf.’ and here he moved his cupped hands up and down like a pair of scales. ‘And what will become of Europe in one hundred. he is said to have declared: ‘I am committed by duty to my people alone. but it was misplaced. Holding our breath we crept closer. I had also noticed that. What does it matter to you what happens to female Jews? Every days tens of thousands of my most valuable men fall while the inferior survive. we heard Hider shout at him: ‘Be silent! You know nothing about it!’ Hider had said precisely the same thing on Good Friday 1943 to Henriette Schirach at the fireplace. From her friends she learned next day that this had been a deportation of Jewish women.HE WAS MY CHIEF in the lounge. the subject of which was an occurrence in Amsterdam a few days previously. which was separated from the Great Hall only by a curtain. Hider answered her in a very brusque manner: ‘Be silent. You are sentimental.1 remember that evening Eva Braun had sat at Hitler’s right before she went upstairs. Hamsun had had the gall to take Hitler to task over the measures introduced by Gauleiter Terboven in Norway. and to the left of Henriette. an argument developed between Henriette and Hitler. In that way the balance in Europe is being undermined. Frau von Schirach. to nobody else!’ The guests noticed that Hitler had now become morose. you understand nothing about it. She promised to bring the matter to the attention of Hider. she told me in 1978.
’ Next morning there was a deathly stillness over the Berghof However this had nothing to do with the departure of the Schirachs. The sirens would howl frequently and the smoke batteries would 10 Herta Schneider nee Ostermeier (b. On 28. and would be invited to Portofino with her. one or another of the doctors’ and adjutants’ wives would be in favour with Eva Braun from time to time. but Hitler waved this aside by saying: ‘That is not your decision.4. It was often an odd bunch up there on the Berg.’ When Schirach pointed out that ‘the Viennese are all for you. who had driven off in the early hours without so much as a by-yourleave: on Martin Bormann’s orders it was always quiet across the entire Berg every morning because Hider spent most of the night studying reports and other documents and slept in more or less until noon.1913 Nuremberg) knew Eva Braun from their primary schooldays. 4. Herta married. Hitler said that it had been ‘a mistake to send Schirach to Vienna. One had to tiptoe around the bed and not bathe until midday.4. Eva Braun was a frequent visitor at the Ostermeier’s because her parents were not interested in her. O f the other women. Eva Braun’s sister. You will stay where you are. where Eva Braun liked to spend time amongst her friends in a deckchair until Hitler appeared. and also a mistake to have annexed the Viennese into the Greater German Reich. Hider retorted. From 1944. enemy aircraft began to overfly Berchtesgaden. ‘I am not in the least interested. 171 . I reject them/ At this Schirach declared that under the circumstances he was resigning his post. All guests were also required to make no noise on the terrace. In 1936. this being a place she adored.1945 she left for Garmisch-Partenkirchen with Margarete Fegelein. All house guests in the floor above his had to pay heed. Frau Schneider10was her friend of longest standing.THE BERGHOF for Goebbels launched at once into a diatribe against Baldur von Schirach. mein Fiihrer. and from then until 1945 spent long periods at Obersalzberg with her children. All the others would then be wary and maintain a reserve towards the reigning favourite. accusing him of fostering Austrian policies in Vienna.
Within a few steps of the back door of the house there was an iron door from where sixty-five steps led down to the bunker complex. as he did on his FHQ. In 1943 bunkers were built. They saved my life in 1945. 172 . Hitler was expecting a concentrated attack on Obersalzberg. ready by Christmas.HE WAS MY CHIEF conceal the region.
but after the upper rooms of the Radziwill Palace. where there was an emergency exit in the form of a small concrete turret. There were several stairways from the main building down into the bunker. had been made uninhabitable by incendiaries. the Adjutancy Wing. The bunker had been intended as a temporary refuge during air attacks. 173 . Hitler spent most of his time with his staff in the bunker. and so at the beginning of 1945 we secretaries would take our meals during the day with Hitler behind drawn drapes with the lights on while outside the spring sun shone down on the gutted Hotel Kaiserhof and the Propaganda Ministry. Hitler withdrew his FH Q to Berlin in January 1945. or from a tower-like entrance in the park. In the Radziwill Palace. particularly the library. Access was by a stairway from the Reich Chancellery palace and a 105-metre-long corridor known as the ‘Kannenberg Corridor’ because o f the provisions stored there. An alleged corridor into the Propaganda Ministry suggested in many sketches never existed. A f t e r t h e f u h r e r .b u n k e r in 1 The Vorbunker (built 1936) and Hitler’s bunker (built 1943) lay below the Reich Chancellery palace in the Wilhelm-Strasse and extended below the Reich Chancellery park.1 It extended below ground into the Reich Chancellery park. was undamaged. including the Staircase Room.Chapter 15 The Order to Leave Berlin: My heave-taking of Hitler the Reich Chancellery park had been reinforced.
sinking back after a while. He always managed to rise to greet us though.4. the other into a cramped bedroom. The study was dominated by a portrait of Frederick the Great2which hung over the writing desk. when Hitler received us after the nightly situation conference. On either side was a door. At lunch. It is not trembling so much. if not. Already narrow. He no longer discussed the Church. my hand is improving. His physical decline made daily advances despite his desperate attempts to hold himself together. Thus almost every day he would tell us: ‘This beast Blondi woke me again this morning. it was equipped with a small writing desk. I can almost hold it out firmly. his manservant raising his feet for him. a table and three chairs. about being Nordic and German. With his large. She came to my bed wagging her tail and when I asked her: ‘Do you have to do your business?’ she dropped her tail and crept back to her corner. powerful eyes the old ruler glared down at Hitler. Ancient Greece or the rise and fall of the Roman Empire. in the early hours of the morning) the same again. sparsely furnished room. exactly 200 years before: ‘I shall either hold out or. He was almost permanently emotional. racial problems. who had always been so passionately interested in all matters of 2 This was the portrait by Anton Graff. dinner and the nightly tea sessions (i.’ The things he talked about became gradually more flat and uninteresting. a small sofa. I desire that everything shall be destroyed and the Prussian name be buried with me. Hitler’s attitude at the end can be summarized precisely by a letter from King Frederick to Podewils on 27. one leading to his bathroom.’ Or: ‘Look. To move across the room required a repositioning of the chairs.’ 174 .e. The room was cold and unpleasant.HE WAS MY CHIEF The evening meal was served in the Fiihrer-bunker in Hitler’s small. She is a sly animal. he would usually be lying exhausted on the litde sofa.1745. At six in the morning. economic and political questions. The oppressive narrowness of the room and the overall general mood in the bunker had a depressing effect. and his talk was increasingly the monotonous repetition of the same stories. He.
The morning tea session usually went on for two hours. Accordingly when enemy bombers were arriving he would dress fully and even shave. It would not leave him much time for sleep. If the lights flickered. Wolf. for he feared that a bomb falling diagonally could penetrate and collapse the bunker wall. lying in ground water. nutrition and the stupidity and degeneration of the world. when the wire and police network would be switched on.TH E ORDER TO LEAVE BERLIN science. In the heavy air raid of 3 February 1945 fifty-eight H E bombs fell around the Reich Chancellery. zoology. During an air raid alarm he would never remain alone in his room. and from the litter Hitler had selected a male puppy to raise and train himself. would tremble perceptibly. there was a danger that in such a case the water would rush in. Every time a bomb exploded in the vicinity. Afterwards Hitler would rise and drag himself to the dog’s box. We used to sit listening to the bombs exploding. After a while he would return the puppy to its mother and take his leave of us to rest. stroking it incessantly while muttering its name. was customarily an extended affair. and would 175 . The approach of enemy aircraft would often be announced during this period. he would at once request a damage report. The radio channel broadcast a monotonous bleeping when not passing reports about the bombers. The nighdy situation conference would not begin until long after midnight. Since the bunker was below the water table. botany and human development spoke out in the latter months only on dog-training. Blondi had had puppies in March. Dinner. usually between 2100 and 2200. and there was never a day when the government district was spared. Hitler would say: ‘That was near. for the sirens would generally start up at about 1100. This was latterly around 0800. the bunker. On the approach of enemy bombers he would always get up. He would remove this animal from the box. That bomb could have hit us!’ After the All-clear. and listen to it calmly without interrupting. sit in his room with the puppy in his lap.
he would play with the dogs and sleep a few hours until the next aerial intrusion. The chorus of congratulations from the personal staff and the military that morning was very restrained in comparison to earlier years. The situation over the last four days had changed considerably. he went on in annoyance. whereas that of the Allies was much more impressive. Reichsleiter 176 . The series of rolling air raids lasted from early morning until 0200 next day. On Hider’s fifty-sixth birthday on 20 April 1945. We no longer left the bunker. ‘Berlin will remain German. Afterwards he would call the afternoon situation conference. In an hour a car leaves for Munich. The mood was very gloomy as we ate. According to the service roster. he told us. That evening during the bombing raid just before 2200 Johanna and I were summoned by Hitler. which would take us to lunch. and the first Russian tanks reached the outskirts. You need have no fear!’ I told him that I had no fears since I had come to terms with dying. We could hear the thunder of the field guns from the Reich Chancellery. He received us in his room looking tired. ‘Over the last four days the situation has changed to such an extent that I find myself forced to disperse my staff. pale and lisdess. Johanna Wolf and I had to keep the boss company until lunch.HE WAS MY CHIEF often last until dawn. Berlin was surrounded. However I could not imagine how Germany could carry on when our forces were being sandwiched ever more firmly between the Americans and the Russians. and the whole game would begin again. Then the tea session would follow. you will go first. ‘Remain calm’. As you are the longest serving. On 16 April at lunch in the Staircase Room when I asked him whether we would remain in Berlin he had replied almost involuntarily: ‘O f course we shall remain in Berlin. we just have to gain time!’ Even in his last address to the Gauleiters on 24 February 1945 in Berlin he had informed them of his unshakeable conviction that ‘we must gain time!’ Now the tune had changed. You may take two trunks.
fled on 22 A pril. Frau Christian (Dara) will in any case get away and if another of the younger girls fails to make it. If it comes to the worst. As if stunned I departed Hitler’s room to begin packing along with my colleague Wolf. but gave us a handshake instead. that is Fate! He did not take his leave of us as he usually did with a kiss to the hand. since I had already decided to use the cyanide capsule which Skorzeny had sold me for a bottle of whisky. . the British historian. and had them forwarded to me in Berlin at the beginning of 1945 before the Allied 3 Schroeder confirmed that Hitler said this. ’ I had always abhorred sudden and unexpected enforced journeys. and left me in a state of confusion. . Her mother lived in Munich. Ullstein.TH E ORDER TO LEAVE BERLIN Bormann will give you further instructions/ Since I had no family I requested permission to stay in Berlin. Hitlers Letzte Tage4 he wrote: ‘Two of Hider’s secretaries. later I will found a resistance movement. Trevor Roper. pretended to know my movements better than I did. He must have noted our subdued mood for he added. Fraulein Wolf and Fraulein Schroeder. You are the most valuable people to me. What it meant remains a mystery. I am coming down in a few days!’ This order to abandon Berlin on 20 April 1945 was not what I had expected for myself. the young will always come through. 4 3rd edition. None of my possessions was in storage. perhaps in an attempt to comfort us: ‘We shall meet again.3 and for that I need you both. . No. He would not accept this. probably his way of indicating that he would hear no further appeals and that the matter was closed. I had left: several trunks in the west and east in 1944. This would allow my junior colleague to leave instead. for in the German language version of his book. 1965. This latest order by Hitler awoke in me far greater feelings of reluctance than ever before. . 177 .
where we secretaries had a room for sleeping and storage. These were the only telephone calls from him I ever received in my twelve years of service . In a weak voice he said: ‘Children. It was a dead room. whose fate concerned me gready. I had not fully realised the chaotic situation. make ready. Everybody stared at us and our two cases with curiosity. I saw armaments minister Speer in the telephone exchange. . As 178 . hurry.HE WAS MY CHIEF advance. around 0230. oppressively quiet like a tomb. . the machine will take off as soon as it is warmed up. Johanna had an unpleasant feeling about her luggage and after it had been stowed she had second thoughts about parting with it. The room allocated to us was originally built as a transmitter room. but although he had not hung up he made no reply. A short while later. The car cannot go through and you will have to fly early tomorrow.’ His voice sounded flat. I felt strange and passed the anxious bystanders full of shame. Suddenly the telephone rang. I called out. for the ceiling and walls were sound proofed and suppressed the tones of conversation. I told him of Hitler’s order and asked him then about Dr Brandt. Hider had sentenced him to death for defeatism and he was being held prisoner in a Berlin villa. Johanna Wolf and I handed over our cases. I was very unhappy about the room. and he broke off halfway through the conversation. the hole is closed up (we were to have driven through the Czech Protectorate). we struggled through the crowded corridors of the Reich Chancellery bunker on Voss-Strasse. It sounded like a beehive. on the basis of Hitler’s assurance that my things would be safest there. and I told her there would be no problem. The packing seemed senseless. It was Hitler.’ He rang again after midnight: ‘Children. Speer told me: ‘We will spring him!’ The vestibule of the \bss-Strasse bunker was crowded with civilians from Voss-Strasse sheltering from the air raid. On the way to the Voss-Strasse bunker. In the courtyard of the Radziwill Palace a lorry stood ready.
we went to Tempelhof airport and our luggage to Staaken. ruins and smoke. The silence was suddenly oppressive. All vestiges of order for the departures had vanished. I do not remember a single word being spoken. As no light could be shown. When we finally located our vehicle. We sat speechless in the aircraft between soldiers seated on green ammunition cases. and Vol\ssturm men hastily erecting street barricades. smouldering heaps of rubble. The airport commander advised us to try to board a Junkers transport bound for Salzburg whose arrival had just been notified from northern Germany. We were as if paralysed as we landed. Eventually he got us to Tempelhof. At Tempelhof airport nobody had knowledge of the Ju 52 of which Hitler’s Luftwaffe adjutant Oberst von Below had spoken. Without luggage. how he managed to get round the red tape I have no idea.5 the aircraft took off in rain and snow. While on the bus for Obersalzberg a few hours later I reflected on how lucky we were to have come out of this flight alive. In the middle distance we could hear the thunder of Soviet artillery. It was a macabre drive through the night past burning houses. Unknown drivers from the SS-Leibstandarte waited with their vehicles for their scheduled passengers. It was 5 ‘Shoko-Dallmann’ were vitamin tablets with caffeine covered in chocolate and marketed in round tins. After some negotiations we succeeded in this. and he had no orders to take us to Tempelhof or Staaken. 179 .THE ORDER TO LEAVE BERLIN it later transpired. In the courtyard of the Radziwill Palace chaos reigned. only a travel bag and knapsack. it was very difficult to find one’s way around. its driver did not know Berlin. packed at the last minute on Schaub’s orders and which contained round tins of ‘ShokoDallmann’. One can imagine our fright when through the cotton-wool ear plugs we heard sounds similar to shooting and the machine seemed to lose height quickly. After an exciting flight over burning villages and towns we touched down at Salzburg in the early morning.
Fiebers. crashed at Bornersdorf near Dresden. and it was their remains which were wrongly identified after the crash. an unknown male and two women. E. The Ju 526 which took off from Staaken. and on which we were booked. Basler. Budka. radio operator. I did not learn of this until several years later. piloted by Major Friedrich Gundelfinger. the remainder for the Soviets..’ The unknown male may have been a member o f the SS-Begleitkpmmando who ‘left on a flight to Upper Bavaria with a manservant and two secretaries.. This was at any rate what I was told by the priest. Schleef. ‘The two women were carbonised and identified from their clothing. Arndt. German soldiers in the Bornersdorf vicarage removed some of the items from my trunk.HE WAS MY CHIEF actually a double miracle that we had survived. The identity of the woman who took my place aboard the aircraft and was buried under my name was researched for many years but remained a mystery. She was Martin Bormann’s secretary and remained at the Reich Chancellery until her escape from Berlin on 1 May 1945. The official list of the dead was: Major Gundelfinger. The victims were interred by the Wehrmacht. The crew had allocated our two unclaimed seats to two other women. Kruger and Christine Schroeder. 180 . who was unable to reveal any details at all about my alleged burial and said I should contact the authorities in East Berlin. Becker. pilot.’ Else Kruger was not the other woman identified. and left. One of the two female bodies burnt to a crisp was identified as me because my trunk was stored in the cargo hold. 7 Hitler’s favourite manservant Wilhelm Arndt was one o f the passengers aboard this flight.7 6 Actually a Ju 352 o f the Fuhrer-Staffel.
They had no idea of the catastrophic situation in Berlin and asked when the Fiihrer would be coming down. Their mother. were only Begleitdrzte. Dr Haase and Dr von Hasselbach. There were frequent air raid alarms. It had hit him hard. Hitler’s personal physician Dr Morell arrived. and Herta Schneider. proof that Hitler had at least given some thought to coming to the alpine redoubt. Dr Karl Brandt was often incorrectly described as the Fiihrer’s personal physician. Frau Franziska Braun. that is. for besides Hitler’s naval adjutant Jesko von Puttkamer some of the SS-Begleitl{ommando had moved into quarters at the Berghof. Dr Brandt and the deputies he had suggested. Even Frau Kannenberg turned up in order to join her husband at Thumsee. Eva’s long-term friend. when Obersalzberg would be hidden under a smoke screen. After a short stay he took his leave saying he was going to Bad Reichenhall. Eva Braun’s sister was very pregnant. He was very distressed and bitter: the Fiihrer distrusted him. he said. Here I must mention something about Dr Morell. Two days later. they were available to perform emergency surgery on Hitler if so required during his U PON OUR arrival a t 181 .Chapter 16 The End at the Berghof the Berghof we found some guests already there. on 24 April 1945. were also present. The enemy aircraft passed overhead without bombing. and had sent him packing. They saw us as the vanguard.
If a photographer reached for his camera. and this could compromise Hider. a wonder-drug he had produced in his own pharmaceutical laboratory. He began with harmless glucose. which was responsible for the award of foreign decorations. Hitler had ‘no time to be ill’ he repeated over and over. and Morell based his treatment on that dictum. Morell was suddenly at Hider’s side. The Foreign Ministry Protocol Section. and which renewed the colonic bacteria. rightly feared that Morell was wearing medals to which he was not entitled.HE WAS MY CHIEF travels. even amongst Hitler’s close staff. Another quite special objection to him was the foul-smelling delousing powder he had patented and which he spread in large quantities around his barrack hut at FHQ. available in 182 . For example he would not peel an orange but bite into it until the juice squirted out. vitamin and hormone injections. most of his patients being from the artistic world. was of average height. As soon as Hitler reported any discomfort. on which he had also picked up some foreign eating habits. He originated from Hesse. Moreover. How had he been appointed Hitler’s personal physician? In 1936 when Hitler’s chronic gastro-intestinal disorder would not respond to treatment. corpulent and wore a good-humoured expression. He was also vain. The personal physician (Leibarzt) was Dr Theodor Morell. and also rid Hitler of the eczema on his legs. Dr Morell had a luxury practice on the Kurfurstendamm in Berlin. was suppressed before it developed. and he succeeded in overwhelming Hitler’s aversion to having an unknown physician treat him. Morell was said to be a profiteer. On his thick fingers he wore exotic rings obtained during overseas voyages. Hair sprouted from his ears and cuffs. Then he went over to ‘Vitamultin’. Morell won Hitler’s total confidence. Any cold. Morell would be on the spot with his injections. Heinrich Hoffmann had recommended a wonderful doctor of his personal knowledge. Hitler named him his Leibarzt and later made him a professor. When Dr Morell brought about a decisive improvement in the complaint with the Mutaflor drug (used nowadays for ulcerative colitis).
TH E END AT THE BERGHOF
ampoules and gold-wrapped tablet form. Hider became increasingly
dependent on this drug until one day it no longer had the desired
effect and Morell had to look for something stronger. My assumption
seems confirmed by an article appearing in edition 7/1980 of Spiegel
magazine under the tide Hitler —An der Nadel. This was based on
the book by Leonard L. and Renate Heston, The Medical Casebook
o f Hitler, which concerned itself with the same question. Morell’s
files were made available to the US psychiatrists and the drug
‘Vitamultin’, containing the stimulants pervitin and caffeine, was
described as ‘an especially effective preparation because caffeine
enhances the effect of pervitin’.
In the autumn of 1944 when Dara and I took tea alone with
Hider, we found him in a strikingly relaxed mood. The waiter had
placed his painful leg on the sofa for him, and now he was stretched
out comfortably. During a murmured conversation he suddenly
threw open his arms and spoke ecstatically o f ‘how lovely it is when
two people find themselves in love’. Dara and I were astonished, for
we had never seen this mood before, Hitler given so mysteriously to
the joys of love.
Afterwards we sought out Dr Morell in his hut and asked why the
boss was behaving so strangely. Morell looked at us over his glasses
with a sly smile: ‘So you’ve noticed? \es, I am giving him hormone
injections from bulls’ testicles, that should pep him up!’ In March
1980, Robert Scholz, who had worked on Rosenberg’s staff, told me
that Morell had asked Rosenberg to get him some bulls’ testicles.
That Hider was dependent on stimulants prescribed by Morell
is proven by several reports. After the attempt of 20 July 1944, Dr
Erwin Giesing, who had been called in to treat Hitler’s damaged
ear drum, made it known that Morell was treating Hider with
ill-considered medications. One morning Dr Giesing discovered
on Hider’s breakfast tray a small bottle of anti-flatulence pills
containing two powerful poisons. When he asked the servant
Linge how many the Ftihrer took daily, he was told ‘Up to sixteen’.
183
HE WAS MY CHIEF
Appalled at Morell’s negligence, he had Dr Brandt, who as head of
the Health Department was no longer constandy at FHQ, come at
once to Wolfsschanze. Dr Brandt and Dr Hasselbach explained to
Hitler that the trembling of his left hand and gradual loss of vision
were the result of the poisons in the anti-flatulence pills and that it
was irresponsible of Dr Morell to have made them freely available
to be eaten like sweets.1 Hider would hear no evil spoken against
Dr Morell, upon whom he was now so dependent that he ignored
the advice of Brandt and Hasselbach. Hitler thought that their only
intention was to get rid of Morell and, since they knew that he,
Hitler, could not live without Morell, they must be aiming indirectly
to get rid of him too.
The extent to which he believed this became clear to me at a
luncheon at the Reich Chancellery in March 1945. From now on
Hider did not want Brandt and Hasselbach at FHQ. His distrust
of Dr Brandt grew when he heard reports allegedly made by Brandt
as to the hopelessness of the war. The fact that Dr Brandt had sent
his wife Anni from Berlin to Liebenzell, and not to the Berghof,
a day before the Americans arrived at Liebenzell, earned him the
death sentence.
On 16 March 1945 Johanna Wolf and I were scheduled to provide
Hitler with company at the table for lunch. As always the table
was carefully laid, the lamp standard switched on and the curtains
drawn, hiding the ruins of the Hotel Kaiserhof and the Propaganda
Ministry. We sat waiting in the Staircase Room far longer than usual.
Finally, probably around 0230, the servant Linge opened the door
and announced: ‘The chief is coming.’ Hider followed him in with
1 In her notes, Schroeder recorded: ‘In the autumn of 1944 the boss took “anti
flatulence tablets” containing two strong poisons including belladonna. I remember
Dr Giesing saying that all the health problems Hider suffered came from taking
these poisons on a regular basis. Hider complained about his serious loss o f vision
. . . I remember how often he used to scratch himself.’
184
THE END AT THE BERGHOF
a worried frown, kissed our hands absent-mindedly and gave vent to
his anger as soon as we had sat down:
I am very annoyed with Albrecht.2 Eva is right in disliking him.
As soon as I do not see to everything myself, nothing gets done. I
expressly ordered that the new winding entrances to the bunker in
Voss-Strasse should have iron underpinning. I asked Albrecht if it
had been done. He said yes. Now I have just seen that the entrances
have only been given a concrete foundation, which is senseless. I
really cannot rely on anybody any more. It makes me ill. If I did not
have Morell I would not be able to look after everything myself, and
then I would be in a complete mess. And those idiots Brandt and
Hasselbach wanted to get rid of Morell! What would have become
of them the gendemen failed to ask themselves. If anything happens
to me Germany is lost, for I have no successor!
This talk of no successor was not new. After Hess went to Britain in
1941, Goring was the official successor, but Hitler did not think he
was capable. I once argued with him when he said there was nobody
who could be his successor. He replied that Hess had gone mad,
Goring had lost the sympathy of the people, and the Party did not
want Himmler. When I told him that Himmler was the name being
mentioned by many people, he began to get annoyed. Himmler
was a person with absolutely no feeling for music. To my objection
that that was not so important nowadays, for the arts could supply
competent people, he retorted that it was not so simple to do that or
he would already have done it. From that I deduced that in Hitler’s
2 Alwin-Broder Albrecht (b. 18.9.1903 St Peter/Freisland). 27.6.1938-30.6.1939 as
Korvettenkapitan deputised for Jesko von Puttkamer as Hitler’s liaison officer to
the German navy; 30.6.1939 following an altercation between Raeder and Hider
discharged from Wehrmacht service but retained the right to wear naval uniform;
1.7.1939 appointed personal adjutant to Hider in rank o f N S K K Oberfuhrer,
where he had responsibility amongst other things for building work at the Reich
Chancellery; 1.5.1945 disappeared without trace.
185
HE WAS MY CHIEF
opinion none of the proposed candidates would be considered as his
successor. At the suggestion of Himmler he became angry and asked
what had possessed me to say such a thing. It hurt his vanity that
those of us who knew Himmler and himself should place Himmler
on a par with him. He left offended, saying: ‘Keep on racking your
brains for who should be my successor.’ On the subject of Morell,
Hitler also stated that ‘without Morell he would be all out of joint
and lost’, but towards the end of the war he did eventually become
suspicious of Morell, and feared being poisoned by him. On 22 April
1945, Dr Morell was expelled from Berlin.
During my internment at Ludwigsburg Camp Dr Brandt
arranged a brief meeting with me. He told me that the Americans
had put him into a cell with Morell. He had told Morell: ‘You swine!’
which signified that he held Morell responsible for having ruined
Hitler’s health. This would certainly not have been done on purpose.
What was Morell to do when, as time went by, medicaments lost
their potency on Hitler, who then demanded that Morell kept him
able to work? Ultimately there was probably nothing else he could
do but give in to Hitler’s wishes. Whether Morell took into account
the possible side-effects is not known . . .
Albert Bormann, Martin Bormann’s brother, had meanwhile
arrived at Obersalzberg from Berlin and was living in the
Berchtesgadener H of with his very pregnant wife. On the morning
of 23 April 1945 he was summoned to Goring’s property above the
Berghof Afterwards Albert Bormann dictated to me the content
of this conversation. Goring had asked him where the records of
the situation conferences were kept. ‘They must be destroyed
immediately’, he said, ‘or the German people will discover that for
the last two years they have been led by a madman!’ Albert Bormann
told me to type a string of dots in place of this sentence. He believed
that Goring was intent on being Hitler’s successor.
That same evening the Berghof was suddenly surrounded
by armed SS. Nobody was permitted to leave the house. My first
186
The bombs rained down. a thick cigar clamped between his teeth. Wednesday 25 April 1945 was a sunny spring day with a cloudless sky. (TN) 187 . There was an acute danger of air attack but I decided to ignore it and stay in bed. There were still some patches of snow lying around. telling her to get to cover quickly. I grabbed my handbag and coat and ran into Johanna Wolf’s room. Nobody could explain why the Berghof had been surrounded. In recent days aircraft had overflown the Berghof but not bombed. The major attack on the Berghof began. A half hour later the second wave arrived. The men of the 55Begleitkpmmando stood at the inner doors of the Berghof vestibule with machineguns at the ready and magazine pouches on their belts. Without waiting I ran down the steps of the old building. The technical installations * The planes were actually from the RAF. Probably nobody had seriously considered that the Berghof would ever be attacked. and thus all were taken by surprise and many tumbled into the bunker only half dressed. but it was not cold. Some hours later after many unsuccessful telephone enquiries. 617 Squadron. Towards 0930 the early warning alarm sounded. At each hit I ducked involuntarily. Straight away the sirens howled and at once American bombers* appeared over the Hohe Goll mountain and dropped bombs. Radio communication to Berlin was no longer possible. an orderly managed to discover from the SS barracks higher up that Goring had been arrested. Amongst them. was Konteradmiral von Puttkamer. with Stoic calm.THE END AT THE BERGHOF thought was that Himmler had staged a coup. or rather I flew down under the air pressure. The second bomb fell at the side of the old house where our rooms were located and destroyed the stairway. I had booked an appointment for 1000 with Bernhardt hairdressers in the Platterhof hotel. many directly on the bunker. The explosions echoed eerily against the rocky mountainside. One exploded nearby. to the bunker entrance only a few metres across the courtyard where sixty steps led down into the refuge.
Seidler and Zeigert. so highly praised as secure. would miscarry. and water began to enter the bunker by way of the steps. the scene was a crater landscape. trees felled at the root. the paths scrambled to rubble. The chaos and fear were indescribable. were largely undamaged. only six were killed. 188 . A picture of appalling destruction greeted us. or she wished to put her sister’s mind at rest. Doors and windows had disappeared. Inside the house the floor was thickly covered with debris and much of the furniture had been demolished. The walls still stood (only one side had been burst open) but the metal roof hung in ribbons. Nothing green remained.500 potential victims in the area at the time.232 tons o f bombs.270. A few days later Herta and Greta. after spending the intervening period packing. A short while before. All the ancillary buildings had been destroyed. up to a hundred metres down. The lighting and ventilation failed. slowly plodding up the sixty steps into the daylight.3 Since there was nothing habitable. Two men from the 3 The first wave of bombers which came in over the Hohe Goll took out the flak and smoke batteries. stopped working. left by lorry and car from Hider’s readyvehicle park on the Berg for Garmisch.’ and she concluded with the hope that Greta ‘should have no worries. Greta Fegelein and Herta Schneider moved into Eva Braun’s bunker. p. We feared that Frau Fegelein. and o f the 3. We left the bunker eventually at about 1430. Die Fuhrerhauptquartiere. who was within a week or so of giving birth. she would see her husband again. They had filled many trunks with Eva Braun’s clothing and left them at Schloss Fischhorn near Zell am See where there was an SS post. The Berghof had been badly damaged. A day or so later Johanna Wolf went by car to Miesbach to ask friends if they would put us up temporarily. where Herta lived. the second wave dropped no less than 1. We do not intend to fall alive into the hands of the enemy. Eva Braun had written to her sister: ‘We await hourly the end. Herbig.’ Here Eva was either mistaken.HE WAS MY CHIEF of the bunker. The bunkers and underground galleries. Johanna Wolf and I into Hitler’s.
1. Albert Bormann lived with his wife. as did Schaub. also possible lodgings. They only came up to the Berghof to organise food and alcohol. files.1945 arrested by CIC at Berchtesgaden. When Schaub disappeared into the ruins of the Berghof for a brief while.6. etc. no message from the boss.1948 released from internment. 189 . On 29 April it was announced in a radio broadcast that 4 This ’lad’ was actually thirty-year old SS-Untersturmfuhrer Heinrich Doose (b. everybody else he deliberately ignored. on 21. Unfortunately I took only a single letter from the carefully assembled batch with male handwriting. had previously been the driver for generals Burgdorf and Maisel and was present at the suicide o f Rommel.4. which I hid from Schaub and retained. It had a white label affixed to the cover with the typed title ‘Idea for and construction of the Greater German Reich’. 16. On the terrace of the Berghof he put a few cans of petrol to work burning letters. Schaub also brought a friend. 2. Meanwhile Schaub arrived and without a word set about clearing Hitler’s safe in the Fiihrer-study. From 1937 with the SS-Begleitkpmmando and Schaub’s driver. I also took a bundle of Hitler’s architectural plans.THE END AT THE BERGHOF SS-Hauptamt whom we had got to know at the Berghof mentioned the possibility of getting false papers for us. 7.4. afterwards took Schaub’s family to Kitzbiihl/Tirol. in the Berchtesgadener Hof.1945 flew from Berlin to Ainring and brought Schaub from H ider’s flat in Munich to the Berghof for the work o f destruction. A shoebox filled with Geli Raubal’s correspondence caught my eye. nothing of what was happening. memoranda.7. books. He exchanged no pleasantries with us.1912 Kiel. A short distance away from the bonfire.1952 Piding). Unfortunately I left this where it was. Hilde Marzelewski. He only allowed a lad4from FHQ to help him. d. I had a closer look at what he was burning. 1. where the compacted snow had heaped up against the terrace wall. was an A4-size binder burnt at the edges similar to an old-fashioned accounts ledger. who had given birth during the bombing raid. Schaub’s bonfire below a leaden sky made a miserable impression. It was however conclusive and set out clearly and distincdy the situation in which Geli had found herself. a dancer from the Berlin ‘Metropol’.
but now he was just another stray.HE WAS MY CHIEF Hitler would not leave Berlin. ‘Do not lose courage. When Hider’s death was announced on 1 May 1945 the change occurred in a manner scarcely to be described. I felt alone and abandoned too.’ I asked myself what else it could possibly be. Chaos broke out on the Obersalzberg. The police officers so previously devoted to law and order. The Pension Posthof at Hintersee near Berchtesgaden had long been reserved for employees and members of the adjutancy and Fiihrerhousehold in Berlin. Negus was symbolic of the change that had come over the place. From the Bechsteinhaus. the house staff and SS men of the Begleitkpmmando. Albert Bormann told the men of the SS-Begleitkpmmando. Negus. He kept insisting that I should come at once. house administrator Mittelstrasser made off with a loaded lorry. People from Berchtesgaden stormed the farm and cleared it. Albert Bormann had arranged rooms for Johanna Wolf and myself in this pension. all were suddenly transformed and unrecognisable. and Speer’s house. They were not heard from again. Previously clumsy and dim. but I preferred 190 . His wife followed him a few days later after extensive packing. it is not the end. incapable of deciding my next move. In the cavernous Berghof bunkers where we were living strange women appeared. Food and drink were sent there for them. she matured overnight. had risen to absolute power. slunk unnoticed and abandoned through the ruins. and made off with full containers. At last it was clear to me that all was lost. The cook Bliithgen. the former guest house for state visitors. Nothing was left in the Platterhof hotel hairdresser’s shop. a previously demure young girl. the native population removed not only the articles which were easily transportable but also all the furniture. He had not been badly treated before. the Scotch terrier so adored by Eva Braun but loathed by everybody else because he growled at everybody and nibbled at their boots. possibly friends of the Kripo officers. dragging off animals and breaking open stockpiles of potatoes. After clearing the Berghof kitchen of rubble.
Even the valuable silverware was to be destroyed.5 I also mentioned to him the intention of the Kripo (Kriminalpolizei) people to blow up the bunker rooms where Hitler’s private art collection was stored. The Kripo officials even ripped out the fly-leaf of any book with her name on it. but here at least somebody saw sense and on 5 May an SS lorry arrived to cart away the silver. I was to give everybody a note of what I was taking and remove them myself/ 191 . Boxes of hand grenades were already placed at the bunker entrance. was burnt on the terrace. Albert Bormann was of the same opinion and agreed that everybody should take a picture with him. the carpets. He had no idea what to do about the paintings. Meanwhile the Kripo officials had begun destroying everything they could lay their hands on in the bunkers. These bore her insignia. So I stayed at the Berghof. dresses. Photo and film albums of Eva Braun with Hider were senselessly cremated. In Eva Braun’s bunker I surprised them smashing her valuable porcelain. but apparently Schaub had the dead Hitler’s orders to go through with it. they told me that ‘everything had to be destroyed which indicated the existence of Eva Braun’. painted by Sophie Stork. living in the bunker. etc. nor anywhere to go after so many years cut off from the world in Hider’s circle.THE END AT THE BERGHOF to wait for Johanna first. shoes. everything in fact which indicated a woman’s presence. Once the Americans began to close in he was suddenly of the opinion ‘that it was not good for everybody to be concentrated in one place. a monogram in the form of a four-leafed clover designed by Dr Karl Brandt. When I expressed my horror.. The Berghof staffwanted to ship out the furniture and I contacted Albert Bormann at the Berchtesgadener H of to obtain his agreement. hats. I considered it madness to destroy these valuable paintings. 5 In her notes Schroeder wrote: ‘I obtained his permission that the girls should have some o f the furniture. What remained of her wardrobe. tapestries and paintings. It was pure madness. It would be better if everybody took it upon themselves to find their own accommodation/ But where? I had neither the means to take off.
said some years later in a conversation with Henriette von Schirach: At the last moment just before the Americans arrived. SS-Sturmbannfuhrer from 21. Italian and French painters. 192 . they sent me a part of Hider’s private collection from the Obersalzberg!’ Amongst the invaluable treasures salted away at Altaussee since 1944 were those which Hitler had scheduled for the planned museum at Linz. He frequendy made known his satisfaction that through his travels to Rome and Florence it had been possible for him to admire the immortal masterpieces which he had only known in the past from photographs. Eva’s silver cudery and sculptures and so forth in the bunker rooms and got the SS-Begleit^ommando men to load them on the lorry.so much for discipline! The lorry eventually arrived at Altaussee near Salzburg. The SS men were not slow to explain all the difficulties involved . nature and science had first found expression. which were difficult to carry down the snowy southern slope now that the stairway to the road was unusable. There were some very large paintings.1944. I collected the most valuable pieces of artwork. sculptures and artistic handicrafts. together with furniture. during the Second World War director-general of the Austrian salt mines and charged with the safekeeping of art treasures. but also very important works by Dutch. to Fischhorn. He shared my opinion that it would be unforgivable and called up the lorry next morning to remove the paintings etc. Hitler considered Greece and Rome to have been the cradle of culture. Dr Emmerich Pochmiiller. mainly paintings by nineteenthcentury German artists. I mentioned that they were going to destroy all the paintings.HE WAS MY CHIEF It came about thus. I told him the story and expressed my disquiet. It was there that the concepts of cosmos. That same evening Fegelein’s adjutant Hannes Gohler6 suddenly appeared. including a Bordone and a Tintoretto. He rejected Italian modernism. spirit. He found it too closely related to Impressionism and 6 Johannes Gohler.12.
The money came from the socalled Postage Stamp Fund devised by post minister Ohnesorge. The journal of art purchases was kept by Schaub under lock and key although I made the entries in it. with a hall for each individual century. He left Goring to look out for Early and Late Gothic. and his birthdays. The Linz museum was one of his favourite conversation pieces at evening tea.his own term —was in his opinion the work of the Jews. as he said . ‘can never give the same attention to detail.‘touching each other’. Art dealers knew that Hitler was not interested in anything up to and including the fourteenth century. His admiration was focused on the Baroque and its creations in Dresden 193 . nor have the patience.’ Here he meant the Antique and Romantic epochs: he rejected the Renaissance because it was too closely associated with the cult of Christianity. art exhibitions. This ‘artless art’ . as those of the great art epochs. he said.and the individual halls would have furniture of the period. even those he did not like.THE END AT THE BERGHOF Expressionism. Hitler’s plans with regard to building art galleries were farreaching. Hitler had a true passion for architecture. They had made a great hoo-ha about this garbage so as to bump up the price while keeping for themselves only old masters. Hider’s passion for Linz was extraordinary. He had also planned a huge museum for the city. Linz would have the finest one. the annexations of Austria and the Sudetenland. He did not think much of most contemporary German artists although he did frequently buy their works. in order to give them some encouragement. He had litde feeling for the Romanesque style and rejected Gothic out of hand because it was contaminated with Christian mysticism. Every town should have a small picture gallery. ‘Our modern artists’. He had read a great deal of specialist literature and knew all epochs in great detail. All paintings obtained by Hider through art dealers were paid for above board. The paintings would not be crowded together as they are at the Louvre . Every stamp bearing Hitler’s image brought him a small royalty. especially special stamps with his head commemorating a Nuremberg rally.
In his opinion the architecture of Paris and Budapest towered over all other capital cities. If he returned from a taxing situation conference exhausted.HE WAS MY CHIEF and Wurzburg. that every historic building is to be photographed in colour inside and out: and it is to be done so thoroughly that future architects and artists will have exact files to work from. unexpected vitality even when he was spent physically. In 194 . although the true creator of the neo-Greek Classic style had been Professor Troost. Hitler’s knowledge of architecture was astounding. Hitler laid a wreath on his grave at each anniversary. He had worked out a gigantic programme for the reconstruction of cities destroyed by war and for artistic monuments. I have seen architects and engineers of renown staggered by his ability and imagination. Even in the war he could always find time to debate architecture and art. Whenever he declared: ‘I will make Berlin into the finest city in the world!’ he would straighten up... And colour photographs make that possible! In his enthusiasm for his own ideas he co-opted architects for talks. for the culturally irreplaceable heritage of earlier times must be rebuilt. Hitler’s plans for postwar Berlin and Hamburg were simply immense. he would quickly find reserves of energy if a technical person invited him to look over new building plans and models. He would sketch out for them what he had in mind. and rebuilt so true to the original as only people can. He took pride in his order: . He knew by heart the measurements and ground plans of all important buildings in the world. It is superfluous to mention his enthusiasm for the new German style. for he himself had been the force behind it. During the war he said more than once: ‘that it would be his happiest day when he could cast off his uniform and devote himself to matters of art’. After the architect’s death. and his voice and gestures dispelled all doubts. The idea of rebuilding Germany lent Hitler new.
the only possibility open to me to get away from the Berghof was to go with the lorry taking the paintings to Schiffhorn in Austria. I turned down the offer by August Korbers of the SS-Begleitkpmmando to join his men in their attempt to find the German troops still resisting. Hitler would often stand before this model and tell people (I remember particularly Dr Ley and Kaltenbrunner) how he would rebuild Linz. but for understandable reasons she failed to return. all in white and gold. No vehicles were available and it had started to snow again. Upon receipt I destroyed everything bearing my true name. 195 . I waited daily for Johanna Wolf. had camped in the bunker. I even threw out my leather jewellery box with my initials ‘C. But what should I do amongst fighting troops? I could not contact anybody for help or advice.THE END AT THE BERGHOF February 1945 Professor Hermann Giesler brought the great model of Linz to the Reich Chancellery cellars.S. The two SS men from the Berlin Hauptamt brought false identity papers for Johanna Wolf and myself. Erd. When news came through that the American armoured spearhead was already at Chiemsee. boozing and smoking. even the telephone lines to Hintersee were down. The next time I saw her was in internment. It was not much. probably attached to the police squad. The SS-Begleitkpmmando wanted to drive to Linz to link up with Sepp Dietrich who was carrying on the war more or less by himself They made spasmodic attempts to obtain fuel for the journey and ammunition. He also planned for the city a round porcelain hall. but they always kept us separated there. must have noticed my misery. an old police officer. for I had lost my papers with the trunk in the Bornersdorf air crash. It required real athleticism to reach the road over the ruined stairway. A thick layer of snow had settled over the damaged road. I cast a despairing last look at the ruin of the Berghof. Some odd types I had never seen before. The house staff gradually left the bunker one after another. Any trace of discipline had long gone. Since I was still undecided as to my future they urged me to join them.’ so unthinking had I become.
for he had not reckoned it would end like this. for he was a soft and sensitive man. with her sister Frau Linge.HE WAS MY CHIEF for he attempted to console me as I climbed into the lorry. He said only that he could not carry on his life with his surname. now made it plain that he was extremely displeased to see me and said: ‘What. wife of Admiral Donitz. wife of the naval adjutant. a remarkable community had developed. Augst. the employee in Albert Bormann’s Chancellery responsible for arranging lodgings in the Pension Post. Along with Frau von Puttkamer. With a look of disgust he pointed to the botde of champagne on the table and said: ‘That is responsible for much!’ He was deflated as I was. He was a reformer and if not actually anti-alcohol then at least a strict moderate. quiet and pleasant. Hitler’s dentist. Schaub and he then disappeared quickly. leaving me alone. now you are coming along too? There are no more single rooms. Upon my arrival I found them both celebrating their escape with champagne. scrupulous. and children. all that has stopped!’ Here too the sudden change in attitude and tone. Professor Blaschke. Frau Donitz. a dancer from the Berlin ‘Metropol’ and Erich Kempka’s ex-wife. and I knew they were staying at Pension Post. During the drive I realised that the time for weighing up the possibilities was now past. It also included Schaub’s female friend Hilde Marzelewski. whom he had divorced on Hider’s orders for her having been a prostitute before the marriage. Seeing that Schaub and Albert Bormann were only interested in their own futures and on getting away from Hintersee at the earliest opportunity. I had to decide either to keep going for Austria or get out at Hintersee. and who in earlier timers had been very friendly and forthcoming. wife of Hider’s manservant. was with them.’ This hurt Albert Bormann and upset him very much. I remonstrated furiously: ‘It is a scandal for you to look after yourselves and leave us to our fate. I decided for the latter. Kempka had rented for her an apartment on the Kurfurstendamm and subsequently 196 . a slim man. As I was still hoping for advice from Schaub and Albert Bormann. her children and mother.
who was then arrested at Hintersee on 18 June 1945. but failed to look under the bed where I had stowed the trunks I packed at the Berghof. Our daily fare was mushy peas. the food suddenly vanished. there was a knock on my door. who made it unmistakeably plain every day that he wanted us all gone. thus leaving something for the Americans to loot later. Food grew increasingly scarce and none was on sale at Hintersee. The former was hiding out in the Berchtesgaden area under the name Roth. They also relieved our baggage of two small radios. Although the hotelier had been paid to place the establishment at our disposal and supply food. They were a thorn in the side of the new hotelier. They rummaged around. and in due course she had filtered down to Pension Post at Hintersee.7 7 From the CIC report it would appear that the informant was another guest. A CIC man said he was looking for Albert Bormann and Fraulein Fusser. We had heard that Gaullists and negroes were looting and robbing in the Berchtesgaden area. Next morning. Meanwhile the Americans had arrived at Berchtesgaden and the Pension Post had been evacuated to house a company of US troops. alcohol and cigarettes. The atmosphere became daily more threatening and worrisome. There was always an excited situation whenever one of the SS-Begleitkpmmando leaders appeared from hiding in the mountain refuges. No explanation was forthcoming although the hotelier had definitely had it in his possession. At Hintersee we all crowded together in the smaller annexe. 197 . Then he asked: And who are you?’ Undoubtedly the hotelier had already told him. This they knew. My stay became daily more unpleasant. One day two armed Gaullists burst into our room.THE END AT THE BERGHOF remained in touch with her. It gave me a nasty feeling of apprehension. The person also informed the Americans about Erich Kempka. opened all drawers without a word and finally decided on two small paintings I had brought from the Berghof and hung on the wall. She was responsible for causing some very unpleasant scenes there. 22 May 1945 towards 0700.
’ After my first interrogation by Mr Albrecht. But at least you talk naturally. and had married one of the SS-Begleitkpmmando officers). At that time it was not permitted to stray further than six kilometres. with whom I shared a room (she had been secretary to Hauptmann Wiedemann. If we were to be persuaded into ‘collaborating’ I wanted to find a room for us both in Berchtesgaden to get away from the awful conditions at Hintersee. removing all the contents. I became enraged. short letters accompanying a gift of bacon from Hider to his sisters. 8 Lt Erich Albrecht was a German who had once worked at the Reich Ministry of Economics. He had emigrated to the United States as a Mormon. Ilse suggested we could buy a horse and cart and head for Luneburg Heath where her in-laws lived. at which the officer told me: ‘You will have to get used to that kind of thing.HE WAS MY CHIEF That same afternoon another CIC officer came for me. amongst them the well-known Jack Fleischer. but nothing came of it. At the CIC offices in Berchtesgaden some of the former FH Q stenotyists were transcribing my shorthand notebooks. It was a nice plan. Following the interrogations I made plans for the future with Ilse Lindhoff. but after a few days journalists from the periodicals Time and Life showed up.8 this officer told me in good German: 4You are a wanted person. The material was innocuous. Hider’s former adjutant. He had advised them: ‘under no circumstances to eat the bacon raw!’ I realised that years of internment might now lie ahead. I shall consider whether to spare you or tell the fourteen journalists in the next room about you. On 28 May 1945 I was bundled into a jeep by two American soldiers together with my two cases and an Erica typewriter.’ That day he still felt sympathy for me. When his female assistant went through my handbag. whereas the Gauleiters and ministers captured to date speak in newspaper phraseology. 198 .
Therefore Hider never invited officers with whom he had to work. He would take breakfast. tea used to finish sometime between five and seven in the morning. Fraulein Wolf was with him from 1929. Hider used these sessions to relax. Charles Patterson Van Pelt Library. Mr Albrecht: At these conferences would Hitler make decisions about air defence? Schroeder: In the presence of Herr Schaub he would probably just grumble. At the end in Berlin we would get to bed around eight in the morning. Then he would go to bed if he didn’t have reports to read. Mr Albrecht: In the last years of the war what was an average workday? Schroeder: We had no set hours. Hider was not satisfied 199 . He often used to say that ‘in his mind’s eye he could only see maps’. I was available permanendy for him from 1933. Politics was not discussed at tea. either Dr Morell or another one .) Mr Albrecht: When did your employment with Hitler begin? Schroeder. This was composed of his female secretaries. an officer of the US Counter-Intelligence Corps.Appendix The following is an extract from the interrogation protocol of Fraulein Schroeder held at Berchtesgaden on 22 May 1945 and conducted by Erich Albrecht. He wanted to get his mind off the battle maps. It was really the opposite of normal. US Army 101st Airborne Division. Hider never gave Schaub instructions because he was not part of the military. for otherwise the conversation would always come round to military business.at the end Dr Morell did not attend because his health was not up to it . A Fraulein Daranowski came additionally in 1938. After the night conference Hitler would always take tea with his intimate circle. Basically we sat up all night. Earlier on. (The original version can be seen on microfilm at the University of Pennsylvania. He did not sleep much. 46M-11FU. then Herr Schaub would come with the air raid reports and inform him which officers had been told to attend the conferences. Frau Christian. We would start off with the situadon conferences which were held at night. usually Gruppenfuhrer Albert Bormann. Fraulein Wolf. Hider was very much a night person and generally did not start work until the evening. We were always on call.plus a personal adjutant. Previous to that I worked for him when needed. Hider would usually get up at eleven. Frau Junge then a doctor.
Mr Albrecht: There was no general rebuilding plan? Schroeden No. Professor Morell was very interested in hormone research. Hider was also interested in nutrition. Mr Albrecht: Did Hider dictate .APPENDIX with the handling of air defence. the German language. but it was not being used. He thought there was still a lot to be done in this field. Mr Albrecht: Apart from letters of thanks and so on did Hider have personal correspondence with friends? Schroeder: No. He had the feeling that it was not being done properly. even in the early days. that was mosdy done by the Wehrmacht. he always emphasised that that was his great strength. music. Mr Albrecht: Racial questions belonged in the political arena? Schroeden Occasionally the subject was touched upon. Hider composed all his own speeches. I never gave it much thought 200 . Mr Albrecht: You were present at mealtimes? Schroeden Towards the end only at lunch and the teas at night. He had a very good style and would keep putting finishing touches to them to the last moment. about things to be done in the future. Mr Albrecht: Did anyone else go over them? Schroeder: No. Towards the end he didn’t dictate letters. that we had the means. Medical matters were also talked about at lunch. People talked about architecture. This subject also interested Hitler. He used to say: ‘I wouldn’t have Schaub if there was another chief adjutant. In the end Speer would have taken it over because it was his province. Mr Albrecht: Was rebuilding the cities discussed? Schroeden Yes. theatre. Mr Albrecht: What things were discussed at lunch? Schroeden They were not of a political nature. Mr Albrecht: Whose job would that have been? Schroeden Professor Frick had already started on it. Mr Albrecht: Even Goebbels had no influence on the contents? Schroeden No. Mr Albrecht: Hider would not give Schaub orders? Schroeden No. there would have been no point.orders personally to the front troops? Schroeden No.’ Mr Albrecht: When did Hider deal with his personal correspondence? Did he dictate his letters personally? Schroeder: Only letters of thanks or congratulations. to have written no letters: if they had fallen into the wrong hands they could have been exploited. Mr Albrecht: Did he edit them afterwards? Schroeden He used to correct them himself a lot. about his plans. Mr Albrecht: What was your main job as secretary? Schroeden Early on Hider used to dictate his big speeches for me to type directly into the machine. he just provided statistics if they were called for. Schaub was an old factotum and Hider did not esteem him gready. Professor Giesler was to complete it.
In the end he ran a Customs office and got himself a property. He worked his own way up. she is very delicate. Mr Albrecht: Was Fraulein (Eva) Braun present at these mealtimes? Schroeder: Fraulein Braun was only in Berlin towards the end. Mr Albrecht: At the nighdy tea was Hider a lively talker? Schroeder: Yes. A lot of what was said is untrue. widow of Raubal. Mr Albrecht: There were no children? Schroeder: No.APPENDIX because the theory has a lot of holes in it. on principle. first of all he didn’t have any real siblings. I often told Hider that. He had no sense of family. Usually Reichsleiter Bormann would report after the meal. She attended occasionally. Many women have deceived their husbands. Mr Albrecht: What type of relationship was there between Hider and Renate Muller? Schroeder: There was none. I took more interest in his life than his family. But he had no personal relationship with Renate Muller. Mr Albrecht: Did Hider talk about his childhood? Schroeder: I made lots of notes about that. His full sister was Paula Hitler who lived in Vienna. He admitted it himself Hider had two sisters. Mr Albrecht: Could one debate freely with Hider? Schroeder: Yes. Mr Albrecht: Did Hider have no personal correspondence? Schroeder: No. His father married three times. I said so. Fraulein Braun is not very healthy. Mr Albrecht: Did Hitler look on her as his wife? Schroeder: He treated her that way. the secretaries attended. Leni Riefenstahl was mentioned once. Mr Albrecht: When was the last tea? Schroeder: On the night of 19 April 1945. Lunch was often taken around four or five in the afternoon. When we were at FHQ. Mr Albrecht: He looked on her as such? Schroeder: Yes. Mr Albrecht: What was the reason for his having such a poor family relationship? Schroeder: Well. Some years ago I read something about that in an American paper. Mr Albrecht: Was Hider very depressed in the final days? 201 . There is a kind of woman who does not refute rumours like that. Supper was around nine or ten. married Professor Hammitzsch in Dresden. I knew where my limits lay. The Berlin climate did not suit her. Hider thought she was a good actress because she looked the part of the perfect German maiden. The father grew up an orphan. she used it for her own purposes. but very delicate and tired. Mr Albrecht: Was she ill? Schroeder: Not actually ill. in Berlin only Fraulein Braun did. He learned the craft of shoemaker in Austria then went to school in the city. His half-sister Angela Hitler. up to a point. I left them in my luggage at the Reich Chancellery in Berlin. Towards the end Hider would not spend even half an hour at the meal table. He wrote a short letter to his sister when he sent her some bacon he had received as a gift from Spain. Leni Riefenstahl was that kind of woman.
APPENDIX
Schroeder: The final days were from the beginning of April, I would say.
Mr Albrecht: In September 1944 he was laid up a long while in bed!
Schroeder: That was as a result of the attempt on his life on 20 July 1944. All the officers
present suffered severe concussion and ear injuries. Hider was the only one not confined to
bed. At that time I used to dine with him alone. He was very depressed in the days leading
up to 20 July 1944. He had a premonition, he felt that an attempt was being planned on his
life. He even told me once and in these words: ‘I note there is something afoot.’ On the day
before he did not feel all that good. When I was dining with him alone he said: ‘Nothing
must happen to me now, for then there would be nobody there to take over the leadership.’
Mr Albrecht: Whom was Hitler considering as his successor?
Schroeder: Not Goring or Himmler. After Hess went, Goring was automatically next. But
Hider didn’t think he was capable. Once I argued with him when he told me he had no
successor. He said that the first one, Hess, had gone mad. The second, Goring, had lost
the confidence of the people, and the Party did not want the third, Himmler. When I told
him that Himmler was being mentioned a lot amongst the people he got very upset. He
said that Himmler had no ear for music. When I protested that in these times it was not
so important, able people could be drafted in to handle the area of the arts, Hider would
not have it. He said it was not so easy to get capable people, otherwise he would have done
so. From that I inferred that in Hider’s view none of those envisaged could be considered
his successor
Mr Albrecht: Which other people came under consideration?
Schroeder: Nobody. He got very indignant at my assertion that Himmler’s name was being
bandied a lot amongst the common people. He said - something out of character for him
- ‘whatever possessed you to say something like that?’ It hurt his pride that we who knew
him and Himmler should put him on a par with Himmler. He went out that midday
offended and said: ‘Keep people busy thinking about who my successor should be.’ On
20 July 1944 I did not expect to be invited to dine after the attempt. To my surprise I was
sent for at 1500 hours. I was amazed at how fresh and lively Hider looked when he came
up to me. He told me how his manservants had reacted to the attempt. Linge had raged,
Arndt had wept. Then he said, ‘Believe me, this is the turning point for Germany, now it
will be all downhill again: I am pleased that the filthy swine have unmasked themselves.’
On 20 July 19441 told him that he could not possibly receive the Duce. He replied: ‘On the
contrary, I must receive him, for what would the world press write if I didn’t?’ Shortly after
lunch he left the camp to greet Mussolini. Finally at the end of September 1944 Hider had
to confine himself to bed on account of the bomb plot of 20 July 1944.
202
Index
Adlerhorst (FH Q ), 125
Aga Khan, 168-9
Ahrens, Karl, 84
Albrecht, Alwin-Broder, 37, 185
Albrecht, Erich, xvii, 198
Alexandria, 10
Alkonic, Lav, xxix-xxx, 84
Altaussee, 192
Amann, Max, 44, 134
Anders, Peter, 101
Antonescu, Ion, 56, 119
Arden, Elizabeth, 60
Ardennes, 125
Arent, Benno von, 82
Arndt, Wilhelm, 122, 180n
Augsburg, xxi
Augst (Chancellery employee), 196
Austria, 1 7 Anschluss, 61-2, 70, 137,193
188, 190, 191; conversion o f Haus Wachenfeld,
143, 153-5; destruction o f documents, 22, 108,
109, 129,186, 189,190; diningroom, 155-8; Eva
Braun’s rooms, 143,153; Eva Braun’s status,
93,144,171; food preparation, 120; Geli
Raubal’s room, 132; Great Hall, 152, 153-5, 162,
163-9; Hider dictates speeches, 57-8; H ider’s art
collection, 191,192-3; Hider’s rooms, 153,162;
Hitler’s secretaries, 72; the Kannenbergs, 34-5;
looting, 190; manservants, 24; meals, 155-8,
160,162; morning silence, 171; as north-facing,
50; prominent visitors, 168-70; in ruins, 195-6;
Sophie Stork as frequent visitor, 15; surrounded
by armed SS, 186-7; terrace, 155, 168,171, 189;
see also Obersalzberg
Berlin: Alois Hider’s restaurant, 42; Congress Hall,
68-9; Deutsche Oper, 136, 138; entertaining
actresses and dancers, 132; Eva Braun’s
apartment, 38; Hitler unable to shop, 38; H ider’s
birthday, 68-70; Hider’s postwar plans, 194; H Q
moved to, 125; RAF bombing, 98; Reichstag, 56,
69,80; Russian gunfire, 176, 179; Staaken airfield,
76,179,180; Tempelhof airport, 179
Berlin, Fuhrer-bunker (FH Q ): and air raids, 125,
175; entrance to, 185; Eva Braun and H ider’s
death, 146, 190; Manziarly as cook, 121; meals,
174,175; secretaries’ departure, 176-7
Berlin, Reich Chancellery: Bruckner’s office,
14-17,23; dining area, 29; Eva Braun moves
in, 145-6; Hacha meeting, 64; Hitler’s flat, 19;
Hitler’s study, 25; length o f hall, 48; meals, 184-5;
Radziwill Palace, xx, 13n, 19, 25,29,32, 37-9,49,
68,130, 137, 173, 179; receptions, 53; Schroeder’s
apartment, 137—8; secretaries at, 18; situation
conferences, 125
Bircher-Benner, Maximilian, 119, 121,157
Bischofswiesen, 119,120
Bismarck, Otto von, 19,25, 55
Bad Gastein, 118,119
Bad Godesberg, 10, 27, 28
Bad Nauheim, 125, 143
Bad Wiessee, 27,28-9
Baden-Baden,14
Bahls, Ernst, 75n
Baur, Hans, 167n
Bayreuth, 42,165
Bechstein, Carl, 147
Bechstein, Frau, 148
Beer Hall putsch, 10,20,47-8
Beethoven, Ludwig von, 105, 165
Belgium, 78, 81,90
Below, Maria von, 94
Below, Nicolaus von, xxiii, 94,179
Benrath, Karl, 109
Berchtesgaden, 16,41,42,45, 131, 149,152, 190, 197
Berghof (FH Q ): Allied bombing, 187-8; as alpine
redoubt, 181; art collection, 108; bunkers, 172,
203
INDEX
Blaschke, D r Hugo, 150,196
Bliithgen (Berghof cook), 190
Bolivia, 4
Bordone, Paris, 164,192
Bormann, Albert, 18-19,118,186,189-90,191,
196,197
Bormann, Martin: character and career, 6-10;
constructs Kehlstein, 160; converts Berghof) 143;
a dog for von Exner, 119-20; estranged from his
brother, 18-19; farm on the Obersalzberg, 156,
160,190; and Hess’s flight, 11,167ri; and H ider’s
table talks, 91,93; Hoffmann order, 108; meals at
the Berghofj 155, 156; music at the Beighofj 165;
orders silence at the Berghof 171; relationship
with Hider, 8-10, 20; Schroeder’s departure from
Fuhrer-bunker, 177; his secretary, 180n
Bornersdorf, 180
Boulogne, 82
Brahms, Johannes, 165
Brandt, Anni (‘Rehlein’), xix-xx, 1^2,150-1,184
Brandt, D r Karl, xix-xx, 60,74,100,116,150-1,178,
181,184,185,186,191
Brauchitsch, e i t h e r von, 102n
Braun, Eva: arranges film shows, 162; aversion to
Goring, 142; Berlin apartment, 38; character,
143-4; death, 146; her dogs, 106,144,190; and
Fegelein, 144-6; H ider’s compliments, 50; as
Hider’s eyes, 55; letter to her sister, 188; meals at
the Berghof 155, 156, 157; on the Obersalzberg,
150; reladonship with Hider, 11,93, 116,133,
140-6,158-9,166-7; rooms at the Berghofj 143,
153; and Sigrid von Laffert, 47; Sophie Stork’s
coffee service, 16; status at the Berghofj 93, 144,
171; suicide attempts, 133,141,142; works for
Hoffmann, 140
Braun, Franziska, 181
Braun, Margarete (‘Greta’), 117,120n, 145,162,
171n, 181,188
Bruckmann, Frau, 45,154
Bruckner, Anton, 165
Bruckner, Wilhelm (‘Owambo’): on breakfast, 37;
describes Schroeder, xxv-xxvi; as disoiganised,
22,23; road accident, 151; sacked by Hider, 21,
35; Schroeder works for, 14,16-17,19,22,27;
Schroeder’s fondness for, 84,85; snores at opera,
166; visits Schroeder in hospital, 60
Bruly de Pesche (FH Q ), 78-81,82
Brussels, 81
Buch, Gerda, 7
Buch, Walter, 7
Budapest, 194
Btigge, Fraulein, 18
Crimea, 99
Czechoslovakia, 64-5,178
Dachs, Frau, 128
Danzig, 51
Daranowski, Gerda (‘Dara’), xxii, 38,60-4, 66,69,
72, 74,76,80,81, 83,88,92,96,97, 102,118,125,
169,177,183
Darges, Friedrich, 120n, 145
Defregger, Franz von, 70
Degano, Alois, 153
Died, Eduard, 103
Dietrich, Otto, 2 7 ,3 7 ,77n, 150,161
Dietrich, Sepp, 24,37,103,195
Dirksen, Viktoria von, 47
Doberitz, 7
Dohring, Herr and Frau, 144
Donitz, Frau, 196
Doose, Heinrich, 189n
Dresden, 194
Drexler, Anton, 139
Dunaburg, 95
Dunkirk, 81,82
Eckart, Dietrich, 18, 42-3, 85,147-8
Endres, Frau, 144,156
Engel, Gerhard, 89,94
England, 23
Epps sisters, 135
Ertl (Berghof police officer), 196
Essen, 27
Esser, Hermann, 147
Exner, Helene Maria (‘Marlene’) von, 118-20
Fegelein, Hermann, 144-6
Fegelein, Margarete, see Braun, Margarete
Felsennest (FH Q ), 77-8
Feuerbach, Anselm, 164
Fick, Roderich, 159
Fiehler, Karl, 52-3n
First World War, 4,7 ,1 0 ,1 6 ,2 0 ,4 4 , 53,81,126,135
Fleischner, Jack, 198
Florence, 63
Forster, Albert, 51
France, 30,62,75,78-83,90, 197
Frederick I (‘Barbarossa’), Emperor, 149
Frederick II (‘the Great’), King o f Prussia, 174
Frentz, Walter, xv, 81
Frey, Herta, 17,18
Frick, Wilhelm, 65
Frobenius, Fraulein, 18
Funk, Walter, 11
Fiirtheimer (imaginary Jew), xxv, 12
Fusser, Fraulein, 197
Calais, 82
Chiemsee, 195
China, 23
Christian, Gerda, see Daranowski, Gerda
Churchill, Winston, 5 5 ,167n
Gahr, Otto, 82
Gandhi, Mahatma, 168
Garmisch, 188
204
INDEX
George, Heinrich, 71
Gesche, Bruno, 28
Giesing, Dr Erwin, 183-4
Giesler, Hermann, 53,195
Goebbels, Josef: diatribe against von Schirach,
171; marriage to Magda, 16; recommends
Kannenbergs to Hider, 32; retort to Otto Dietrich,
161; Rohm putsch, 27, 29
Goebbels, Magda, 16, 56, 118, 133
Gogolin, 73
Gohler, Hannes, 192
Goncharov, Ivan, xviii
Goring, Emmy, 56, 142
Goring, Hermann: arrested, 187; his corpulence,
and Hitler, 160; Eva Braun’s aversion to, 142;
Gerdy Troost’s designs for, 154; Hitler on Hess’s
flight, 167n; H ider’s art collection, 193; house
on the Obersalzberg, 186; road accident, 151;
succession to Hitler, 185
Graffj Anton, 174n
Great Britain, 11, 75, 80,98-9, 106, 167-8, 187n
Giinsche, Otto, 93
Gunther, Otto (‘Kriimel’), 94-5
Beer Hall putsch, 10-11; his birthday, 68-70,
143, 160n; book on foreign policy, 168; and
Bormann, 8-10; Bruckner as adjutant, 15,16,21,
23; centralises SA, 2-3; childhood reminiscences,
38-40; conversion o f Haus Wachenfeld, 153-5;
daily routine, 25-6; his danger perceived, 5;
denigrates army officers, 124; his dictation, xx,
31, 55-8,63, 81,117-18,167; dieting, 160; and
dogs, 105-6, 119, 159,162, 174, 175, 176; dress,
47-8,49-50, 158-9, 161; and Eckart, 18,42-3,
147-8; entertains actresses and dancers, 21,132-3;
and Eva Braun, 11,93,116, 133,140-6,158-9,
166-7; exercise, 50-1; and fame, 43, 61; family
reminiscences, 38-9,40-2, 158; his first love,
18, 126; first visits Obersalzberg, 147; flatters his
secretaries, 60, 63,66; and foreign languages, 54;
gastro-intestinal disorder, 119-20, 124,182-4;
and Geli Raubal, 128-32,133, 140, 141, 152, 157,
189; giving presents, 34-5, 132, 150; and Great
Britain, 80, 81, 167-8; and Gred Slezak, 136-9,
166; Hamsun visit, 169-70; H ess’s flight, 167,
168; and Hoffmann, 1,107-9,131, 182; hormone
injections, 183; household, 31-7; hygiene, 50;
image on stamps, 193; imprisoned at Landsberg,
20,42,45, 52, 150; invasion o f Poland, 73-5;
and Jews, 93, 136,170; on Japan, 106-7; Lloyd
George visit, 169; love o f architecture, 81,93,
107, 109, 189, 193-5; love o f music, 101,105,
165—6, 185; love o f scenery, 78, 159; manservants,
23—4,35, 174; on marriage, 132; meals, 37—8, 66,
88, 102, 121, 155-8, 160,162, 174, 175, 184-5;
meeting with Hacha, 64; Mein Kampf\ 45, 150; his
memory, 53; as a mimic, 44, 58; missing testicle,
127; and money, 44-5,49; orders Fegelein’s
execution, 146; paintings and sketches, 108-9,
138-9, 189; passion for Linz, 93,192,193, 195;
physicians, 181-6; powers o f suggestion, 51;
Prague visit, 65; premonition o f 20 July, 121, 122;
reading, 52, 54; receives Hindenburg, 19; on
religion, 45-6, 71-2, 96; Rohm putsch, 27-30;
on Russia, 88-9,100; and Schaub, 20-22, 25-6,
31; on Schroeder’s fiance, xxix; his second-hand
knowledge, 54-5; and secrecy, xix, 59,161;
self-mastery, 51-2, 70, 160; sense o f humour,
44, 77,87-8, 116,158,161, 162-3; and sexual
gratification, 126, 127; signs Bulgarian Pact, 83;
situation conferences, xx, xxii-xxiii, 76,87, 89,90,
102, 121-2, 125, 145, 163, 164, 174, 175-6, 186;
and smoking, 20,39-40,116-17,119,154; and
society ladies, 46-7,49-50; his spectacles, 56, 57;
speeches, 56,57-8,69, 80-1,123,138,176; on
Speer, 107; starts Western offensive, 77; state visit
to Italy, 62-3; Stauffenberg bomb, 121-3; on his
successor, 10, 185—6; suicide, 146, 190; and the
sun, 50, 66; as supreme army commander, 102;
as supreme SA-Fiihrer, 3; table talks, 45,91-4,
105-7,158,174-5; his train, 65— 7, 70,73-4,
76-7, 8 2 ,99n; vegetarianism, 131,157-8,169;
Haase, Dr Werner, 151, 181
Haberstock, Karl, 32
Haberstock, Magdalene, 32, 34
Hacha, Emil, 64
Hamburg, 10, 59
Hammitzsch, Martin, 143
Hamsun, Knut, 169-70
Hanesse, Friedrich-Carl, xxx, 83
Hannoversch Munden, xxiv
Hasselbach, D r Hans Karl von, 127n, 151, 181,
184,185
Haushofer, Karl, 11
Heidelberg, 126
Heim, Heinrich, 91,92, 148
Hess, Rudolf: Bormann as his chief o f staf£ 8;
flight to Britain, 11, 167, 168, 185; heads NSDAP
Liaison Staff, 13; Hitler dictates Mein Kampf, 45;
Hitler on, 10,168; introduces Schroeder to Hider,
17; his secretaries, 18; state visit to Italy, 62
Heston, Leonard L. and Renate, 183
Hewel, Walther, 145
Himmler, Heinrich: on atrocities in Poland, xxii;
Hitler’s verbal orders to, 25; report on military
resistance, 124; SS inveigled into police, 30; and
succession to Hider, 185-6
Hindenburg, Paul von, 19,43
Hintersee, xvii, xxvii, 190,195,196-7
Hider, Adolf: and Ada Klein, 134-5, 157,162-3;
Aga Khan visit, 168-9; and alcohol, 20,39-40, 65,
108, 117,152,156, 169; Anschluss, 61-2, 70, 137,
193; alleged illegitimate son, 126,135; anxieties as
host, 33; his appearance, 48-9; appoints Wagener
head o f SA, 4; and Arent, 82; art collection, 191,
192-3; and atrocities, xxii; aversion to clergy, 39;
205
Alfred. Sigrid von. 133 Junge.37 Landsberg am Lech. xx. 12 Laffert.34-5. 122-3. Emilie. Johanna. xxix. 154 Miesbach. 140-1. Werner. Ernst. 150 Leipa. 77. 52.122. Gertraud (‘Traudl’). Charlotte. 18.32. 64—5 Lenbach. 119. 83. 13.123 Kempka. 136. 196-7 Kielleutner. 169 Marzelewski. 107-8. 61-2 Inonii.31-6. Unity.49. 95n.46.63—4 . 43.29. 11-12.144.128. Joseph. 47.93. 46-7. 50 Kroiss. xxx Neumarkt. 195 Kovno. 136. Charles. Hider on. 42 Hider. 52-3. I57. Jean-Marie.81. 108.95 Muller. 42-5. 1. 149 Niederlindenwiese.164 Nagold. David. 150 Hoffmann.196 Maser. Artur. 131. 23. Ilsa. 169 Lobjoies. rallies. 11. Heinrich: after Geli Raubal’s suicide. 160. Zoller’s interrogation. William Patrick. 127 Maulbrunn. 90 Krause. 117 Kaltenbrunner. xxiv Neuhausen. 37. 120n. 49.170 Jochmann. 142.139. 189.45. trials. 142 Morell.124. walks. Jenny. 195 Kannenberg. Martin. Robert. Hans. 88 Morell. Frau. 45 Klein. see Felsennest (FH Q ) Mussolini.135 Lorenz. 101 Ley. 184 Lindau. 107-8. 69 206 .151-2. Em a. 2 3 . 75. Werner. Dr Theodor. Paula.132 Lambach.144. 43 Lammers. David. Wilhelm. xxvi. on the Obersalzberg. 70 Leningrad. 19. Emil. refounding .93.150 May. 2 Lloyd Geoige. 92-3 Junge.192. 168 Innitzer. 60. 71.84 Nuremberg. 56. Herr.181 Kannenberg.23. watches films. 133 Horthy de Nagybanya. see Raubal. xxxi. xxv. Angela. 131. Erich.see also Beer Hall putsch Munstereifel. on winning the war. 48. 33. Constanze.45 Linde. 150. August.89.117. Hans. 91 Jodi. 16. 158-60. years o f struggle. 196 Linge.196-7 Kempka. introduces Morell to Hider. Hider meets Eva Braun. ofN SD A E 134.127. 127-8. 125.134. 134-5. 20. Hider and its architecture. xxviii Maurice. 83. 24. 147 Lindhoff. 76n Loret. 155.162.195 Lithuania. Klara. Ismet.53 Hider. 162-3 Kohler. 42 Hoffmann.20.122. 95 Mitford.99n. 42 India. xxxi. xxvii. Nikolaus. 106-7 Jews. Frau.195 Liebenzell. xxiii. Benito. 133 Mittelstrasser. scurrilous films. 62 Japan.135 Ludwigsburg. xxiii. 1-2.12 Korbers.165-6. NSDAP H Q . Carl Gustav Emil. 185. Professor.190 Molotov-Ribbentrop Pact. 40 Mayer.14. 131-2. 27-9.133. 140.123 Jugo.90. 17 Hopfner sisters. Alois (Hider’s father). Adelheid (‘A da’. 46. Gartner-Platz theatre. 31.25. ‘Deli’). 12-13.32. Karl. Heinz.183. Bernhard. 186 Luther. 119. as smoker and drinker. xxxi. on Hider and Eva Braun. Rohm putsch. 106. 56 Ley. Theodor. Johanna. Franz von. 56 Manziarly. 40-1 Hider. 154. Angela Hider.110. 40-1 Hider. Karl von. xix. Heinz. Freda. 169.132.193. Franz von. theatre in. photographs Hider’s hands. 50. 133.184 Linz.77n Nusser. Herr and Frau. 139. 77. Alois (Hider’s half-brother). 22-3. Karl. Hilde.42. 144. xxi Holsken. 188 Minsk.69 Italy. 163. 182. 127 Kirdorfj Emil. 198 Linge. looks around Moscow.17. xxviii. 126. 56 Ibsen. Wiedemann as adjutant.120-1 Martel. Thierschstrasse flat.181-4. 44 Munich: death o f Geli Raubal. Adolf.128. Henrik. 71 Mannerheim. Herr.154. 61. 56 Irving. 147 Meyer.193.157.186 Moscow. 128. Mauritia (‘Moritz’). 42 Neumayer (architect).INDEX visits Schroeder in hospital.181 Keitel. 126. 41-2 Hider. arguments with Schaub. 55. 23—4. Hoffmann’s villa.
98-9.134. 133 Quandt. 193. destroys documents at the Berghof. 6 Schloss Fischhorn. Arthur. 148 Rehborn. 63. 194 P£tain. 130.27-30 Roosevelt.147. Hitler’s first visit. 65 Puttkamer. 73-5. 82. at Haus Wachenfeld. 171 Prague. 151-2. on Galicia. 65. 62-3. 92. 91-2. Magda Rastenburg.107 Riefenstahl. 189. 84. 128 Reiner. 83. 73-5 Portofino. 19-20. 49. 27-30. 141. secrecy.141. 117—20. 158 Schopenhauer. Franklin D.93-4. 190. 172. 198. Friedl. Kehlstein. Allied bombing at the Berghofj 172. 133 Scholter. Robert. 117—18.129.189. Paris. Paul. 109. 64. on Hider and Eva Braun.181. 101 Schmid peter. 148 Raubal. 65-7. as a resort. 1-2. period in Hider’s favour.22. 123. 192 Schlusnus. xxv. post-war career. 114. 157. recommends Manziarly join staff. Prague visit. 27. road accident. 62. 141-3. 133 Scholz. Stauffenberg bomb. xx Schmundt. Bruckner on. 161. apartment in Reich Chancellery. on Hitler’s many faces. 84-5. xxiii. 80 Picker. Mooslahner K opf tea-house. 155. moves to Berlin. 31. 142-3. life at Wehrwolf 109-16. 151-2. first direct meeting with Hider. 171. as fanatic for truth.181. schedule in Wolfsschanze. Rohm putsch. Berchtesgadener H o£ 186. letter to Nusser. Kurt von. xxvii. Franz Pfeffer von. 85. 190. 187. xxvi-xxvii.. 86. self-description. 165-6. Julius. Rohm putsch. slandered over Vierthaler. 108. Georg. 81. Hoffmann order. 70. Magda. engagement to Alkonic. xxiii-xxiv.75. 13 Reit imWinkl.52 Salomon. 188. mountain walks. 133. 89-90. xx. Wilhelm. xxix-xxx. racial views. invasion of. 129. 141. 148-51. 5 Salomon.171 Schirach. 16. 2-3. 198. Heinrich. interrogation by Albrecht. 81-2. state visit to Italy. 189. 132 Reynaud. annoys Hider. 166—7. internment. 132. 191. 128-30. 28. 41. Bechsteinhaus. 81. Leni. 179. 183 Ruhr.190. 65.61. 57. 137-8. interview at NSDAP HQ. 177. see also Berghof (FH Q ) Oberstaufen. Bormann’s farm. Hider kisses.167. xvii. Elio. Speer’s house. fondness for Bruckner. loyalty to Hider. xxviii. 85. Johann. dictation from Hitler. 22. 13. Rolf. 128-32. see Brandt. Maria. Ernst. 207 . dislike for Dara. 192 Poland. gifts from Hider. on H ider’s vegetarianism. 104. shorthand notes on Hitler. 193 as H ider’s wallet. xxv. Marion. 95-6. flight to Salzburg. as chief adjutant. Dr Emmerich. xxxii. 133 Schleicher. 54. Hider and fame. cyanide capsule. 60. 127.150 Schroeder. 15. 62. 156 Raubal. destroys Geli Raubal’s effects. 2 Salzburg. Hider visits in hospital. 151 Reiter. 2. 196. 26. 121-3.169. stays at Pension Post. Leo. 174-6. Goring’s house.189 Raubal. 145. 124 Schneider. Julius: arguments with Hoffmann. Haus Wachenfeld. 109. Hider as employer. false ID papers. stays at Pension Post. Herta. 72.INDEX Obersalzberg: Allied aircraft overfly. xvii. 17.187-8. 38-9. xx-xxi. 6.187 Quandt. 4. 120-1. Schroeder’s bag at the Fuhrer-bunker. 195. 140.144. Harry. 196 Puttkamer. 152. Angela. 156. xxi. 152. Frau. 33. coffee with Hider. xxviii-xxix. xxvi. 76. 54 Schreck. 179 Schaub. 89. 18. 59-60. Brandt on. 147. 103. in Paris. 73-4. Nelly.14. 83. Fritz von. Anni.159-60. 118-19. xv-xvi. 186. 65. journal o f art purchases.161. asks Hitler about winning war. 186. 148. 153-4. life in the Fuhrer-bunker. 55-7.188 Scholter. 69-72.30 Rohm putsch. Jesko von. 147. 132. 77. xxiii Ohnesorge. Anni Reichel. 191. Henriette von. Allied bombing.90-1. at Felsennest. 60. meals with adjutants. Angelika (‘Geli’). and Schroeder’s allowance. xxi Schirach. 160. 133n. 55. drinking at Wolfsschanze. matchmakes for Hitler. 43. 94. 102. on the Obersalzberg. invasion o f Poland. 78. 179-80. on Russians. 37. 133 Rohm. xviii-xix. 138. Rudolf. 109. 11-13. 81. Philippe.193. 158-9. 150. 160-2. 147. 156. Klaus von. reconciled with Hider. 195. B ln . as ‘degraded’.181. 80 Ribbentrop. 76-7. 43.192 Schirach. 85n. 21. Zoller’s interrogation.98 Rosenberg. xvii-xviii. see Goebbels. Baldurvon. corrects Hider. see also Wolfsschanze (FHQ) Rattenhuber. 76-7. 136 Pochmiiller. 183 Schonmann.34. 128n. on Great Britain. 99-100. 134. Joachim von. 157. Christa: aboard Hider’s train. 25. Alfred. catches Hitler out. as major war criminal. 125. and H ider’s table talks. xxvii-xxviii. on joining the Party. Hochlenzer. 28 Raubal. saves documents and sketches at the Berghofj 108. 158-60.170. 88-91. Dr. Frau von.
171 Vierthaler (friend o f Schroeder). 193 Terboven. 60 Stork.151. 145 Wagner. 99 Soviet Union.112-13. 184.133. Imam ofj 34 Yugoslavia. 23. 118.178-9. 15-16. King o f Italy. Paul. Max.1 1 9 . works in Reich Chancellery. 84. H ugh. 48. 101. D r Walter. works for NSDAP Liaison Staff. 44. 5-6 Strauss. Franz. 124 Stalingrad.102. Upper. Emmy. daily schedule. 107 Skorzeny. 51. 159.63 Vienna.128n Zoppot.194 Yemen.3 -4 . 56. 82.8 3 . see also Wehrwolf (FH Q ) Wagener. xxxi-xxxii. Zoller’s book.191 Strasser. 128. 12-13 Seitz.110-11. Emmy South America. Claus Schenk von. invasion of. 2 2 . Josefj 27.92.153. 43 Werlin. 112 Thoma. unhappiness at Wolfsschanze. Richard.84 Weser. Crown Prince o f Italy. 148-9.52. twenty-four-hour day. Schroeder’s description. 144 Thumsee.161-2. 178. 198 Windsor. see Goring. Anni.190. Winifred. 42 Stadelheim. Richard.164n. river. 70 Tivoli. 176-7. 63 Todt. preparations for Ardennes. 123 Stoeckel.117-18.107. 18 Wolf.55.118.141n Winter. Fritz. 37-8.136-9. 147. 131.121 Zaporozhye-Dnepropetrovsk.174-5.60. Sophie. telephone calls from Hitler.82. 109. Adolf. xxv-xxvi.154. 101. 192 Titian.98. jr.1 0 8 .118. Franz Xaver. succession to Hitler. Margarete (‘Gretl’). xxviii Schwarz. 50. 136 Slezak.88-90.179. 9. 70 Warsaw.19.176. 176-7. 168 Winter. 121—3 Wolzogen. 109.170 Thiess. 96-7. H A .151 Trevor Roper. 88-91.93. xxv.194 Turner. 73 Weber. 118 Zoller. 181 Tintoretto. Frank.91. 104 Traunstein. Jakob. Maxime. tea with Hitler. Paul Ludwig. 147 Wehrwolf (FH Q ).154 Troost.100. 177 Troost. Ferdinand Georg.86.87. 104. 101. 116. 38. xix. 4-5. 137.105.27.96-8. taking leave of Hitler. 25. 33. 147. Gregor.195. 12-13 Victor Emmanuel III.84. Christian. 115 Weygand.188-9.6 1 -2 . 14. 13-14. 147 Silesia.165. 73 208 . assault on Berlin. 101. 2 Singapore. 119. music at.197-8 Venice. 85 Wiinsche.83. Fraulein. Dr. 165 Speer. Mimi. 178 Spittal. 87.135 Schulze. Albert. 80 Wiedemann.130. 99 Umberto.184-5. uniform. Hider’s physicians. 31. xxv.INDEX 196-7.53.98. 109-12 Weimar.8 1 . 43. xxix.166 Wagner.104-5. xxix-xxx Zabel.46.156 Waldmiiller.43. 65 Sudetenland.165 Wolfj Johanna (Wolfen'). 185-6. 137-8. midges.106. Fritz. 86-7. 95n Schumann.17.165 Stuckart. 125. 177 Slezak.1 1 . 104. 116. 63 United States.7 . Wilhelm.62. Albert. Herr and Frau. visits H aus Wachenfeld. 3. Professor.93. 5 Ukraine. 16. Josef. 105.121. 131.128. male-dominated atmosphere. 29 Stalin.148 Wittmann. 165 Schultze. xxv. Ernst von. 165 Schwabisch Gmund. 35-6 Wurzburg. Ruchard.38. 22.95.195 Wolfsschanze (FH Q ): Allied aircraft overfly. 124. xxvi. Otto. 88.59.1 2 8 Wagner.116 Spanish Civil War.60. 95.16-17. 66-7 Wernicke. Stauffenberg bomb. works for Bruckner. 153-4. 176. 53. 2 . Gerhardine (‘Gerdy’). 18. xxi-xxii.19.166 Sonnemann. 60. 12 Vinnitsa. cinema and tea house. Dr Otto. Bormann shields Hider. 105 Stauffenberg. xxxii.120. Robert.183.69. Hugo.187. Duke and Duchess of. Leo. works for Otto Wagener. xxi-xxiii Schubert. 4 1. Dr.
the workings o f Hitler’s inner circle. one o f the most important primary sources from the pre-war and wartime period. m Frontline Books an imprint of Pen & Sword Books Limited 47 Church Street Barnsley. because he had so many. fascinating and creepy take on one o f history’s most evil men. ” T h e Sunday Telegraph “A n alternately adoring. of the artist and the barbarian. He was a mixture o f lies and truth.99 ISBN 978-1-84832-631-6 Email: info@frontline-books. ” N ew York Post. fascinating insight into Hitler and his household. and crucially into Hitler’s personality and the personalities o f those closest to him.. R O G ER M O O R H O U SE is a leading expert on the Third Reich and the author o f Killing Hitler: The Third Reich and Plots Against the Fiihrer. o f kindliness and brutality. This is. o f faithfulness and violence. Christa Schroeder was perfectly placed to observe the actions and behaviour o f Hitler. ” As secretary to the Fiihrer throughout the time o f the Third Reich. o f simplicity and luxury. It is simply impossible. without any doubt. Yorkshire. S70 2AS £12. she does not fail to deliver fascinating insights into the course o f military and political events. S.. o f mysticism and reality. clinical. 2 0 April 1939 Printed in G reat Britain 781848 326316 . M ay 2 0 0 9 “It was my mistake to assume that I could unveil the “true face”o f Adolf Hitler.com C o v er design: e-D igital D esign Front cover: Chrisra Schroeder congratulates H itler on his 50th birthday in the Reich Chancellor)'. In her compelling memoir.“Christa Schroeder provides a rare. along with the most important figures surrounding him.
|
https://www.scribd.com/document/276508999/263853067-He-was-my-chief
|
CC-MAIN-2018-51
|
refinedweb
| 86,411 | 76.42 |
PR#894 (by Dean) complains that set_last_modified() does too much,
specifically futzing with ETags. #895 (also by Dean) whinges that
Last-Modified headers emitted by scripts don't go through
conditional checks.
My first pass at this caused ETags to be generated for scripts; not
good. Alexei raised the issue (raised more than 18 months
previously) that maybe the server shouldn't be doing condition-checks
for script requests.
For the first part.. I've broken set_last_modified() into three
routines:
o set_last_modified(), which does the Right Stuff to rationalize
the time and store it in headers_out
o set_etag(), which calculates and sets the ETag in headers_out
o meets_conditions(), which checks the headers_out fields against
the requirements of the headers_in fields
I've modified the places where set_last_modified() was called to use
the new arrangement, and added a call to [the new]
set_last_modified() and meets_conditions() to util_script.c.
As for the second part: whether the server should be doing the
checks.. I think that yes, it should. If the script did it itself,
it should generate the correct status line. This patch does *not*
do the checking IFF it sees no status from the script; that it
should is just my opinion for now.
It's unclear to me if any additional kill-the-script stuff is needed
before blowing out due to a condition unmatch. Probably.. so please
treat this as a work-in-progress that will include that in a later
revision. If approved at all.
Okey, now for the obligatory forty-two messages telling me I did it
wrong and shouldn't have done it at all.. <g> But that's okey; I'm
rather in terra incognita here.
#ken :-)}
Index: core/http_core.c
===================================================================
RCS file: /export/home/cvs/apachen/src/core/http_core.c,v
retrieving revision 1.112
diff -u -r1.112 http_core.c
--- http_core.c 1997/08/18 07:19:34 1.112
+++ http_core.c 1997/08/19 20:36:05
@@ -1590,9 +1590,12 @@
return FORBIDDEN;
}
- if ((errstatus = set_last_modified (r, r->finfo.st_mtime))
- || (errstatus = set_content_length (r, r->finfo.st_size)))
- return errstatus;
+ set_last_modified(r, r->finfo.st_mtime);
+ set_etag(r, r->finfo.st_mtime);
+ if (((errstatus = meets_conditions(r)) != OK)
+ || (errstatus = set_content_length (r, r->finfo.st_size))) {
+ return errstatus;
+ }
#ifdef USE_MMAP_FILES
block_alarms();
Index: core/http_protocol.c
===================================================================
RCS file: /export/home/cvs/apachen/src/core/http_protocol.c,v
retrieving revision 1.155
diff -u -r1.155 http_protocol.c
--- http_protocol.c 1997/08/18 07:19:36 1.155
+++ http_protocol.c 1997/08/19 20:36:22
@@ -348,101 +348,117 @@
return 0;
}
-API_EXPORT(int) set_last_modified(request_rec *r, time_t mtime)
+/*
+ * Return the latest rational time from a request/mtime (modification time)
+ * pair. We return the mtime unless it's in the future, in which case we
+ * return the current time. We use the request time as a reference in order
+ * to limit the number of calls to time(). We don't check for futurosity
+ * unless the mtime is at least as new as the reference.
+ */
+API_EXPORT(time_t) rationalize_mtime(request_rec *r, time_t mtime)
{
- char *etag, weak_etag[MAX_STRING_LEN];
- char *if_match, *if_modified_since, *if_unmodified, *if_nonematch;
- time_t now;
+ time_t latest_real;
/* For all static responses, it's almost certain that the file was
* last modified before the beginning of the request. So there's
* no reason to call time(NULL) again. But if the response has been
* created on demand, then it might be newer than the time the request
* started. In this event we really have to call time(NULL) again
- * so that we can give the clients the most accurate Last-Modified.
- */
- now = (mtime <= r->request_time) ? r->request_time : time(NULL);
+ * so that we can give the clients the most accurate Last-Modified. If we
+ * were given a time in the future, we return the current time - the
+ * Last-Modified can't be in the future.
+ */
+ latest_real = (mtime < r->request_time) ? r->request_time : time(NULL);
+ return (mtime > latest_real) ? latest_real : mtime;
+}
- table_set(r->headers_out, "Last-Modified",
- gm_timestr_822(r->pool, (mtime > now) ? now : mtime));
-
- /*);
+API_EXPORT(int) meets_conditions(request_rec *r)
+{
+ char *etag = table_get(r->headers_out, "ETag");
+ char *if_match, *if_modified_since, *if_unmodified, *if_nonematch;
+ time_t mtime;
+ char *last_mtime = table_get(r->headers_out, "Last-Modified");
- /* Check for conditional requests --- note that we only want to do
+ /*
+ * Check for conditional requests --- note that we only want to do
* this if we are successful so far and we are not processing a
* subrequest or an ErrorDocument.
*
- * The order of the checks is important, since etag checks are supposed
+ * The order of the checks is important, since ETag checks are supposed
* to be more accurate than checks relative to the modification time.
+ * However, not all documents are guaranteed to *have* ETags, and some
+ * might have Last-Modified values w/o ETags, so this gets a little
+ * complicated.
*/
-
- if (!is_HTTP_SUCCESS(r->status) || r->no_local_copy)
+
+ if (!is_HTTP_SUCCESS(r->status) || r->no_local_copy) {
return OK;
+ }
- /* If an If-Match request-header field was given and
- * if our ETag does not match any of the entity tags in that field
- * and the field value is not "*" (meaning match anything), then
- * respond with a status of 412 (Precondition Failed).
- */
+ mtime = (last_mtime != NULL) ? parseHTTPdate(last_mtime) : time(NULL);
- if ((if_match = table_get(r->headers_in, "If-Match")) != NULL) {
- if ((if_match[0] != '*') && !find_token(r->pool, if_match, etag))
- return HTTP_PRECONDITION_FAILED;
+ if (etag != NULL) {
+ /*
+ * If an If-Match request-header field was given
+ * AND if our ETag does not match any of the entity tags in that field
+ * AND the field value is not "*" (meaning match anything), then
+ * respond with a status of 412 (Precondition Failed).
+ */
+
+ if ((if_match = table_get(r->headers_in, "If-Match")) != NULL) {
+ if ((if_match[0] != '*') && !find_token(r->pool, if_match, etag)) {
+ return HTTP_PRECONDITION_FAILED;
+ }
+ }
}
- /* Else if a valid If-Unmodified-Since request-header field was given
- * and the requested resource has been modified since the time
+ /*
+ * Else if a valid If-Unmodified-Since request-header field was given
+ * AND the requested resource has been modified since the time
* specified in this field, then the server MUST
- * respond with a status of 412 (Precondition Failed).
+ * respond with a status of 412 (Precondition Failed).
*/
- else if ((if_unmodified = table_get(r->headers_in, "If-Unmodified-Since"))
- != NULL) {
- time_t ius = parseHTTPdate(if_unmodified);
-
- if ((ius != BAD_DATE) && (mtime > ius))
- return HTTP_PRECONDITION_FAILED;
+ else {
+ if_unmodified = table_get(r->headers_in, "If-Unmodified-Since");
+ if (if_unmodified != NULL) {
+ = table_get(r->headers_in, "If-None-Match")) != NULL) {
- if ((if_nonematch[0] == '*') || find_token(r->pool,if_nonematch,etag))
- return (r->method_number == M_GET) ? HTTP_NOT_MODIFIED
- : HTTP_PRECONDITION_FAILED;
+ if (etag != NULL) {
+ if_nonematch = table_get(r->headers_in, "If-None-Match");
+ if (if_nonematch != NULL) {
+ int rstatus;
+
+ if ((if_nonematch[0] == '*')
+ || find_token(r->pool, if_nonematch, etag)) {
+ rstatus = (r->method_number == M_GET)
+ ? HTTP_NOT_MODIFIED
+ : HTTP_PRECONDITION_FAILED;
+ return rstatus;
+ }
+ }
}
- /* Else if a valid If-Modified-Since request-header field was given
- * and it is a GET or HEAD request
- * and the requested resource has not been modified since the time
+ /*
+ *.
@@ -452,11 +468,62 @@
table_get(r->headers_in, "If-Modified-Since")) != NULL)) {
time_t ims = parseHTTPdate(if_modified_since);
- if ((ims >= mtime) && (ims <= r->request_time))
+ if ((ims >= mtime) && (ims <= r->request_time)) {
return HTTP_NOT_MODIFIED;
+ }
}
-
return OK;
+}
+
+/*
+ * Construct an entity tag (ETag) from resource information. If it's a real
+ * file, build in some of the file characteristics. If the modification time
+ * is newer than (request-time minus 1 second), mark the ETag as weak - it
+ * could be modified again in as short an interval. We rationalize the
+ * modification time we're given to keep it from being in the future.
+ */
+API_EXPORT(void) set_etag(request_rec *r, time_t mtime)
+{
+ char *etag, weak_etag[MAX_STRING_LEN];
+
+ /*
+ *);
+}
+
+/*
+ * This function sets the Last-Modified output header field to the value
+ * passed - rationalized to keep it from being in the future.
+ */
+API_EXPORT(void) set_last_modified(request_rec *r, time_t mtime)
+{
+ time_t mod_time = rationalize_mtime(r, mtime);
+
+ table_set(r->headers_out, "Last-Modified",
+ gm_timestr_822(r->pool, mod_time));
}
/* Get a line of protocol input, including any continuation lines
Index: core/http_protocol.h
===================================================================
RCS file: /export/home/cvs/apachen/src/core/http_protocol.h,v
retrieving revision 1.26
diff -u -r1.26 http_protocol.h
--- http_protocol.h 1997/08/18 07:19:36 1.26
+++ http_protocol.h 1997/08/19 20:36:29
@@ -95,7 +95,9 @@
API_EXPORT(int) set_content_length (request_rec *r, long length);
int set_keepalive (request_rec *r);
-API_EXPORT(int) set_last_modified (request_rec *r, time_t mtime);
+API_EXPORT(time_t) rationalize_mtime(request_rec *r, time_t mtime);
+API_EXPORT(void) set_etag(request_rec *r, time_t mtime);
+API_EXPORT(void) set_last_modified(request_rec *r, time_t mtime);
/* Other ways to send stuff at the client. All of these keep track
* of bytes_sent automatically. This indirection is intended to make
Index: core/util_script.c
===================================================================
RCS file: /export/home/cvs/apachen/src/core/util_script.c,v
retrieving revision 1.69
diff -u -r1.69 util_script.c
--- util_script.c 1997/08/05 06:33:26 1.69
+++ util_script.c 1997/08/19 20:36:49
@@ -399,6 +399,24 @@
else if(!strcasecmp(w,"Transfer-Encoding")) {
table_set (r->headers_out, w, l);
}
+/*
+ * If the script gave us a Last-Modified header, run it through the checks
+ * which work against it [done in set_last_modified()]. Any conditional
+ * failures in those will cause us to bail out. Success means all the
+ * conditions were satisfied and the appropriate response header fields have
+ * been set - so we don't need to do anything else.
+ */
+ else if (!strcasecmp(w, "Last-Modified")) {
+ time_t mtime = parseHTTPdate(l);
+ int slm_status;
+
+ set_last_modified(r, mtime);
+ slm_status = meets_conditions(r);
+
+ if (slm_status != OK) {
+ return slm_status;
+ }
+ }
/* The HTTP specification says that it is legal to merge duplicate
* headers into one. Some browsers that support Cookies don't like
Index: modules/standard/mod_include.c
===================================================================
RCS file: /export/home/cvs/apachen/src/modules/standard/mod_include.c,v
retrieving revision 1.47
diff -u -r1.47 mod_include.c
--- mod_include.c 1997/08/18 13:12:13 1.47
+++ mod_include.c 1997/08/19 20:37:33
@@ -1957,13 +1957,16 @@
return FORBIDDEN;
}
+ set_last_modified(r, r->finfo.st_mtime);
+ set_etag(r, r->finfo.st_mtime);
if (*state == xbithack_full
#if !defined(__EMX__) && !defined(WIN32)
/* OS/2 dosen't support Groups. */
&& (r->finfo.st_mode & S_IXGRP)
#endif
- && (errstatus = set_last_modified (r, r->finfo.st_mtime)))
- return errstatus;
+ && ((errstatus = meets_conditions(r)) != OK)) {
+ return errstatus;
+ }
send_http_header(r);
|
http://mail-archives.apache.org/mod_mbox/httpd-dev/199708.mbox/%[email protected]%3E
|
CC-MAIN-2017-39
|
refinedweb
| 1,628 | 50.12 |
This is due in a few hours....this is the first java program I have been asked to write and I have no idea how to do it and I left my textbook in my friend's car.
I have to write a program that asks a user for their birth month, birth date, and birth year, and then tell them what day they will turn 100. This is what i have so far.
import java.util.Scanner; public class PrintBirthday { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String month; // birthday month double day; // birth day double year; //birth year double oldyear = 0; //year turning 100 System.out.print( "Enter the month you were born: "); month = stdIn.next(); System.out.print( "Enter the day you were born: "); day = stdIn.nextDouble(); System.out.print( "Enter the year you were born: "); year = stdIn.nextDouble(); oldyear += year+100; System.out.println("You will be 100 on " + month() + day() + oldyear(0)); } // end main } // end class PrintBirthday
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/11004-please-help.html
|
CC-MAIN-2015-11
|
refinedweb
| 167 | 83.36 |
React — Tips & Tricks
📄 Table of contents
- how to pass props from PARENT to CHILD in CLass vs FUnctional components
- Passing a function as a prop to a functional component
- Passing props as string or Number
- equivalent of forceUpdate() in reactHooks
- props validation
- difference between import {sthg…} vs import sthg…
- template literals usage
- how to submit form data
- handle multiple form elements with SINGLE onChange Handler
- handle multiple setStates in consecutive
- toggle a ClassName
- fetch from API via axios + hooks
- form validations
- how to format code using Prettier in visual code
- Do we need to
importReact for stateless functional components?
- What is the
index.jsfile in the component directories?
- Event handlers must always be a function or a reference to a function (with an exception).
◉ how to pass props from PARENT to CHILD in Class vs Functional components
In React, props stand for “properties” and they are the way we pass data from one React component to another.
React’s props are read-only. There is no way in React to set props (even though it was possible in the past).
However, Once the state changes, the component renders again. In addition, state can be passed as props to child components too.
Props are passed as arguments into a React component. The syntax for passing props is the same for class and functional components, but the syntax for accessing these props is different.
props can be anything from integers over objects to arrays. Even React components, but you will learn about this later. You can also define the props inline. In case of strings, you can pass props inside double quotes (or single quotes) too.
But you can also pass other data structures with inline props. In case of objects, it can be confusing for React beginners, because you have two curly braces: one for the JSX and one for the object. That’s especially confusing when passing a style object to a style attribute in React the first time.
import React, { Component } from 'react';class App extends Component {
render() {
return (
<div>
<Greeting greeting={{ text: 'Welcome to React' }} />
</div>
);
}
}const Greeting = ({ greeting }) => <h1>{greeting.text}</h1>;export default App;
Where class and functional components differ is in accessing props. In a functional component, you will see the props object as a parameter and can access it without the
this keyword. It is also best practice to
destructure the object using the
destructuring assignment syntax to make it clear what props you are expecting in the component.
function App() {
const blogPost = {
title: 'How to pass prop to components',
description: 'Your component library for ...',
};
return (
<div>
<BlogCard
title={blogPost.title}
description={blogPost.description} />
</div>
);
}
function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
more at @source: How to pass props in React (koalatea.io)
Basically, that’s how props are passed to React components.
As you may have noticed, props are only passed from top to bottom in React’s component tree. There is NO way to pass props up to a parent component.
In conclusion, every time the props or state change, the rendering mechanism of the affected component is triggered. That’s how the whole component tree becomes interactive, because after all, state is passed as props to other components, and once the state in a component changes, which may be passed as props to the child components, all affected components render again.
◉ Passing a function as a prop to a functional component
The first parameter
logThis will be
props object itself. You need to destructure the
logThis object.
const ChildComp = ({ logThis }) => (
<button onClick={() => logThis('test string')}>Click Here</button>
)
Or you can access it from
props
const ChildComp = (props) => (
<button onClick={() => props.logThis('test string')}>Click Here</button>
)
◉ Sending props as strings (instead of numbers)
React developers with experience writing a lot of HTML find it natural to write something like this:
<MyComponent value=”4” />
This value prop will actually be sent to MyComponent as a string. If you do need it as a number, you can fix this issue by using something like the
parseInt() function or inserting curly brackets instead of quotation marks.
<MyComponent value={4} />
◉ React — How to force a function component to render?
I have a function component, and I want to force it to re-render.
How can I do so?
Since there’s no instance
this, I cannot call
this.forceUpdate().
🎉 You can now, using React hooks
Using react hooks, you can now call
useState() in your function component.
useState() will return an array of 2 things:
- A value, representing the current state.
- Its setter. Use it to update the value.
Updating the value by its setter will force your function component to re-render,
just like
forceUpdate does:
◉ Prop validation
Since, Javascript is not a TYPED language there is a helpful package to validate the prop types passed into a React component, which will help when reading and debugging code.
This package is called prop-types.
Here is an example of using prop-types to validate our props.
import PropTypes from 'prop-types';function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}BlogCard.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
};
◉ difference between import {sthg…} vs import sthg…
when you are doing
export default <sthg> then while DON’T include
{}while importing the same.
When you have to export multiple <sthg> <sthg1> then don’t include
default keyword…simply
export const <sthg> <sthg1>. but while importing you will have to include
{}
Both lines are equivalent.
◉ template literal usage
console.log(`Using video device: ${videoTracks[0].label}`);console.log("Using video device: " + videoTracks[0].label);
◉ delete remote branch on git
@
Deleting a remote branch is quite different. You’ll use the git push command along with the -d flag to delete. After that, supply the name of the remote (often origin) and the branch name:
$ git push -d origin dev
To github.com:bobbykjack/sandbox.git
- [deleted] dev
◉ useState on array
@
const [optionsList, setOptionsList] = useState(["default"]);setOptionsList([...optionsList, `${videoTracks[0].label}`]);
◉ How to submit form data in React
Ref: How to submit form data in React (sebhastian.com)
<form onSubmit={handleSubmit}>
<div>
<label>Email address</label>
<input
type="email"
name="email"
placeholder="Enter email"
onChange={handleEmailChange}
value={email}
/>
</div>
<button type="submit">
Submit
</button>
</form>
you need to cancel the form submission default behavior with
preventDefault() while submitting the form via
handleSubmit here.
◉ Handling Multiple Inputs with a Single onChange Handler in React
Ref: Handling Multiple Inputs with a Single onChange Handler in React | Pluralsight
Besides handling just one input, a single
onChange handler can be set up to handle many different inputs in the form.
Logic: To handle this efficiently, we define each input with a
name prop. This matches a corresponding field in React state. In order to update that state, we use the change event’s
evt.target.name field.
In addition to getting the
value from the event target, we get the
name of that target as well. This is the essential point for handling multiple input fields with one handler. We funnel all changes through that one handler but then distinguish which input the change is coming from using the
name.
This example is using
[evt.target.name], with the name in square brackets, to create a dynamic key name in the object. Because the form
name props match the
state property keys, the
firstName input will set the
firstName state and the
lastName input will separately set the
lastName state.
Also note that, because we are using a single
state object that contains multiple properties, we're spreading (
...state) the existing state back into the new state value, merging it manually, when calling
setState. This is required when using
React.useState in the solution.
◉ handle multiple setStates in consecutive
It’s easy to forget that the state in React is asynchronous. It’s something that even the most seasoned React developers forget.
Being asynchronous means that any modifications you make don’t take effect immediately (and may take effect on the next render). React automatically batches update calls to improve performance. If you access a state value right after setting it, you might not get the most accurate result.
Let’s look at an example:
handlePetsUpdate = (petCount) => {
this.setState({ petCount });
this.props.callback(this.state.petCount); // Old value
};
You can fix this by giving an optional second parameter to
setState(), which will act as a callback function. The callback function will be called right after you update the state with your change.
handlePetsUpdate = (petCount) => {
this.setState({ petCount }, () => {
this.props.callback(this.state.petCount); // Updated value
});
};
Note: The same thing is true for
useState(), except they don’t have a similar callback argument to
setState(). Instead, you would use the
useEffect()hook to get the same result.
◉ Add Required (*) using CSS on dynamic form data
Ref: Add Required Asterisk With CSS — Paulund
But what would happen if you forget to add the asterisk after a form field or if the form is dynamically created, here is a quick tip for automatically adding a red asterisk next to required fields just by using CSS. Here is a standard HTML for creating a form field as you can see the label has a required class therefore we need to add an asterisk after this label.
<div class="form-group">
<label class="control-label required" for="username">Username</label>
<input type="text" id="username" name="data[username]" required="required" class="form-control">
</div>
Using CSS we search for all labels with a class required and use the :after pseudo class to add an asterisk and set the colour to red.
form label.required:after
{
color: red;
content: " *";
}
◉ Toggle a ClassName — the Hooks way
Ref:
Toggle between two classnames
return (
<div className={isActive ? "app" : "container"}>
...
)
Adding a classname to the existing class name
return (
<div className={`app ${isActive ? "danger" : ""}`}>
...
)
fetch data from APIs with Axios and Hooks
Ref: How to fetch data from APIs with Axios and Hooks in React — Kindacode
multiple option selection in react select
Ref:
Form Validations
Ref:
◉ How To Format Code with Prettier in Visual Studio Code
How To Format Code with Prettier in Visual Studio Code | DigitalOcean
Formatting code consistently can be a challenge, especially when working on a team. The beauty of modern-day web…
Do we need to import React for stateless functional components?
Basically, no. In the past, you had to import it but with the new React 17 update , you don’t need to import React .
Further information at : react official blog , stackoverflow
What is the index.js file in the component directories?
You may have seen a folder structure like this before :
Why we use index.js here? When we need to import a component, we could’ve done it by directly importing component.
We use index.js, because inside index.js, we can do something like this:
And when we want to import our components, we can use a syntax like this:
import {CartProduct} from './Components/Cart'
instead of
import {CartProduct} from './Components/Cart/CartProduct'
That’s because when we import a file from a directory, it tries to access index.js file by default . Basically it’s a refactoring technique to keep code simpler.
Further read: stackoverflow
Event handlers must always be a function or a reference to a function (with an exception) .
Many people often get confused on about how to use event handlers.
In the below example;
2nd and 3rd buttons won’t work because instead of passing a function or function reference, we’re passing function calls. React calls them on first render, doesn’t wait for buttons to be clicked.
But,
In the 1st example, we are passing a function reference, and in the 4th example, we’re passing a function (literally). Thus , these both work correctly.
But , there’s an exception here. Which are the functions that return functions.
Now, each button has their own handler, this is a cool trick.
|
https://anil-pace.medium.com/react-tips-tric-28cf2ad5bd7a?source=user_profile---------9-------------------------------
|
CC-MAIN-2022-05
|
refinedweb
| 1,992 | 55.13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.